Question presented to candidate:
"On our visits table, COUNT(*), COUNT(user_id) and COUNT(DISTINCT user_id) give three different numbers. Explain what each one counts, and tell me which one you would use for 'visits per user' in a report that LEFT JOINs users to visits."
What a strong answer should cover:
COUNT(*)counts rows, whatever they contain;COUNT(col)counts rows wherecolis not NULL;COUNT(DISTINCT col)counts distinct non-NULL valuesCOUNT(1)andCOUNT(*)are the same thing; neither is faster in a meaningful way- The LEFT JOIN trap:
COUNT(*)counts the NULL-padded row, so a user with no visits shows 1; count a column of the right-hand table instead - Counting distinct combinations: standard SQL has no multi-column
COUNT(DISTINCT a, b); use a subquery withSELECT DISTINCT a, b, a row value in PostgreSQL, or MySQL's extension; beware the concatenation trick and NULLs - Cost:
COUNT(DISTINCT)needs a sort or hash of all values;COUNT(*)on PostgreSQL still scans the table because of MVCC
Code / implementation expected: Yes β the three counts side by side, and the LEFT JOIN per-user count.
Schema used by the examples: