Aggregations & Grouping
Summarize data with COUNT, SUM, AVG, MIN, MAX, GROUP BY, and the post-aggregation HAVING filter.
Core Learning Objectives
- •Understand the crucial distinction between WHERE (pre-aggregation) and HAVING (post-aggregation)
- •Handle NULL values gracefully inside COUNT(*) vs COUNT(column)
- •Perform multi-column aggregations and conditional counts using CASE WHEN
Interactive Cheatsheet
PostgreSQL SyntaxSELECT department_id, COUNT(*) AS employee_count, AVG(salary) AS avg_salary FROM employees WHERE is_active = TRUE GROUP BY department_id HAVING AVG(salary) > 85000;
Curated Practice Problems (3)
Movie Duration 90th Percentile
Netflix wants to evaluate content pacing across genres. For each genre that has at least 3 movies, calculate the 90th percentile duration (in minutes). Write a query to output: - `genre` - `p90_duration` (rounded to nearest integer) Order by `p90_duration` descending. Table: - `movies` (`movie_id` INT, `title` VARCHAR, `genre` VARCHAR, `duration_minutes` INT)
User Direct Message Volume & Word Counts
Meta Messenger team is analyzing user communication frequency. Write a SQL query to calculate: 1. `sender_id` 2. Total messages sent (`total_messages`) 3. Total words sent across all messages (`total_words`) 4. Average words per message rounded to 1 decimal place (`avg_words_per_message`) Only include users who sent at least 3 messages. Sort by `total_words` descending. Tables: - `messages` (`message_id` INT, `sender_id` INT, `receiver_id` INT, `word_count` INT, `sent_time` TIMESTAMP)
High-Dispute Merchant Chargeback Thresholds
Stripe's Risk team monitors merchants whose chargeback dispute rate exceeds regulatory caps. Write a SQL query to identify all merchants with at least 5 processed charges whose dispute rate is strictly greater than 20.0%. Return `merchant_id`, total charges (`total_charges`), disputed charges (`disputed_charges`), and the dispute percentage rounded to 2 decimals (`dispute_pct`). Sort by `dispute_pct` descending. Tables: - `charges` (`charge_id` INT, `merchant_id` INT, `amount` DECIMAL, `is_disputed` BOOLEAN)