SQL
Perform Conditional Counting with CASE WHEN in SQL
Create dynamic summary reports by counting records based on specific conditions within a single SQL query using CASE WHEN expressions.
SELECT
product_category,
COUNT(CASE WHEN status = 'completed' THEN 1 END) AS completed_orders,
COUNT(CASE WHEN status = 'pending' THEN 1 END) AS pending_orders,
COUNT(*) AS total_orders
FROM
orders
GROUP BY
product_category;
How it works: This query demonstrates conditional aggregation using the `CASE WHEN` statement within the `COUNT()` function. It allows you to count items that meet specific criteria (e.g., 'completed' or 'pending' orders) as separate columns in a single query, grouped by a dimension like 'product_category'. This is very powerful for generating summary reports.