A table contains duplicate and NULL email values. How will COUNT(*), COUNT(email), and COUNT(DISTINCT email) differ?
Interview preparation resource from Gate Smashers.
COUNT(*) counts all rows; COUNT(email) counts only non-NULL email values; COUNT(DISTINCT email) counts unique non-NULL email values.
SELECT COUNT(*) AS total_rows,
COUNT(email) AS non_null_emails,
COUNT(DISTINCT email) AS unique_non_null_emails
FROM Customers;Direct answer
COUNT(*) counts rows in the result set. COUNT(email) counts only non-NULL values in the email column. COUNT(DISTINCT email) counts unique non-NULL email values (duplicates removed).
- **COUNT(*):** Counts every row, regardless of column values or NULLs.
- COUNT(email): Counts only non-NULL email entries; ignores NULLs.
- COUNT(DISTINCT email): Counts distinct (unique) non-NULL email values; duplicates are removed before counting.
How each function works
COUNT(*) does not inspect any particular column
it simply counts result rows. Aggregate functions that take a column as an argument ignore NULL values for that column. DISTINCT removes duplicate non-NULL values before the aggregate is applied.
NULL and duplicate handling
NULL values are ignored by column-based aggregates (so COUNT(email) and COUNT(DISTINCT email) do not count NULLs). Duplicate non-NULL email values are counted by COUNT(email) but are removed by COUNT(DISTINCT email), so only unique non-NULL emails contribute to the DISTINCT count.
Example query
The following query shows all three counts together; aliases label each result column for clarity. The actual SQL is provided below in the code block.
