SQL Subqueries: Queries Within Queries
Subqueries let you use the result of one query inside another. Essential for filtering, comparisons, and derived tables.
Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.
The formula
"Find products that have never been ordered"
SELECT p.product_id, p.name
FROM products p
WHERE NOT EXISTS (
SELECT 1 FROM order_items oi
WHERE oi.product_id = p.product_id
);
The outer query checks each product. The subquery searches order_items for that product. NOT EXISTS returns TRUE when the subquery finds zero rows — meaning the product has never been ordered.
Step-by-step breakdown
- Outer query: SELECT from products with an alias p
- WHERE NOT EXISTS — only include rows where the subquery returns nothing
- Subquery: SELECT 1 FROM order_items — checks if any order contains this product
- WHERE oi.product_id = p.product_id — correlates the subquery to the outer row
- SELECT 1 is conventional for EXISTS — the value doesn't matter, only row existence
Edge cases & warnings
- NOT IN fails with NULLs: if the subquery returns any NULL, NOT IN returns no rows. Use NOT EXISTS instead.
- Correlated subqueries run once per outer row — can be slow on large tables
- EXISTS stops at the first match — more efficient than COUNT(*) > 0
- For readability on complex subqueries, consider converting to CTEs
Examples
"Product 'Widget A' has 5 orders"
Not in results (has orders)
"Product 'Gadget Z' has 0 orders"
Included in results
Frequently asked questions
When should I use EXISTS vs IN?
Use EXISTS for correlated checks (does a match exist?). Use IN for comparing against a list. EXISTS is generally faster when the subquery table is large.
Should I use subqueries or CTEs?
CTEs are more readable for complex multi-step queries. Subqueries are fine for simple filters. Performance is usually identical.
Can't find what you need?
Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.