Break complex database queries into clean, maintainable modular pipelines. Calculate quarterly logo churn rates, net expansion bridges, and recursive organizational tree hierarchies with PostgreSQL CTEs.
Key patterns and rules practiced in this track.
Creates named temporary result sets that exist only within the execution of the query. Improves readability over nested subqueries.
WITH step_one AS (SELECT ...), step_two AS (SELECT ...) SELECT * FROM step_twoWITH active_cohort AS (SELECT user_id, signup_date FROM users WHERE status = 'active'), order_summary AS (SELECT user_id, COUNT(*) AS orders FROM purchases GROUP BY user_id) SELECT a.user_id, COALESCE(o.orders, 0) FROM active_cohort a LEFT JOIN order_summary o ON a.user_id = o.user_id;
Executes an initial anchor query and repeatedly joins against itself until no new rows are generated. Ideal for organizational trees and bill-of-materials.
WITH RECURSIVE hierarchy AS (anchor_query UNION ALL recursive_query) SELECT * FROM hierarchyWITH RECURSIVE org_tree AS (SELECT emp_id, name, manager_id, 1 AS depth FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.emp_id, e.name, e.manager_id, o.depth + 1 FROM employees e JOIN org_tree o ON e.manager_id = o.emp_id) SELECT * FROM org_tree;
Isolates starting and ending state snapshots to compute net retention, upgrades, downgrades, and logo churn.
WITH mrr_start AS (...), mrr_end AS (...) SELECT ...WITH account_changes AS (SELECT account_id, old_mrr, new_mrr, (new_mrr - old_mrr) AS delta FROM subscription_events) SELECT SUM(delta) FILTER (WHERE delta > 0) AS expansion_mrr, SUM(ABS(delta)) FILTER (WHERE delta < 0) AS contraction_mrr FROM account_changes;
Click any problem to open the interactive editor.
Single row summary with total_accounts, churned_accounts, and churn_rate_pct.
Single row summary showing new_mrr, expansion_mrr, contraction_mrr, and net_new_mrr.
Summary with total_customers, repeat_customers, and repeat_rate_pct within 30 days.
Single row summary showing total discharges, readmissions within 30 days, and readmission rate percentage.
Summary of client count and total assets grouped by wealth tier.
Employee hierarchy showing reporting depth distance from the executive level.
Summary of stops, total driving time, and shift violation status per route.
Power users utilizing at least 3 distinct modules and logging >= 10 actions.
Customer lifetime spend with quartile segmentation.
Surgical rooms with total surgery minutes and utilization percentage.
Monthly paydown schedule showing remaining loan balance after 4 periods.
At-risk inventory items with 10 or fewer days of remaining stock.
Run queries directly in your browser against realistic tables.