1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL Subqueries Tutorial: Types, Correlated Subqueries and EXISTS With Examples

A subquery is a query inside another query. Learn each type and where it fits, understand correlated subqueries properly, and avoid the NOT IN trap that silently returns no rows at all.

9 min read
SQL subqueries tutorial: types, correlated subqueries and EXISTS with examples

Key takeaways

  • A subquery is a query nested inside another, and the outer query uses its result.
  • Subqueries can appear in WHERE, FROM, SELECT and HAVING.
  • A correlated subquery refers to the outer row, so it is logically evaluated per row.
  • Prefer NOT EXISTS to NOT IN when NULLs are possible.

Some questions take two steps to answer. “Which orders are above average?” requires you to find the average first, and then compare each order with it. SQL subqueries let you write both steps as one statement.

This tutorial covers each type using two small tables. We ran these queries in SQLite 3.50, and the results shown come from that run. Standard subquery syntax is widely supported, and we point out the places where databases differ.

What is a subquery?

A subquery, also called an inner or nested query, is a SELECT statement placed inside another statement, in round brackets. Conceptually, the inner query produces a result that the outer query then uses.

SELECT id, total
FROM orders
WHERE total > (SELECT AVG(total) FROM orders);

The sample tables

CREATE TABLE customers (id INT, name TEXT, city TEXT);
CREATE TABLE orders (id INT, customer_id INT, total INT);

INSERT INTO customers VALUES
 (1,'Asha','Pune'), (2,'Ben','Delhi'), (3,'Chitra','Pune'), (4,'Dev','Goa');

INSERT INTO orders VALUES
 (101,1,1200), (102,1,800), (103,2,300), (104,3,2500), (105,3,100);

Note that Dev has no orders. That detail matters for several examples below.

Types of subquery at a glance

Type Returns Typical location Common operators
Scalar One value WHERE, SELECT =, >, <
Multi-row One column, many rows WHERE IN, ANY, ALL
Table (derived) Many columns and rows FROM Used like a table
Correlated Depends on the outer row WHERE, SELECT Any, and EXISTS

Scalar subqueries

A scalar subquery returns exactly one value, so you can use it wherever a single value makes sense. Here is the query from earlier, with its result. The average of all orders is 980:

SELECT id, total
FROM orders
WHERE total > (SELECT AVG(total) FROM orders);

-- 101 | 1200
-- 104 | 2500

You could not write WHERE total > AVG(total), because aggregates are not allowed directly in WHERE. The subquery gets around this, by calculating the value separately.

What if a “scalar” subquery returns several rows? Most databases, including PostgreSQL, MySQL and SQL Server, raise an error. SQLite does not. In our test, it silently used only the first row, which could hide a real bug, so do not depend on this behaviour.

IN and NOT IN

When the inner query returns a list, use IN. This finds customers with at least one order over 1000:

SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE total > 1000);

-- Asha
-- Chitra

NOT IN does the opposite, finding customers who have never ordered:

SELECT name FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);

-- Dev

That works here, but NOT IN has a dangerous edge case, which we cover below.

Subqueries in FROM

A subquery in FROM acts as a temporary table, often called a derived table. It is useful when you need to aggregate twice, as in this query for the average spending per customer in each city:

SELECT city, AVG(spent) AS avg_spent
FROM (
  SELECT c.city, SUM(o.total) AS spent
  FROM customers c
  JOIN orders o ON o.customer_id = c.id
  GROUP BY c.id, c.city
) AS per_customer
GROUP BY city;

-- Delhi |  300.0
-- Pune  | 2300.0

The inner query totals each customer, and the outer one averages those totals. Giving the derived table an alias is a good habit, as some databases require it. If GROUP BY is new to you, see SQL GROUP BY and HAVING.

Subqueries in SELECT

A scalar subquery can also add a calculated column. This one counts orders per customer:

SELECT name,
       (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS order_count
FROM customers c;

-- Asha   | 2
-- Ben    | 1
-- Chitra | 2
-- Dev    | 0

Dev appears with zero. An inner join would have dropped Dev completely, because Dev has no matching rows. You could get the same result with a LEFT JOIN and GROUP BY, which we explain in SQL joins explained.

Correlated subqueries

The previous example is also correlated, since the inner query refers to c.id from the outer query. A non-correlated subquery can run alone. A correlated one cannot, because it depends on a value from the current outer row.

This finds orders above that same customer’s own average:

SELECT o.id, o.customer_id, o.total
FROM orders o
WHERE o.total > (
  SELECT AVG(i.total)
  FROM orders i
  WHERE i.customer_id = o.customer_id
);

-- 101 | 1 | 1200
-- 104 | 3 | 2500

Here is how to read it. For order 101, the inner query averages customer 1’s orders (1200 and 800), which gives 1000. Since 1200 is greater, the row is kept. For order 102, the same average applies, but 800 is not greater, so it is dropped. Customer 2’s single order equals its own average, so it is dropped too.

Feature Non-correlated Correlated
Uses outer query values? No Yes
Can run on its own? Yes No
Logical execution Once Once per outer row
Performance risk Usually low Can be high on large tables

“Once per row” describes the logic, and query optimizers often rewrite these into something far more efficient. Still, a slow correlated subquery is worth investigating. An index on the inner column, here orders.customer_id, can make a major difference. See SQL indexes explained.

EXISTS and NOT EXISTS

EXISTS asks a yes or no question: does the inner query return at least one row? It can stop at the first match, and what you select inside does not matter, which is why people often write SELECT 1.

SELECT c.name FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

-- Asha, Ben, Chitra

SELECT c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

-- Dev

The NOT IN NULL trap

This is one of the most common subquery bugs. We created a table with one real ID and one NULL, then ran both forms against it:

CREATE TABLE r (customer_id INT);
INSERT INTO r VALUES (1), (NULL);

SELECT name FROM customers
WHERE id NOT IN (SELECT customer_id FROM r);
-- (no rows at all)

SELECT c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM r WHERE r.customer_id = c.id);
-- Ben, Chitra, Dev

Why does the first return nothing? id NOT IN (1, NULL) means id <> 1 AND id <> NULL. Any comparison with NULL is unknown rather than true, so the whole condition can never be true. There is no error message and no warning, just an empty result that looks plausible.

Tip: Use NOT EXISTS for anti-joins by default. If you do use NOT IN, add WHERE customer_id IS NOT NULL inside the subquery.

Subquery vs JOIN vs CTE

Many queries can be written more than one way. Earlier we found customers with a large order using IN. Here is the same result with a join:

SELECT DISTINCT c.name FROM customers c
JOIN orders o ON o.customer_id = c.id AND o.total > 1000;

-- Asha
-- Chitra

Notice the DISTINCT. A join can produce duplicates if a customer has several matches, whereas IN and EXISTS cannot.

Use When
JOIN You need columns from both tables
IN or EXISTS You only need to filter by whether a match exists
Derived table You need to aggregate first, and it stays short
CTE The logic has several steps, or is used more than once
Window function You need a per-group figure beside each row

Performance varies by database and data, and modern optimizers often produce similar plans. So choose the clearest form first, then check EXPLAIN if it turns out to be slow.

Common mistakes

  • Using = with a multi-row result. Use IN, or make sure the inner query returns one row.
  • Using NOT IN on a nullable column. You can silently lose every row.
  • Using unclear aliases. In correlated queries, qualify every column, or it may bind to the wrong table.
  • Deep nesting. Three levels are hard to read, so convert them to CTEs.
  • Adding ORDER BY inside. It usually has no effect on the outer result, and some databases reject it.

Final thoughts

Subqueries are a natural way to express two-step questions. Start with scalar subqueries and IN, then practise correlated ones by reasoning through a single outer row at a time. And remember NOT EXISTS whenever NULLs are possible. To practise, write one question three ways, with a subquery, a join and a CTE, and compare both results and readability.

Frequently asked questions

What is a subquery in SQL?

A subquery is a SELECT statement nested inside another SQL statement, in brackets. The outer statement uses its result as a value, a list or a table.

What is a correlated subquery?

It is a subquery that refers to a column from the outer query. It depends on the current outer row, so it cannot run on its own.

Which is faster, a subquery or a JOIN?

It depends on the database and data, and optimizers often produce similar plans. Write the clearest version first, then compare execution plans if performance matters.

What is the difference between IN and EXISTS?

IN compares a value with a list of results. EXISTS checks whether any row is returned at all. They behave differently with NULLs when negated.

Can a subquery return multiple columns?

Yes, when used in FROM as a derived table, and some databases allow row comparisons too. A scalar subquery must return just one column and one row.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →