DELAPARRA
Index
Color
NL
Category: SQL

subquery

Explained by Updated

What is subquery?

subquery: A query nested inside another — in SELECT, FROM, or WHERE. A correlated subquery references the outer row. A subquery is a query inside another query. It can appear in WHERE, as in finding customers whose total exceeds the average, in FROM as a derived table, or in SELECT to calculate a value per row.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about subquery

How is subquery used in practice?

A correlated subquery refers to the outer query's current row, such as counting each customer's orders. It runs once per outer row, which can be slow on large tables.

What should you keep in mind with subquery?

Modern databases optimise many subqueries well, but when one is slow, rewriting it as a JOIN, a CTE or a window function often helps. EXISTS subqueries are an efficient exception, because they stop at the first match. Check with EXPLAIN rather than guessing. For readability, a CTE with a clear name is often easier to follow than deeply nested subqueries.

What does an example of subquery look like?

SELECT name FROM users u WHERE (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) > 0;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with S

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.