Common Table Expressions: Concept
Module: Subqueries & CTEs
Think of a CTE as giving a name to a subquery. Instead of writing (SELECT ...) AS something buried in your FROM clause, you write WITH something AS (SELECT ...) at the top of your query. It's like declaring a variable in programming - you define it once with a clear name, then use it wherever you need.
Example without CTE (hard to read):
SELECT * FROM (SELECT * FROM employees WHERE salary > 80000) AS high_earners WHERE department = 'Engineering';
Same query with CTE (clear and readable):
WITH high_earners AS (
SELECT * FROM employees WHERE salary > 80000
)
SELECT * FROM high_earners WHERE department = 'Engineering';
The CTE version reads like English: "WITH high earners defined as employees making over 80K, SELECT the ones in Engineering." Much clearer intent.
CTEs are named temporary result sets. They improve readability by breaking complex queries into logical steps. Each CTE can reference earlier CTEs. Performance is similar to derived tables. Check execution plan to see if materialized.
CTEs are modern SQL best practice - preferred over nested subqueries and derived tables in 90% of cases. Every data analyst, BI developer, and backend engineer uses them daily. They are the difference between code that works and code that others can understand and maintain. Essential for technical interviews and production code reviews.
CTEs are everywhere in production SQL. They make complex reports readable by breaking them into named steps: "first get active customers, then calculate their totals, then rank them". Used in data warehousing, analytics dashboards, financial reports, and any query where clarity matters as much as correctness.