SteelReed

Search

Search posts, questions…

SQL & Query TuningQuestion 8 / 37

Junior

How do COUNT(*), COUNT(col) and COUNT(DISTINCT col) differ, especially after a LEFT JOIN?

Short answer

COUNT(*) counts every row, COUNT(col) counts only rows where col is not NULL, COUNT(DISTINCT col) counts distinct values. Column x holds 1, NULL, 1:

Expression Result Why
COUNT(*) 3 Counts every row
COUNT(x) 2 Skips the NULL row
COUNT(DISTINCT x) 1 Only one distinct value

3 points to say:

  1. COUNT(1) is not faster than COUNT(*).
  2. After LEFT JOIN, count the right table's PK.
  3. DISTINCT fixes counts, not SUM.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.