Retail · SQL
Resolving a three-way customer count conflict with a single self-documenting SQL query
Independent grading: 97/100(verify, opens in a new tab)
Problem
Chidi Okafor at Meridian Retail (simulated retailer) was receiving three different customer totals from three internal teams and needed one defensible number for an upcoming investor meeting. The specific question was which of the figures, 2,331, 2,131, or 2,105, was correct, and why the others differed.
What I did
Using COUNT(*) with conditional FILTER clauses reproduces all three counting methodologies in a single pass over retail.customers, so the relationship between the figures is arithmetically transparent in one result row. The FILTER (WHERE is_duplicate = FALSE) isolates non-duplicate records for the operations count, and adding AND total_orders > 0 to that filter replicates finance's stricter rule. Embedding the recommendation as a string literal in a chidi_recommendation column makes the query self-documenting, the output tells Chidi what number to use and why without a separate write-up.
Finding
The three counts are 2,331 (all records), 2,131 (non-duplicates), and 2,105 (non-duplicates with at least one order placed), with 2,131 identified as the correct figure for the investor context.
Outcome
Chidi received a single query result containing all three counts, a clear label identifying the correct investor-facing figure, and the logical basis for why the other two differ.
SELECT COUNT(*) AS marketing_count, COUNT(*) FILTER (WHERE is_duplicate = FALSE) AS operations_count, COUNT(*) FILTER ( WHERE is_duplicate = FALSE AND total_orders > 0 ) AS finance_count, '2,131 operations_count represents unique, non-duplicate customers.' AS chidi_recommendation FROM retail.customers;
The FILTER clauses apply row-level conditions to COUNT without affecting the FROM clause, so all three counts are produced from one table scan and remain directly comparable.
Next step
A follow-on query breaking the 26 non-duplicate zero-order customers down by acquisition source and signup date would help Chidi decide whether those customers are recent signups who may still convert or long-inactive accounts that should be removed from forecasts.
- FILTER clause on COUNT for conditional aggregation
- WHERE clause deduplication filtering
- Self-documenting aliasing and inline result annotation
- GROUP BY with COUNT(*) for frequency distribution