Advanced SQL Patterns
Master conditional aggregation with CASE WHEN, date/timestamp arithmetic, NULL handling, and regex string manipulation.
Core Learning Objectives
- •Write multi-condition CASE WHEN expressions for business bucketing and pivoting
- •Perform PostgreSQL interval arithmetic using EXTRACT(EPOCH FROM ...) and DATE_TRUNC
- •Cleanse messy strings and handle NULLs with COALESCE and NULLIF
Interactive Cheatsheet
PostgreSQL SyntaxSELECT user_id, COUNT(CASE WHEN status = 'completed' THEN 1 END) AS completed_orders, ROUND(EXTRACT(EPOCH FROM (delivered_at - ordered_at)) / 3600.0, 1) AS hours_taken FROM orders GROUP BY user_id;
Curated Practice Problems (2)
Weekend vs. Weekday Engagement Split
Meta's Instagram engagement team wants to compare user posts published on Weekends (Saturday, Sunday) versus Weekdays (Monday - Friday). Write a SQL query using `CASE WHEN` and PostgreSQL `EXTRACT(ISODOW FROM ...)` or `TO_CHAR` to calculate: - `user_id` - `weekday_posts` (count of posts created Monday through Friday) - `weekend_posts` (count of posts created Saturday or Sunday) - `pct_weekend_posts` (percentage of total posts on weekends, rounded to 1 decimal place) Only include users who published at least 3 total posts. Order by `pct_weekend_posts` descending. Tables: - `posts` (`post_id` INT, `user_id` INT, `post_timestamp` TIMESTAMP)
Prime 24-Hour Guaranteed Delivery SLA Breaches
Amazon Logistics monitors fulfillment performance against Prime 24-hour delivery SLAs. Write a SQL query to identify all orders where actual delivery time exceeded order placement time by more than 24.0 hours. Calculate: - `order_id` - `customer_id` - `hours_to_deliver` (rounded to 1 decimal place) - `breach_severity` categorizing delay: - 'Moderate Breach' if between 24.1 and 36.0 hours - 'Severe Breach' if greater than 36.0 hours Order by `hours_to_deliver` descending. Tables: - `fulfillment_orders` (`order_id` INT, `customer_id` INT, `ordered_at` TIMESTAMP, `delivered_at` TIMESTAMP)