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:
COUNT(1)is not faster thanCOUNT(*).- After
LEFT JOIN, count the right table's PK. DISTINCTfixes counts, notSUM.
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.