Scalar Subquery
Result:
| name | price | vs_average |
|---|---|---|
| Laptop | 899.00 | 647.94 |
| Phone | 599.00 | 347.94 |
| Desk | 249.00 | -2.06 |
IN and NOT IN
Result:
| name |
|---|
| Asha Rao |
| Chen Wei |
NOT IN returns no rows at all. Use NOT EXISTS.
Result:
(0 rows)
Result:
| not_exists_result |
|---|
| 2 |
Correlated Subquery
The inner query uses a column of the outer row, so it runs once per outer row (the optimizer may rewrite it):
Result:
| name | category | price |
|---|---|---|
| Phone | Electronics | 599.00 |
| Laptop | Electronics | 899.00 |
| Desk | Furniture | 249.00 |
| Pen Pack | Stationery | 5.00 |
EXISTS
Result:
| name |
|---|
| Ben Carter |
EXISTS stops at the first match and the select list does not matter.
ANY and ALL
Result:
| name | price |
|---|---|
| Phone | 599.00 |
| Laptop | 899.00 |
Derived Tables
A subquery in FROM must have an alias:
Result:
| category | units |
|---|---|
| Stationery | 800 |
| Electronics | 145 |
ERROR 1248: Every derived table must have its own alias
LATERAL Derived Tables (MySQL 8.0.14+)
A normal derived table cannot see the other tables in FROM. With LATERAL it can, which makes "top N per row" easy:
Result:
| name | order_id | order_date |
|---|---|---|
| Asha Rao | 7 | 2025-04-20 |
| Ben Carter | 10 | 2025-06-01 |
| Chen Wei | 8 | 2025-05-05 |
| Eli Brown | 6 | 2025-04-02 |
| Fatima Khan | 9 | 2025-05-11 |
Each customer gets their latest order. Use LEFT JOIN LATERAL (...) t ON TRUE to keep customers without orders:
Result:
| name | order_id |
|---|---|
| Asha Rao | 7 |
| Ben Carter | 10 |
| Chen Wei | 8 |
| Dina Cohen | NULL |
| Eli Brown | 6 |
| Fatima Khan | 9 |
Subquery or Join?
| Goal | Good choice |
|---|---|
| Existence check | EXISTS / NOT EXISTS |
| Compare with an aggregate | Scalar subquery or CTE |
| Latest row per group | ROW_NUMBER() or LATERAL |
| Need columns from both tables | JOIN |
Common Beginner Mistakes
| Mistake | What happens | Fix |
|---|---|---|
NOT IN with a NULL | Empty result | NOT EXISTS |
| Derived table without alias | Error 1248 | Add an alias |
| Scalar subquery returning many rows | Error 1242 | Add LIMIT 1 or aggregate |
Using LATERAL on MySQL 5.7 or 8.0.13 | Syntax error | Upgrade or use window functions |
Practice
- Products priced above their category average.
- Customers with no orders using
NOT EXISTS. - Each customer's biggest order by item count using
LATERAL. - Categories whose total stock is above the overall average category stock.
Conclusion
Subqueries answer questions inside questions. Prefer EXISTS for presence checks, avoid NOT IN with NULLs, alias derived tables, and use LATERAL for top-N per row.

