1. Home
  2. Data Science
  3. SQL for Data Analysis
  4. Counting customers by joining customers to orders and…

Added 30 Nov -0001

Counting customers by joining customers to orders and using COUNT(*) inflates the number. Why, and what fixes it?

  1. Because COUNT(*) ignores NULLs in the customer key, so rows with a missing key are never counted at all by the aggregate
  2. The one-to-many join repeats each customer row per order, so COUNT(DISTINCT customer_id) or a subquery gives the true count Correct answer
  3. Because the join sorts the rows and duplicates them during the sort, so the sort key must therefore be made distinct first of all
  4. Because COUNT(*) counts columns rather than rows, so it returns the width of the joined result instead of its height

Correct answer

B. The one-to-many join repeats each customer row per order, so COUNT(DISTINCT customer_id) or a subquery gives the true count

15 views

MCQSEXAM

Explanation

Join fan-out multiplies rows: a customer with five orders appears five times, so counting rows counts orders rather than customers. COUNT(DISTINCT c.customer_id) collapses the duplicates, and aggregating orders in a subquery before joining avoids the multiplication entirely. Checking that the join key is unique on one side, ideally with a declared key or unique index, prevents the mistake.

Reference

Asked in: NTS, PPSC IT, Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More SQL for Data Analysis MCQs

Practise all SQL for Data Analysis MCQs

Similar MCQs