Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 22/ 160
02. Aggregations, Functions & Data Manipulation

COUNT(*) vs COUNT(column) vs COUNT(DISTINCT column)

Know which COUNT variant ignores NULLs and when DISTINCT changes the answer.

BeginnerCOUNT(*) · COUNT(column)3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

COUNT(*) counts every row, COUNT(column) skips blanks, and COUNT(DISTINCT column) counts each different value once.

Think of it like…

A class register: COUNT(*) is how many names are on the list, COUNT(phone) is how many students gave a phone number, and COUNT(DISTINCT city) is how many different cities they come from.

Where you’ve seen it

A signups table with 1,000 rows, 800 emails filled in, and 760 unique emails: COUNT(*) = 1,000, COUNT(email) = 800, COUNT(DISTINCT email) = 760. Each answers a different business question.

Words you’ll hear

COUNT(*)
Number of rows, including rows full of NULLs.
COUNT(column)
Number of rows where that column is not NULL.
COUNT(DISTINCT column)
Number of different non-NULL values.
COUNT(1)
Exactly the same as COUNT(*); not faster.

Visual diagram

Loading interactive diagram

Theory & example queries

What each variant counts

COUNT(*) counts rows, regardless of their contents. COUNT(expr) evaluates the expression for each row and counts the non-NULL results. COUNT(DISTINCT expr) removes duplicates first, then counts the remaining non-NULL values.

COUNT(1), COUNT('x') and COUNT(*) all count rows, because the constant is never NULL. Modern optimizers treat them identically, so the idea that COUNT(1) is faster is a myth. Unlike SUM, AVG and MAX, COUNT over zero rows returns 0, not NULL.

Three metrics in one passQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  COUNT(*) AS signups,3  COUNT(email) AS with_email,4  COUNT(DISTINCT email) AS unique_emails5FROM6  signups;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output1 sample row
Expected output
signupswith_emailunique_emails
1000940917

Note: Illustrative counts: 60 NULL emails and 23 repeated non-NULL email values are excluded by the respective COUNT rules.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Rows, non-NULL values, distinct non-NULL values.

Counting after joins, and the cost of DISTINCT

After customers LEFT JOIN orders, a customer with no orders still produces one row, so COUNT(*) gives them 1 order. COUNT(o.id) gives 0 because o.id is NULL on that row. Always count the key of the table whose rows you mean.

COUNT(DISTINCT) has to remember every value it has seen, so on large data it's much more expensive than COUNT(*). For dashboards over billions of rows, analytical engines offer approximate versions such as APPROX_COUNT_DISTINCT (BigQuery, Snowflake) that use HyperLogLog. In PostgreSQL, an exact COUNT(*) on a huge table needs a full scan; pg_class.reltuples gives a fast estimate.

Orders per customer, including zeroQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  c.id,3  COUNT(o.id) AS orders4FROM5  customers c6  LEFT JOIN orders o ON o.customer_id = c.id7GROUP BY8  c.id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
idorders
13
20
37
41

Note: Illustrative customers; COUNT(o.id) remains 0 for customer 2 because the unmatched order side contains NULL.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Count the key of the table you mean; DISTINCT costs memory.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Question

Say what you're counting

Rows (signups), filled-in values (signups with an email) or different values (unique emails)? The wording decides the function.

SQL at this stepReadable preview
1rows · non-NULL · distinct
What to watch at this step
Decide
before writing SQL
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

**COUNT(*) counts rows. COUNT(column) counts rows where that column is not NULL. COUNT(DISTINCT column)** counts the different non-NULL values. On the same data they can give three different answers.

Why it matters: Picking the wrong one quietly changes a metric: "number of users" vs "number of users with an email" vs "number of distinct emails". It also matters after joins, where COUNT(*) counts NULL-padded rows that COUNT(column) ignores.

When to reach for it

  • COUNT(*) for volume metrics
  • COUNT(column) for data-completeness checks and counts after LEFT JOIN
  • COUNT(DISTINCT user_id) for unique users or active users

When to avoid or be careful

  • COUNT(*) after a LEFT JOIN when you mean "related rows"
  • COUNT(DISTINCT) over billions of rows when an approximate count would do
  • Assuming COUNT(1) is faster than COUNT(*)

COUNT(*) vs COUNT(column) vs COUNT(DISTINCT column)

COUNT(*)
Best for: Number of rows: signups, orders, events

Strengths: Fastest and unambiguous.

Watch out: Counts NULL-padded rows after outer joins.

COUNT(column)
Best for: How many rows have a value filled in

Strengths: Ignores NULLs automatically, which makes it correct after LEFT JOIN when you count the right table's key.

Watch out: Easy to confuse with a row count when the column is nullable.

COUNT(DISTINCT column)
Best for: Unique users, unique products, unique values

Strengths: Counts each value once.

Watch out: Expensive on large data; still ignores NULLs.

Interview signals & numbers to know

When this topic comes up

  • “How many unique users?”
  • “COUNT(*) vs COUNT(column)”
  • “Why is the count too high after the join?”
  • Data completeness
  • Daily or monthly active users

Benchmarks & rules of thumb

0 -
COUNT over an empty set
NULL -
SUM over an empty set
COUNT(1) -
identical to COUNT(*)

Common mistakes & follow-ups

Common interview mistakes

  • Using COUNT(*) after a LEFT JOIN and reporting 1 order for customers who have none.
  • Counting COUNT(email) and calling it the number of users.
  • Expecting COUNT(DISTINCT col) to count NULL as a value.

Likely interviewer follow-ups

  • What does COUNT(DISTINCT col) return when every value is NULL?
  • How would you count distinct combinations of two columns?
  • How would you count rows matching a condition without a WHERE clause, in the same query as other counts?
Interview tip: Use one tiny example (a, a, b, NULL, NULL) and give all three answers: 5, 3, 2. It's faster and clearer than three definitions.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply COUNT(*) vs COUNT(column) vs COUNT(DISTINCT column) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Aggregate Functions (COUNT, SUM, AVG, MIN, MAX)
Next topic
Grouping Data with GROUP BY (Single & Multiple Columns)