“I just need one more filter…”
That’s always how it starts.
If you’re a beginner in data analytics, you might think a subquery is the best way to add that new filter… just nest a small SELECT inside your bigger query. No big deal, right?
But what happens when you have more filters to add? And what if they all come from different tables?
Your triple-nested subqueries aren’t looking so user-friendly then.
And when you have to update that query (and you will need to update it at some point), figuring out which query belongs to which becomes a nightmare.
That’s where CTEs come in, and they will become your new best friend.
Let’s Start with the Basics: What’s a Subquery?
Subqueries and CTEs may sound confusing, but you just need to think of them in a simpler way.
They think like this:
If SQL were a conversation, a subquery would be the side comment in brackets.
A subquery is the query inside your query, which is used to calculate something, filter something, or build a mini-table inside your query set. You’ve probably seen it, even if you didn’t know it had a name.
But subqueries aren’t just one thing. They come in different forms depending on where they appear in your main query. And once you understand how they work, it becomes a lot easier to spot when it’s time to skip it altogether and use a CTE instead.
But first: let’s talk types.
Types of Subqueries
There are 3 main places you’ll typically see subqueries:
1. In the SELECT Clause (i.e., Scalar Subqueries)
This is when you want to pull a single value from another table to display with each row of your main query.
A scalar subquery returns just one value. One row, one column. That’s it.
Example: Show each customer and the average transaction amount across all customers.
SELECT
name,
total_spent,
(SELECT AVG(amount) FROM transactions) AS avg_transaction_amount
FROM customers;
Sample Output:
| name | total_spent | avg_transaction_amount |
|---|---|---|
| Alice | 250 | 218.75 |
| Bob | 150 | 218.75 |
| Charlie | 500 | 218.75 |
| Dina | 50 | 218.75 |
The highlighted line is the subquery, which we’ve aliased (i.e., named) avg_transaction_amount. The query adds the same average transaction value (218.75) to every customer row.
That inner query runs once and returns a single number. That same number is repeated for every row in the result.
Think of it like adding a sticky note to every customer row saying, “By the way, the average is $218.75.”
Use this when:
You need to bring in a single value to compare or display.
Recommended Posts:
2. In the WHERE Clause
Here, a subquery helps filter your data by checking if something matches or exists elsewhere.
Tired of googling the same SQL problems every week?
Learn and practice SQL here:
Example: Show customers who made at least one transaction over $100.
SELECT name
FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM transactions
WHERE amount > 100
);
Sample Output:
| name | |
|---|---|
| 1 | Bob |
| 2 | Charlie |
This works because the subquery returns a list of IDs, and the outer query uses that list to filter rows for the resulting names.
This is one of the most common subquery patterns you’ll use in corporate data. It’s clean, readable, and works great when you want to filter based on another table.
Use this when:
You want to filter based on another table’s values or conditions.
3. In the FROM Clause (i.e., Table Subqueries)
This one is a little more advanced.
In this case, we use a subquery as if it’s a temporary table that you can join or query from.
Example: Get each customer’s name and their total transaction amount.
SELECT
c.name,
tx.total_amount
FROM customers c
JOIN (
SELECT customer_id, SUM(amount) AS total_amount
FROM transactions
GROUP BY customer_id
) tx ON c.customer_id = tx.customer_id;
Sample Output:
| name | total_amount |
|---|---|
| Alice | 100 |
| Bob | 275 |
| Charlie | 500 |
The subquery builds a summary table. Then the outer query joins it with the main table.
In other words, the part in brackets is building a little summary table on the fly, and then we’re joining it to the customer list.
NOTE: We have to alias the subquery with a name, like “tx” in our example, or else the subquery will result in an error when you run the code.
Use this when:
You need to create an intermediate result, like a summarized or filtered version of a table.

What Is a CTE?
CTE stands for Common Table Expression. It’s written with a WITH clause at the top of your query and lets you name your subquery so it’s easier to reuse and understand.
Think of a CTE as writing out the steps of your logic before handing them to SQL.
Let’s rewrite the previous example using a CTE:
WITH transaction_totals AS (
SELECT customer_id, SUM(amount) AS total_amount
FROM transactions
GROUP BY customer_id
)
SELECT
c.name,
t.total_amount
FROM customers c
JOIN transaction_totals t ON c.customer_id = t.customer_id;
In our final SELECT statement, we refer to the CTE in the join (highlighted).
We get the exact same result as with the subquery, but this version is much easier to follow, right?
You’re telling SQL:
“Step 1: calculate totals. Step 2: join those totals to customers.”
Tired of googling the same SQL problems every week?
Learn and practice SQL here:
But Can a CTE Replace All Subqueries?
Replacing all subqueries with CTEs sounds like the best way forward, doesn’t it?
Well, it’s not quite that simple.
CTEs work best as replacements for subqueries in the FROM clause.
If you’re using a subquery in the SELECT or WHERE, things get a bit trickier.
Let me explain with some examples:
Replacing a subquery in the FROM clause
This is the most common use for a CTE.
If your subquery is acting like a temporary table you’re selecting or joining from, a CTE is a cleaner alternative.
Subquery:
SELECT c.name, tx.total
FROM customers c
JOIN (
SELECT customer_id, SUM(amount) AS total
FROM transactions
GROUP BY customer_id
) tx ON c.customer_id = tx.customer_id;CTE version:
WITH tx AS (
SELECT customer_id, SUM(amount) AS total
FROM transactions
GROUP BY customer_id
)
SELECT c.name, tx.total
FROM customers c
JOIN tx ON c.customer_id = tx.customer_id;The CTE is a direct replacement of the subquery in the FROM clause, and it makes the logic more readable.
Subqueries in SELECT and WHERE cannot be directly replaced by CTEs – they need to be joined in
Because CTEs return tables, not scalar values or value lists, they don’t work as direct drop-in replacements for subqueries like these:
1. Subquery in SELECT (scalar subquery):
Let’s say we have this query, with a subquery in the SELECT:
SELECT
name,
(SELECT AVG(amount) FROM transactions) AS avg_tx
FROM customers;You can’t convert this to a CTE:
WITH avg_tx AS (
SELECT AVG(amount) AS avg_tx FROM transactions
)
SELECT
name,
avg_tx -- doesn't work
FROM customers;Why? Because avg_tx is not a column in customers, and there’s no join happening.
To use the CTE version, you’d need to cross-join it in:
WITH avg_tx AS (
SELECT AVG(amount) AS avg_tx FROM transactions
)
SELECT
c.name,
a.avg_tx
FROM customers c
CROSS JOIN avg_tx a;Remember, a CTE returns a table, not just a single value or list. So if you want to use the result of that CTE in your final query, you have to connect it to your main table using a JOIN, just like you would with any other table.
avg_txis its own one-row table.- You “join it in” using
CROSS JOIN, which just attaches that one-row result to every row incustomers.
So now each customer row gets the average value alongside it.
2. The same goes for WHERE subqueries.
A CTE can’t be used inside a condition like WHERE value IN (SELECT …) unless you join it and filter that way.
So now each customer row gets the average value alongside it.
Why CTEs Are Preferred Over Subqueries
I want to point something out before we continue:
There is nothing wrong with subqueries, and using them is not wrong.
I’ve worked with data analysts and data scientists who were more old-school and preferred writing nested subqueries. That was how they liked to write their code. But when it came time to debug, I had to reorganize them into CTEs to make it easier for testing. Again, that’s a personal choice, as I find CTEs much easier to understand.
It’s up to you!
Just remember that CTEs are much easier to understand.
Subqueries are fine for simple cases, or for scenarios mentioned previously where you can’t replace them with CTEs. They’re also used in interview problems and online challenges. But in large-scale data projects you’ll work with in your career, CTEs become the better choice.
Here’s why you should ditch those subqueries for CTEs:
1. CTEs are easier to read
You name them, format them, and you don’t have to scroll up and down trying to untangle nested parentheses.
2. CTEs are reusable
Need the same calculation in two different places? With subqueries, you’d have to copy-paste. With a CTE, you just reference the name.
3. CTEs scale better
When your logic changes, it’s easier to adjust one step in a CTE chain than to rewrite multiple nested subqueries.
Subqueries vs. CTEs: A Quick Comparison
| Feature | Subquery | CTE |
|---|---|---|
| Inline & concise | Yes | No |
| Readable for long queries | No | Yes |
| Can be reused | No | Yes |
| Named steps for logic | No | Yes |
| Recursive logic support | No | Yes (recursive CTEs) |
Recap: When Should You Use Each?
Use a subquery when:
- You need to plug in a single value.
- You’re writing a quick filter in a
WHEREclause. - The logic is short, simple, and only needed once.
Use a CTE when:
- Your query is longer than a few lines.
- You need to join or group something first.
- You want to name and organize each step.
- You’re writing production-level queries or reports.
Example Scenario: Filtering on a Calculation
Let’s say you want to get a list of customers where their average transaction is over $100.
You could do this with a subquery in the FROM clause:
SELECT name, avg_amount
FROM (
SELECT
c.name,
AVG(t.amount) AS avg_amount
FROM customers c
JOIN transactions t ON c.customer_id = t.customer_id
GROUP BY c.name
) sub
WHERE avg_amount > 100;
Or you could write it as a CTE:
WITH avg_tx AS (
SELECT
c.name,
AVG(t.amount) AS avg_amount
FROM customers c
JOIN transactions t ON c.customer_id = t.customer_id
GROUP BY c.name
)
SELECT *
FROM avg_tx
WHERE avg_amount > 100;
Which one is easier to maintain and explain?
Probably the second.
My Rule of Thumb?
Subqueries help you learn SQL.
CTEs help you scale it.
If you’re new to SQL, subqueries help you understand how one query can depend on another.
But the moment your logic starts nesting or repeating, switch to a CTE. Your future self (and your colleagues) will thank you.
So what’s the takeaway?
Keep these in mind the next time you are trying to figure out whether CTEs or subqueries are the better (or only) option:
- CTEs are great for replacing
FROMsubqueries, especially when summarizing or transforming data. - Subqueries in
SELECTandWHEREare often best left as-is unless you’re willing to restructure your query with JOINS or CROSS JOINS. - If you’re repeating the same subquery logic multiple times, even in
SELECTorWHERE, it might be worth restructuring the logic into a CTE + JOIN.
What about you?
Have you ever gone back to an old SQL query and had to restructure it?
Liked this post?
Subscribe to my newsletter and check out my data analytics resources. Your future self will thank you. Don’t forget to follow me on LinkedIn.










