CTEs — Common Table Expressions
Write cleaner, more readable complex queries using WITH
✅ What You Will Learn
A CTE (Common Table Expression) is a named temporary result set defined at the start of a query using the WITH keyword. Think of it as giving a subquery a name so you can reference it clearly, multiple times if needed.
CTEs make complex queries dramatically easier to read and debug. Instead of nesting subqueries inside each other, you build the result step by step — each step has a clear name. Senior analysts use CTEs in almost every complex query they write.
📋 CTEs break complex queries into named steps using this orders table
| order_id | customer_name | product | amount | city |
|---|---|---|---|---|
| 1001 | Rahul Sharma | Laptop | 45000 | Delhi |
| 1002 | Priya Verma | Mobile Phone | 18000 | Noida |
| 1003 | Amit Kumar | Headphones | 3500 | Gurgaon |
| 1004 | Sneha Kapoor | Laptop | 52000 | Delhi |
| 1005 | Vikram Singh | Tablet | 28000 | Noida |
| 1006 | Neha Joshi | Laptop | 48000 | Delhi |
Syntax
Examples
📌 Key Points to Remember
- ✓CTEs start with WITH and are defined before the main SELECT
- ✓Multiple CTEs are separated by commas
- ✓A CTE can reference a previous CTE defined in the same WITH block
- ✓CTEs are not stored — they only exist for the duration of the query
- ✓Use CTEs whenever a query has more than two levels of nesting
🏢 Real-World Application
CTEs are the professional way to write complex SQL queries. Without CTEs, a multi-step analysis becomes an unreadable mess of nested subqueries. With CTEs, you break the problem into named steps: WITH monthly_revenue AS (GROUP BY month), top_months AS (filter from monthly_revenue), final AS (join with targets) — each step is clear and testable. Data engineers at companies like Razorpay, CRED, and MakeMyTrip write production SQL using CTEs extensively. Recursive CTEs are used for hierarchical data — org charts, bill of materials, category trees. Mastering CTEs is a sign of SQL maturity.
⚠️ Common Mistakes to Avoid
❓ Frequently Asked Questions
What is a CTE in SQL?
CTE stands for Common Table Expression. It is a named temporary result set defined with the WITH clause before a SELECT statement. CTEs make complex queries more readable by breaking them into named steps.
What is the difference between a CTE and a subquery?
Both create temporary result sets. CTEs are defined once at the top with WITH and referenced by name — making them reusable within the query and easier to read. Subqueries are written inline and cannot be reused without repeating code.
Can you have multiple CTEs in one query?
Yes. Chain multiple CTEs with commas: WITH cte1 AS (SELECT ...), cte2 AS (SELECT ... FROM cte1) SELECT * FROM cte2. Each CTE can reference previously defined CTEs in the same WITH clause.
What is a recursive CTE in SQL?
A recursive CTE references itself to traverse hierarchical data. It has an anchor member (starting point) and a recursive member (next step). Used for org charts, category trees, folder structures, and network graphs.
Is a CTE better than a temporary table?
CTEs are faster to write and automatically dropped after the query completes. Temporary tables persist for the session, can be indexed, and work better for very large intermediate datasets that need to be queried multiple times. For most analytics queries, CTEs are sufficient and preferred.
✏️ Practice Exercise
Rewrite the GROUP BY + HAVING query you wrote earlier (products with revenue above ₹10,000) as a CTE. Then add a second CTE that ranks those products by revenue.
Learn SQL with Live Trainer Guidance
These tutorials give you the theory. Our live SQL course at EVIKA Academy, Noida teaches you to apply SQL on real company datasets — with a trainer who uses it daily at MakeMyTrip.