How do you select COUNT(*) combined with DISTINCT values in SQL? | A1Lab@HumairaM to SQLEnglish • 2 days ago

How do you select COUNT(*) combined with DISTINCT values in SQL?

message-square
0

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 where customer_id is NULL).
  • COUNT(DISTINCT customer_id) ignores NULLs and counts each distinct non-NULL customer_id once.

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 North has 10 completed orders placed by 4 unique customers, total_orders is 10 and distinct_buyers is 4.

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

  1. Expect higher cost on COUNT(DISTINCT ...) than COUNT(*): Counting distinct values often requires sorting or hashing to deduplicate values, whereas COUNT(*) can often scan a compact nonclustered index or count rows quickly.
  2. Watch for NULL behavior: Both COUNT(*) and COUNT(col) count rows differently around NULLs—COUNT(*) includes NULL rows, while COUNT(DISTINCT col) excludes NULLs.
  3. Avoid COUNT(DISTINCT ...) inside window functions: Most SQL engines (including SQL Server) do not allow COUNT(DISTINCT col) OVER (...) directly; compute distinct counts via a CTE, derived table, or GROUP BY first.
  4. Use HAVING for post-aggregation filters: Filter on COUNT(*) or COUNT(DISTINCT col) using HAVING (such as HAVING COUNT(DISTINCT customer_id) >= 5), not WHERE.