SQL LEARNING PLATFORM
Named subqueries that make complex logic readable.
Learning Blocks
Interactive Queries
Concepts you'll master
Defining a CTE with WITH ... AS (...)
Using multiple CTEs in sequence
Recursive CTEs for hierarchical data
CTE vs subquery — when to use each
WITH dept_avg AS (
SELECT department, AVG(salary) AS avg_sal
FROM employees
GROUP BY department
)
SELECT e.name, e.salary, d.avg_sal,
e.salary - d.avg_sal AS diff
FROM employees e
JOIN dept_avg d ON e.department = d.department
ORDER BY e.department, diff DESC;WITH
order_totals AS (
SELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent
FROM orders GROUP BY customer_id
),
customer_tier AS (
SELECT customer_id, spent,
CASE WHEN spent > 100000 THEN 'VIP'
WHEN spent > 10000 THEN 'Regular'
ELSE 'New' END AS tier
FROM order_totals
)
SELECT c.name, t.spent, t.tier
FROM customers c
JOIN customer_tier t ON c.customer_id = t.customer_id
ORDER BY t.spent DESC;✅ Pro Tips: Rule of thumb: if you need to reference the same subquery twice, use a CTE. If a subquery is used once and is simple, inline it. If it is used 3+ times, consider a view or temp table.
💡 Engineering Insight: CTEs do not always improve performance — in some databases they are materialised (computed once and cached), in others they are inlined as subqueries. PostgreSQL inlines by default; you can force materialisation with the MATERIALIZED keyword. Always check your EXPLAIN plan.
Practice your SQL skills