SQL CTE vs Subquery: Differences, Examples and Performance Guide
SQL is more than writing SELECT statements. Learn how Common Table Expressions and subqueries help analysts solve complex business problems, organise analytical logic and write maintainable queries with practical examples.

SQL CTEs vs Subqueries: How to Write Cleaner, Smarter and More Efficient SQL Queries
Imagine working as a Data Analyst at an e-commerce company.
Your manager asks you to identify the top-performing products in every region, calculate their contribution to total sales and compare their performance against the previous month.
You open your SQL editor and begin writing the query.
After a few minutes, the query becomes increasingly complicated. There are multiple aggregations, nested SELECT statements and repeated calculations.
You can technically solve the problem using nested queries, but the result is difficult to understand and maintain.
This is where two important SQL concepts become useful: Common Table Expressions (CTEs) and subqueries.
Understanding when and how to use them is an important step towards becoming a stronger SQL analyst.
1. What Is a Subquery in SQL?
A subquery is a SQL statement written inside another SQL statement.
It allows the result of one query to be used by another query.
For example, suppose a company wants to identify employees earning more than the average salary.
SELECT
employee_name,
salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);
The inner query calculates the average salary.
The outer query identifies employees whose salary is higher than that result.
This is a straightforward example of a subquery.
2. Different Types of Subqueries
Scalar subquery
Returns a single value.
Example: Finding employees whose salary exceeds the average salary.
Multiple-row subquery
Returns multiple values that can be used with operators such as IN.
SELECT *
FROM employees
WHERE department_id IN (
SELECT department_id
FROM departments
WHERE location = 'Bangalore'
);
Correlated subquery
References columns from the outer query and is logically evaluated in relation to its rows.
For example:
SELECT
e.employee_name,
e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department_id = e.department_id
);
This identifies employees earning more than their department's average salary.
3. What Is a Common Table Expression?
A Common Table Expression, or CTE, is a named temporary result set defined using the WITH keyword.
It helps divide a complicated query into smaller, more understandable sections.
Consider the earlier employee example.
WITH department_average AS (
SELECT
department_id,
AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT
e.employee_name,
e.department_id,
e.salary,
d.avg_salary
FROM employees e
JOIN department_average d
ON e.department_id = d.department_id
WHERE e.salary > d.avg_salary;
The CTE calculates average salary by department.
The main query then compares each employee's salary against the corresponding department average.
The intermediate calculation has a meaningful name, making the analytical process easier to follow.
4. CTE vs Subquery: Detailed Comparison
| Parameter | CTE | Subquery | |---|---|---| | Syntax | WITH keyword | Nested SELECT | | Readability | Often better for complex queries | Good for simple conditions | | Organisation | Named intermediate results | Nested query structure | | Multiple references | Can be referenced multiple times within the statement | Often requires repeating logic | | Recursion | Supported by databases with recursive CTEs | Not intended for recursive querying | | Best application | Multi-step analysis | Simple nested calculations |
Neither approach is universally superior.
The right choice depends on the problem, database engine and maintainability requirements.
5. A Real-World Example: Finding the Top Products by Region
Suppose your sales table contains:
- order_id
- product_name
- region
- quantity
- selling_price
You need to calculate revenue by product and identify the top three products in each region.
First, calculate revenue.
WITH product_sales AS (
SELECT
region,
product_name,
SUM(quantity * selling_price) AS revenue
FROM sales
GROUP BY
region,
product_name
),
ranked_sales AS (
SELECT
region,
product_name,
revenue,
DENSE_RANK() OVER (
PARTITION BY region
ORDER BY revenue DESC
) AS product_rank
FROM product_sales
)
SELECT *
FROM ranked_sales
WHERE product_rank <= 3;
This query uses two CTEs.
The first calculates product revenue.
The second ranks products separately within each region.
The final query returns the top three ranks.
Notice how each stage performs a clearly defined task.
6. Which Approach Performs Better?
A common misconception is that CTEs are always faster than subqueries.
That is incorrect.
Performance depends on:
- Database engine.
- Query structure.
- Table size.
- Indexes and partitions.
- Optimisation strategy.
- Whether intermediate results are materialised.
- Data distribution.
Some database engines inline CTEs, while others may materialise them under certain conditions.
Use EXPLAIN or the database's equivalent execution-plan feature to investigate query performance.
Never assume that shorter SQL automatically means faster SQL.
7. Five Mistakes SQL Analysts Should Avoid
- Using deeply nested queries when a clearer structure is possible.
- Repeating the same calculation unnecessarily.
- Using SELECT * in production analytical queries without considering the required columns.
- Ignoring NULL values and duplicate records.
- Assuming a query is efficient without examining its execution plan.
8. How to Practise These Concepts
Try solving these problems using both CTEs and subqueries:
- Employees earning above their department average.
- Customers whose total spending exceeds the average.
- Products with the highest monthly sales.
- Customers who placed orders in consecutive months.
- Regions with revenue above the company average.
- The second-highest salary in every department.
For every solution, ask three questions:
Is the logic correct?
Can another analyst understand it?
Does the execution plan indicate acceptable performance?
Frequently Asked Questions
Are CTEs and subqueries interchangeable?
Many problems can be solved using either technique, but their syntax and capabilities differ. Choose according to readability, database support and performance.
Are CTEs important for Data Analyst interviews?
Yes. They are useful for demonstrating structured SQL problem-solving, especially in multi-step analytical questions.
Can a CTE be referenced multiple times?
Yes. A named CTE can be referenced multiple times within its SQL statement in supported database engines.
Are recursive CTEs useful?
They are useful for hierarchical and recursive problems such as organisational structures, category trees and certain graph-like relationships.
Should beginners learn subqueries before CTEs?
Learning simple subqueries first is a sensible approach. Once nested queries are understood, CTEs provide a cleaner way to organise complex analytical logic.
Final Thoughts: Write SQL That Solves Problems and Communicates Logic
A strong SQL analyst is not simply someone who can produce a query that returns the correct answer.
They should also understand how the query works, whether the result is reliable and how the logic can be maintained.
CTEs and subqueries are two important techniques for developing that capability.
At InsightNest, we encourage learners to move beyond memorising SQL syntax and focus on solving actual business problems using data.
Learn. Build. Grow.
Want to learn this properly?
The Data Analytics with GenAI for Placement Bootcamp covers Excel, SQL, Python, Power BI and Statistics live over 8 weekends, built on 7 real projects.
See the course