CTEs with WITH
SQL · 14 questions
Short notes
Key idea
A CTE (WITH ... AS) names a subquery and puts it at the top, so the query reads in steps, top to bottom. Each step can use the ones before it.
Syntax
WITH step1 AS (
SELECT ...
),
step2 AS (
SELECT ... FROM step1
)
SELECT * FROM step2;
One WITH, steps separated by commas, then the final SELECT.
Example
Customers whose spending is above the average customer's:
WITH spend AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT customer_id, total
FROM spend
WHERE total > (SELECT AVG(total) FROM spend);
The same CTE is used twice, which a plain subquery couldn't do without repeating itself.
Traps
- Only one
WITH. WriteWITH a AS (...), b AS (...), not a secondWITH. - No comma before the final
SELECT. - A CTE lives only for its one query. It isn't a saved table.
- Check each step by running
SELECT * FROM step1on its own while you build.
Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →
- Question 1easy
Which is the correct way to define two CTEs?
- Question 2medium
You define a CTE called
recent_ordersin one query. Can a second, separate query use it? - Question 3medium
What does this return?
WITH per_customer AS ( SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id ), loyal AS ( SELECT * FROM per_customer WHERE n >= 3 ) SELECT COUNT(*) FROM loyal;
- Question 4medium
What does this return?
WITH per_customer AS ( SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id ) SELECT MAX(n) FROM per_customer;
- Question 5hard
No orders were placed in October 2024. What is
ordersfor October in this result?WITH RECURSIVE months AS ( SELECT DATE '2024-09-01' AS month UNION ALL SELECT month + INTERVAL 1 MONTH FROM months WHERE month < DATE '2024-11-01' ), counts AS ( SELECT date_trunc('month', order_date) AS month, COUNT(*) AS orders FROM orders GROUP BY month ) SELECT COALESCE(c.orders, 0) AS orders FROM months m LEFT JOIN counts c ON c.month = m.month WHERE m.month = DATE '2024-10-01';
CTEs with WITH
CTEs with WITH
CTEs with WITH
CTEs with WITH
CTEs with WITH
9 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.