In SQL, you combine total row counts and unique-value counts in the same query by placing COUNT(*) alongside COUNT(DISTINCT column_name) (or COUNT(DISTINCT expr)) inside a SELECT statement. COUNT(*) counts all rows (including NULLs and duplicates), whereas COUNT(DISTINCT column_name) counts unique non-NULL values of that column—often paired with GROUP BY to compute both metrics per category or group.
1. Combining COUNT(*) and COUNT(DISTINCT col) in One Query
Use both aggregate functions side by side when you want total volume and unique entity counts together.
SELECT
COUNT(*) AS total_rows,
COUNT(DISTINCT customer_id) AS unique_customers,
COUNT(DISTINCT order_date) AS active_days
FROM dbo.orders;
COUNT(*)returns every row matching the query (including rows wherecustomer_idisNULL).COUNT(DISTINCT customer_id)ignoresNULLs and counts each distinct non-NULLcustomer_idonce.
2. Grouping by a Column (GROUP BY) to Compare Totals vs. Uniques
Pairing COUNT(*) and COUNT(DISTINCT col) with GROUP BY shows how many total events occur per group versus how many distinct subjects/items are involved.
SELECT
region,
COUNT(*) AS total_orders,
COUNT(DISTINCT customer_id) AS distinct_buyers,
SUM(total_amount) AS gross_sales
FROM dbo.orders
WHERE status = 'COMPLETED'
GROUP BY region
ORDER BY gross_sales DESC;
- If
Northhas 10 completed orders placed by 4 unique customers,total_ordersis10anddistinct_buyersis4.
3. Counting Distinct Combinations Across Multiple Columns
Standard SQL COUNT(DISTINCT col1, col2) is not supported in all engines (for example, SQL Server / T-SQL requires a single expression inside COUNT(DISTINCT ...)). To count unique combinations across multiple columns reliably across SQL Server and other SQL dialects, concatenate with a delimiter or use a subquery / GROUP BY:
-- Portable approach using a subquery or CTE (works in SQL Server, PostgreSQL, MySQL, Oracle)
WITH distinct_pairs AS (
SELECT DISTINCT
customer_id,
product_id
FROM dbo.order_items
)
SELECT
COUNT(*) AS distinct_customer_product_pairs
FROM distinct_pairs;
- Avoid concatenating strings without a separator (such as
col1 + col2) because'a' + 'bc'and'ab' + 'c'would collide into'abc'.
4. High-Cardinality / Large Table Performance Tips
- Expect higher cost on
COUNT(DISTINCT ...)thanCOUNT(*): Counting distinct values often requires sorting or hashing to deduplicate values, whereasCOUNT(*)can often scan a compact nonclustered index or count rows quickly. - Watch for
NULLbehavior: BothCOUNT(*)andCOUNT(col)count rows differently aroundNULLs—COUNT(*)includesNULLrows, whileCOUNT(DISTINCT col)excludesNULLs. - Avoid
COUNT(DISTINCT ...)inside window functions: Most SQL engines (including SQL Server) do not allowCOUNT(DISTINCT col) OVER (...)directly; compute distinct counts via a CTE, derived table, orGROUP BYfirst. - Use
HAVINGfor post-aggregation filters: Filter onCOUNT(*)orCOUNT(DISTINCT col)usingHAVING(such asHAVING COUNT(DISTINCT customer_id) >= 5), notWHERE.
