Common Table Expressions · Guide + 18 Interview Questions
SQL Common Table Expressions: Readable Queries With the WITH Clause
A Common Table Expression, or CTE, is a named temporary result set created with the SQL
WITH clause. It exists only for the duration of one statement, but it can make a
complicated query dramatically easier to read, debug, and maintain. This guide covers CTE syntax,
simple and multiple CTEs, recursive CTEs, CTE versus subquery, CTE versus view, CTE versus
temporary table, performance expectations, and the 18 interview questions that actually come up.
🎯 Key Takeaways
CTEs create named result sets using the WITH clause
CTEs improve readability, especially in multi-step queries
Multiple CTEs can be defined in one query
Recursive CTEs process hierarchical data
CTEs do not automatically improve performance
18 Interview QuestionsBeginner to AdvancedOracle, MySQL, PostgreSQL & SQL ServerUpdated Dec 2, 2026
KW
Kailas Warade
✓ Verified Author
Data Engineer · Oracle Certified · SQL & PL/SQL
Kailas works with SQL, PL/SQL, Python, and PySpark to build data pipelines.
He writes the SQL interview guides at Sankalan Data Tech, focused on
practical, real-world answers.
🏆 Oracle Certified💼 Data Engineer📝 SQL & PL/SQL Guides📍 Pune, India
A Common Table Expression, or CTE, is a named temporary result set defined using the SQL
WITH clause. You create it before the main query, give it a name, and then
reference that name in the final SELECT, INSERT,
UPDATE, or DELETE statement.
The key word is temporary. A CTE is not stored permanently in the database.
It exists only while the statement that defines it is running. Once the statement finishes,
the CTE is no longer available.
CTEs are useful because they let you break a complex query into logical steps. Instead of
nesting several subqueries inside one another, you can define each intermediate result with
a meaningful name and then combine those results in the final query.
A CTE does not replace a subquery, a view, or a temporary table. It is another tool for
organizing SQL logic. The best choice depends on whether you need readability, reuse across
queries, or physical storage of intermediate results.
The Sample Data We Use in Every Example
The examples below use an employees table and an orders table.
They are simple enough to follow, but realistic enough to show how CTEs are used in
reporting and analysis queries.
These tables make CTE examples useful because they support filtering, aggregation, joins,
duplicate detection, and ranking-style analysis.
CTE Syntax and Rules
A CTE begins with the WITH keyword, followed by the CTE name, the
AS keyword, and a query enclosed in parentheses.
WITH cte_name AS (
SELECT column1, column2
FROM table_name
WHERE condition
)
SELECT column1, column2
FROM cte_name;
WITH starts the CTE definition.
cte_name is the temporary name assigned to the result set.
AS introduces the CTE query.
The query inside parentheses is evaluated first.
The final query references the CTE by name.
A CTE can contain SELECT, FROM, WHERE,
GROUP BY, HAVING, ORDER BY, joins, and aggregate
functions. However, the CTE itself is only a named result set; it is not automatically
materialized or indexed.
💡 Important Rule
A CTE is available only within the statement that defines it.
You cannot reuse a CTE in a later, separate SQL statement.
Use a view when the query must be reused across sessions or applications.
Simple CTE Examples
Filter employees using a CTE
WITH high_salary_employees AS (
SELECT employee_id, employee_name, salary
FROM employees
WHERE salary > 50000
)
SELECT employee_id, employee_name, salary
FROM high_salary_employees;
The CTE high_salary_employees first filters employees whose salary is greater
than 50,000. The final query then retrieves the required columns from that filtered result.
Find active customers using a CTE
WITH active_customers AS (
SELECT customer_id, customer_name, city
FROM customers
WHERE status = 'Active'
)
SELECT customer_id, customer_name, city
FROM active_customers
ORDER BY customer_name;
This CTE separates the business rule — “active customers” — from the final presentation
query. If the definition of an active customer changes later, you only need to update the
CTE.
Find duplicate records using a CTE
WITH duplicate_emails AS (
SELECT email, COUNT(*) AS email_count
FROM users
GROUP BY email
HAVING COUNT(*) > 1
)
SELECT email, email_count
FROM duplicate_emails
ORDER BY email_count DESC;
This is a common interview use case. The CTE identifies duplicate email addresses, and the
final query displays them in descending order of frequency.
Multiple CTEs in One Query
SQL allows more than one CTE in a single WITH clause. Separate each CTE with
a comma.
WITH active_customers AS (
SELECT customer_id, customer_name
FROM customers
WHERE status = 'Active'
),
customer_orders AS (
SELECT customer_id, COUNT(*) AS total_orders
FROM orders
GROUP BY customer_id
)
SELECT c.customer_name,
COALESCE(o.total_orders, 0) AS total_orders
FROM active_customers c
LEFT JOIN customer_orders o
ON c.customer_id = o.customer_id
ORDER BY total_orders DESC;
The first CTE, active_customers, retrieves active customers. The second CTE,
customer_orders, counts orders for each customer. The final query combines
both result sets using a LEFT JOIN.
This approach is much easier to read than placing one subquery inside another. It also
makes the business logic explicit: first identify active customers, then count their
orders, then combine the results.
For a detailed explanation of joins, see the
SQL JOINs guide.
Recursive CTEs
A recursive CTE references itself. It is used to process hierarchical data, such as
employee-manager relationships, category trees, folder structures, and organizational
charts.
WITH RECURSIVE employee_hierarchy AS (
SELECT employee_id, employee_name, manager_id, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.employee_name, e.manager_id, eh.level + 1
FROM employees e
INNER JOIN employee_hierarchy eh
ON e.manager_id = eh.employee_id
)
SELECT employee_id, employee_name, manager_id, level
FROM employee_hierarchy
ORDER BY level, employee_name;
A recursive CTE has two parts:
Anchor query: Retrieves the starting rows, such as employees with no manager.
Recursive query: Joins the CTE to itself to retrieve the next level of hierarchy.
The two parts are combined using UNION ALL. The database repeatedly executes
the recursive part until no more matching rows are found.
⚠️ Important Caution
Always include a termination condition in a recursive CTE.
An incorrect recursive condition can create an infinite loop.
Recursive CTE syntax differs across database systems.
PostgreSQL, MySQL 8+, and SQLite use WITH RECURSIVE. Oracle and SQL Server
generally define recursive CTEs using WITH without the
RECURSIVE keyword.
CTE vs Subquery
Both CTEs and subqueries produce temporary result sets, but they organize SQL logic in
different ways.
Aspect
CTE
Subquery
Definition
Defined before the main query using WITH
Written inside another query
Readability
Better for complex, multi-step logic
Better for short, simple logic
Reuse
Can be referenced multiple times in the same statement
Usually written once at its point of use
Storage
Temporary, statement-scoped
Temporary, query-scoped
Performance
Depends on optimizer and query plan
Depends on optimizer and query plan
Same result using a CTE
WITH high_salary AS (
SELECT employee_id, employee_name, salary
FROM employees
WHERE salary > 50000
)
SELECT *
FROM high_salary;
Same result using a subquery
SELECT *
FROM (
SELECT employee_id, employee_name, salary
FROM employees
WHERE salary > 50000
) AS high_salary;
Both queries return the same result. Use a CTE when the logic is long, needs a meaningful
name, or must be referenced more than once. Use a subquery when the logic is short and
used only once.
CTEs, views, and temporary tables all help manage intermediate or reusable data, but they
solve different problems.
Aspect
CTE
View
Temporary Table
Scope
One statement
Database object
Session or transaction
Storage
Not permanently stored
Stored definition, not necessarily data
Physically stores data temporarily
Reuse
Within one query
Across queries and applications
Across multiple statements in a session
Best use
Readable multi-step query
Reusable reporting logic
Large intermediate result sets
Use a CTE when you need to simplify one query. Use a view when the same query must be
reused. Use a temporary table when intermediate results must be stored and processed
multiple times.
A common interview mistake is to say that CTEs always improve performance. They do not.
A CTE primarily improves readability and query organization.
Some databases may materialize a CTE, while others may inline it into the final query plan.
The actual performance depends on the database engine, indexes, data volume, joins,
filters, and how many times the CTE is referenced.
⚡ Performance Rule
Use a CTE for clarity, not automatically for speed.
Check the execution plan before assuming a CTE is faster.
A CTE referenced once may be inlined by the optimizer.
A CTE referenced many times may be evaluated repeatedly unless the optimizer materializes it.
These are the Common Table Expression questions that come up most often in SQL interviews.
Every answer stands on its own — read them in any order, or work through them in sequence
to build a complete understanding of CTEs, the WITH clause, recursive CTEs,
and their practical use cases.
/
🔍
No matching questions found
Try a keyword like CTE, WITH, recursive, or subquery.
A Common Table Expression, or CTE, is a named temporary result set created using the
SQL WITH clause. It exists only for the duration of the statement that
defines it.
WITH high_salary_employees AS (
SELECT employee_id, employee_name, salary
FROM employees
WHERE salary > 50000
)
SELECT *
FROM high_salary_employees;
The CTE high_salary_employees stores employees whose salary is greater
than 50,000. The final query then retrieves data from that named result set.
A CTE is mainly used to make complex SQL queries easier to read, organize, debug, and
maintain. It does not store data permanently in the database.
The basic syntax of a CTE is:
WITH cte_name AS (
SELECT column1, column2
FROM table_name
WHERE condition
)
SELECT column1, column2
FROM cte_name;
WITH starts the CTE definition. cte_name is the temporary
name assigned to the result set. The query inside parentheses is evaluated first, and
the final query references that result by its CTE name.
A CTE can include SELECT, FROM, WHERE,
GROUP BY, HAVING, joins, aggregate functions, and
ORDER BY.
A CTE is defined before the main query using the WITH clause. A subquery
is written inside another query, often in the SELECT,
FROM, or WHERE clause.
-- Using a CTE
WITH high_salary AS (
SELECT employee_id, employee_name, salary
FROM employees
WHERE salary > 50000
)
SELECT *
FROM high_salary;
-- Using a subquery
SELECT *
FROM (
SELECT employee_id, employee_name, salary
FROM employees
WHERE salary > 50000
) AS high_salary;
Both queries return the same result. A CTE is usually easier to read when the logic is
long or needs to be referenced more than once. A subquery is often better for a
short, one-time calculation.
Yes. You can define multiple CTEs in a single WITH clause by separating
them with commas.
WITH active_customers AS (
SELECT customer_id, customer_name
FROM customers
WHERE status = 'Active'
),
customer_orders AS (
SELECT customer_id, COUNT(*) AS total_orders
FROM orders
GROUP BY customer_id
)
SELECT c.customer_name,
COALESCE(o.total_orders, 0) AS total_orders
FROM active_customers c
LEFT JOIN customer_orders o
ON c.customer_id = o.customer_id
ORDER BY total_orders DESC;
The first CTE retrieves active customers. The second CTE calculates the number of
orders for each customer. The final query combines both result sets.
A later CTE can reference an earlier CTE defined in the same WITH clause.
A recursive CTE is a CTE that references itself. It is used to process hierarchical
data, such as employee-manager relationships, category trees, folder structures, and
organizational charts.
WITH RECURSIVE employee_hierarchy AS (
SELECT employee_id, employee_name, manager_id, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.employee_name, e.manager_id, eh.level + 1
FROM employees e
INNER JOIN employee_hierarchy eh
ON e.manager_id = eh.employee_id
)
SELECT employee_id, employee_name, manager_id, level
FROM employee_hierarchy
ORDER BY level, employee_name;
A recursive CTE has two parts: an anchor query and a recursive query. The anchor query
provides the starting rows, while the recursive query joins the CTE to itself until no
more matching rows are found.
UNION ALL combines the anchor result with each recursive result without
removing duplicate rows.
SELECT ...
UNION ALL
SELECT ...
It is generally preferred in recursive CTEs because it avoids the additional work
required to identify and remove duplicates. In most hierarchical queries, duplicates
are not expected at each recursion level.
Use UNION only when duplicate removal is explicitly required, because it
can add unnecessary processing overhead.
Not automatically. A CTE mainly improves readability, query organization, and
maintainability.
Performance depends on the database optimizer, indexes, query plan, filters, joins,
data volume, and how many times the CTE is referenced.
Some databases may materialize a CTE, while others may inline it into the final query
plan. Always check the execution plan before assuming that a CTE is faster or slower
than a subquery.
Yes. A non-recursive CTE can be referenced multiple times within the same statement.
WITH monthly_sales AS (
SELECT sale_month, SUM(amount) AS total_sales
FROM sales
GROUP BY sale_month
)
SELECT a.sale_month AS current_month,
a.total_sales AS current_sales,
b.total_sales AS previous_sales
FROM monthly_sales a
LEFT JOIN monthly_sales b
ON a.sale_month = b.sale_month + INTERVAL '1 month';
This is one of the main advantages of a CTE: you define the intermediate result once
and reference it wherever needed within the same query.
Yes, in many databases. A CTE can be referenced by an INSERT,
UPDATE, or DELETE statement that follows it.
WITH inactive_customers AS (
SELECT customer_id
FROM customers
WHERE last_login_date < DATE_SUB(CURDATE(), INTERVAL 365 DAY)
)
UPDATE customers
SET status = 'Inactive'
WHERE customer_id IN (
SELECT customer_id
FROM inactive_customers
);
The exact support and syntax depend on the database system. Always test the statement
in your target database before using it in production.
A CTE is temporary and exists only for one SQL statement. A view is a stored SQL query
that can be reused across multiple queries, sessions, and applications.
-- CTE: available only in this query
WITH active_customers AS (
SELECT *
FROM customers
WHERE status = 'Active'
)
SELECT *
FROM active_customers;
-- View: stored and reusable
CREATE VIEW v_active_customers AS
SELECT *
FROM customers
WHERE status = 'Active';
Use a CTE for a one-time, readable query. Use a view when the same business logic must
be reused repeatedly.
A CTE is a logical, temporary result set. A temporary table physically stores
intermediate results for a session or transaction.
Aspect
CTE
Temporary Table
Scope
One statement
Session or transaction
Storage
Not permanently stored
Physically stores data temporarily
Reuse
Within one query
Across multiple statements
Best use
Readable multi-step query
Large intermediate result sets
Use a CTE when you need to simplify one query. Use a temporary table when intermediate
results must be stored and processed multiple times.
Yes. A CTE can contain joins, filters, aggregations, sorting, and other valid SQL
query logic.
WITH employee_department AS (
SELECT e.employee_id,
e.employee_name,
d.department_name,
e.salary
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id
)
SELECT employee_name, department_name, salary
FROM employee_department
WHERE salary > 50000;
This CTE combines employee and department data, and the final query filters the joined
result by salary.
For a detailed explanation of joins, see the
SQL JOINs guide.
Yes. CTEs are often used to calculate grouped results before joining or filtering them
in the final query.
WITH department_totals AS (
SELECT department_id,
COUNT(*) AS employee_count,
AVG(salary) AS average_salary
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 1
)
SELECT department_id, employee_count, average_salary
FROM department_totals
ORDER BY average_salary DESC;
The CTE calculates the employee count and average salary for each department. The
HAVING clause keeps only departments with more than one employee.
Use a CTE with GROUP BY and HAVING to identify values that
occur more than once.
WITH duplicate_emails AS (
SELECT email, COUNT(*) AS email_count
FROM users
GROUP BY email
HAVING COUNT(*) > 1
)
SELECT email, email_count
FROM duplicate_emails
ORDER BY email_count DESC;
This query returns email addresses that appear more than once, along with the number of
times each email appears.
This is one of the most common practical uses of a CTE in interviews and data-cleaning
tasks.
Use a CTE with a window function such as DENSE_RANK(), then filter the
ranked result in the final query.
WITH ranked_salaries AS (
SELECT employee_name, salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees
)
SELECT employee_name, salary
FROM ranked_salaries
WHERE salary_rank = 2;
The CTE assigns a rank to each salary. The final query retrieves employees whose salary
rank is 2.
DENSE_RANK() is preferred when multiple employees can have the same
salary, because it does not skip rank values after ties.
It can run indefinitely or until the database reaches a recursion limit. This can
consume excessive CPU, memory, and time.
-- Risky recursive CTE without a clear stopping condition
WITH RECURSIVE numbers AS (
SELECT 1 AS n
UNION ALL
SELECT n + 1
FROM numbers
)
SELECT n
FROM numbers;
Always include a condition that eventually stops recursion, such as limiting the level
or ensuring that no new rows match the recursive join condition.
WITH RECURSIVE numbers AS (
SELECT 1 AS n
UNION ALL
SELECT n + 1
FROM numbers
WHERE n < 10
)
SELECT n
FROM numbers;
This query stops after generating the numbers 1 through 10.
The basic non-recursive CTE syntax is widely supported, but recursive CTE syntax and
optimizer behavior differ across database systems.
Database
Recursive CTE Keyword
PostgreSQL
WITH RECURSIVE
MySQL 8+
WITH RECURSIVE
SQLite
WITH RECURSIVE
Oracle
WITH
SQL Server
WITH
Always check the documentation for your specific database version before writing
recursive CTEs.
Use a CTE when the query has multiple logical steps, needs a meaningful name, must be
referenced more than once, or becomes difficult to read with nested subqueries.
WITH high_value_orders AS (
SELECT customer_id, SUM(order_amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING SUM(order_amount) > 10000
),
active_high_value_customers AS (
SELECT c.customer_name, h.total_amount
FROM customers c
INNER JOIN high_value_orders h
ON c.customer_id = h.customer_id
WHERE c.status = 'Active'
)
SELECT customer_name, total_amount
FROM active_high_value_customers
ORDER BY total_amount DESC;
This query is easier to understand because each CTE represents one clear business step:
first identify high-value orders, then identify active customers who placed them.
Use a subquery instead when the logic is short, used only once, and does not need a
separate name.
Mistakes I Keep Seeing in Interviews
These come up repeatedly. None of them are exotic, and every one of them is easy to avoid
once you know it is coming.
Mistake one: assuming a CTE always improves performance. A CTE improves
readability and organization; performance depends on the optimizer, indexes, query plan, and
how the CTE is used.
Mistake two: confusing a CTE with a view. A CTE exists only for one
statement, while a view is a stored database object that can be reused.
Mistake three: writing a recursive CTE without a termination condition. This
can create an infinite loop or consume excessive resources.
Mistake four: using UNION instead of
UNION ALL in recursive CTEs without understanding the duplicate-removal cost.
Mistake five: creating deeply nested subqueries when a CTE would make the
logic clearer and easier to maintain.
Mistake six: assuming a CTE is materialized or indexed by default. Check the
execution plan before making performance decisions.
Follow-Up Questions Interviewers Ask
Getting the first answer right is only half the interview. What usually decides the
outcome is what happens next. Here is what to prepare for on the CTE topic.
After “What is a CTE?” — expect
“How does a CTE differ from a subquery?”
“When would you not use a CTE?”
“Can a CTE be used more than once?”
“What is the difference between a CTE and a view?”
After “Recursive CTE” — expect
“What are the anchor and recursive parts?”
“Why is UNION ALL commonly used?”
“How do you prevent an infinite loop?”
“What data problems are best solved with a recursive CTE?”
After “CTE performance” — expect
“Does a CTE always improve performance?”
“How does the optimizer handle a CTE?”
“When would you use a temporary table instead?”
“How would you check whether a CTE is efficient?”
For every question above, prepare a second-level answer. The candidates who pass are not
the ones who memorized the first answer — they are the ones who kept going for another
thirty seconds and said something useful about why it matters.
Quick Quiz
Three questions to check whether the topics above have landed.
1. Which SQL clause creates a Common Table Expression?
2. Which operator is commonly used to combine the anchor and recursive parts of a recursive CTE?
3. Does a CTE automatically improve query performance?