SQL WITH clause (CTE)
A Common Table Expression (CTE) names a subquery with WITH, so you can build a query in readable steps. Analysts use CTEs constantly, and interviewers love them.
You can chain several CTEs, separated by commas, and each can use the ones before it.
Syntax
WITH step1 AS ( SELECT ... ), step2 AS ( SELECT ... FROM step1 ) SELECT * FROM step2;
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
Examples
1. Spend per customer
WITH spend AS (SELECT o.customer_id, SUM(oi.quantity * oi.unit_price) AS total FROM orders o JOIN order_items oi ON oi.order_id = o.id GROUP BY o.customer_id) SELECT customer_id, total FROM spend ORDER BY total DESC LIMIT 5;
Top 5 customers by spend.
Common mistakes
- Putting a comma after the last CTE before the final SELECT.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
Using a WITH clause, find customers whose total spend on orders not cancelled is over 1000. Return customer_id and total_spent (rounded to 2 decimals).
FAQ
Is a CTE faster than a subquery?
In modern PostgreSQL they are usually optimised the same way. Choose CTEs for readability.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.