We’re improving Formula Genius. We’re redesigning the app and fixing issues along the way. Sorry for any disruption, and thank you for your patience.
SQL intermediate

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

Prompt

"Find products that have never been ordered"

SQL
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

  1. Outer query: SELECT from products with an alias p
  2. WHERE NOT EXISTS — only include rows where the subquery returns nothing
  3. Subquery: SELECT 1 FROM order_items — checks if any order contains this product
  4. WHERE oi.product_id = p.product_id — correlates the subquery to the outer row
  5. 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

Prompt

"Product 'Widget A' has 5 orders"

SQL
Not in results (has orders)
Prompt

"Product 'Gadget Z' has 0 orders"

SQL
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.