CTE
Common Table Expression
ELI5 — The Vibe Check
A CTE is a temporary named result set you define at the top of a query with the WITH keyword. It's like giving a subquery a name so you can reuse it. Makes complex queries readable instead of a nested mess of parentheses. Some people call them 'WITH clauses.'
Real Talk
A CTE (Common Table Expression) is a named temporary result set defined using the WITH clause that exists only within the scope of a single SQL statement. CTEs improve readability, enable recursive queries, and can be referenced multiple times. They are supported by PostgreSQL, MySQL 8+, SQL Server, and SQLite. Non-recursive CTEs are typically expanded inline by the query planner.
Show Me The Code
WITH active_users AS (
SELECT id, name FROM users WHERE status = 'active'
),
recent_orders AS (
SELECT user_id, COUNT(*) as order_count
FROM orders WHERE created_at > NOW() - INTERVAL '30 days'
GROUP BY user_id
)
SELECT u.name, COALESCE(o.order_count, 0)
FROM active_users u LEFT JOIN recent_orders o ON u.id = o.user_id;
When You'll Hear This
"Use a CTE instead of a subquery — it's much easier to read." / "Recursive CTEs are perfect for traversing tree structures like org charts."
Related Terms
Common Table Expression
A CTE (WITH clause) lets you name a sub-query and use it later, like setting a variable in your SQL.
Recursive Query
A recursive query is SQL that calls itself, like a mirror reflecting a mirror.
SQL (Structured Query Language)
SQL is the language you use to talk to a database. You ask it things like 'give me all users who signed up this week' and it actually does it.
Subquery
A subquery is a query inside a query. The inner query runs first and its result is used by the outer query.