Conditional Aggregation: Data Pivoting & Crosstab Reporting
Relational databases store transactional data vertically (normalized rows). However, business analysts and financial controllers want to see reports formatted horizontally (pivot tables / crosstabs): displaying sales by month across columns (Jan, Feb, Mar), or counting orders by status horizontally (Pending, Shipped, Delivered).
While MySQL does not have a dedicated PIVOT keyword like SQL Server, you can achieve world-class data pivoting using Conditional Aggregation (embedding CASE expressions inside aggregate functions like SUM() and COUNT()).
1. The Concept of Data Pivoting
1 NORMALIZED VERTICAL DATA:
2 year | quarter | revenue
3 2026 | Q1 | 150000.00
4 2026 | Q2 | 180000.00
5 2026 | Q3 | 210000.00
6 2026 | Q4 | 250000.00
7
8 PIVOTED HORIZONTAL REPORT (Columns created from row values!):
Do Not Use COUNT(CASE WHEN cond THEN 0 END): A common beginner bug! If you write COUNT(CASE WHEN status = 'Paid' THEN 1 ELSE 0 END), MySQL counts both 1 and 0 because 0 is a non-null value! Always use ELSE NULL (or omit ELSE) with COUNT(), or use SUM() with ELSE 0.
Performance Benefits: Conditional aggregation computes multiple metrics across an entire table in a single table scan, replacing what would otherwise require 5 or 6 separate join queries!
Interactive Quiz• Knowledge Check
Multiple Choice Questions
Question 1
What is "Conditional Aggregation" in relational SQL?
Question 2
Why does COUNT(CASE WHEN status = 'Shipped' THEN 1 ELSE 0 END) fail to count only shipped orders accurately?
Question 3
Which construct correctly sums sales revenue strictly for the month of January in a pivoted yearly report?
Question 4
What is the primary performance advantage of conditional aggregation over joining multiple filtered subqueries?
Question 5
In a pivoted query calculating cancellation rates, what function prevents a division by zero error if COUNT(order_id) is 0?
Next Lesson
Advanced Null Handling with NULLIF & COALESCE
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.