CAB206 · Unit 3: OLAP and SQL for BI
SQL aggregation, joins and NULL handling for reports
9 practice questions
Key points
- COUNT(*) vs COUNT(col) vs COUNT(DISTINCT col)
- Aggregates ignore NULL; AVG divides by non-NULL count
- WHERE filters rows, HAVING filters groups
- WHERE on the right table turns LEFT JOIN into inner join
- Missing join condition gives a Cartesian product
Most BI reports are SQL aggregations over joined tables.
Aggregates and NULLs
COUNT(*)counts rows;COUNT(col)counts non-NULL values;COUNT(DISTINCT col)counts distinct non-NULL values.SUM,AVG,MIN,MAXignore NULLs.AVGdivides by the number of non-NULL values; useAVG(COALESCE(x,0))if NULL should count as zero.SUMof no rows (or only NULLs) is NULL, not 0.NULL = NULLis not true. UseIS NULL/IS NOT NULL. A comparison such asamount <> 100also excludes NULL rows.
WHERE vs HAVING. WHERE filters rows before grouping; HAVING filters groups after aggregation.
Joins
INNER JOIN: only matching rows.LEFT JOIN: all rows from the left table, with NULLs where the right has no match.- A filter on the right table placed in
WHEREremoves the NULL rows and silently turns a LEFT JOIN into an inner join. Put the condition in theONclause to keep unmatched left rows. - A join without a join condition produces a Cartesian product (3 x 2 = 6 rows).
- Joining to a table with duplicate keys multiplies rows (fan-out) and inflates SUMs.
Conditional aggregation with CASE WHEN inside SUM or COUNT builds pivot-style columns in a single query.
Try two questions
Using customers LEFT JOIN orders with the data above, grouped by name with SUM(amount), what is Meena's total?
- Meena is omitted from the result
- NULL
- 50
- 0
Show the answer
B. Meena has no matching orders so the group's only amount is NULL, and SUM of only NULLs is NULL, not 0.
An orders table has 4 rows and amounts 100, 200, NULL, 50. What does COUNT(amount) return?
- 0
- 2
- 3
- 4
Show the answer
C. COUNT(column) ignores NULLs, so only 100, 200 and 50 are counted. COUNT(*) would return 4.