MySQL Subqueries, Derived Tables, EXISTS and LATERAL

MySQL 60 min min read Updated: Nov 27, 2026 Intermediate
MySQL Subqueries, Derived Tables, EXISTS and LATERAL
Intermediate Topic 2 of 3

Scalar Subquery

sql SELECT name, price, ROUND(price - (SELECT AVG(price) FROM products), 2) AS vs_average FROM products ORDER BY price DESC LIMIT 3;

Result:

namepricevs_average
Laptop899.00647.94
Phone599.00347.94
Desk249.00-2.06

IN and NOT IN

sql SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE status = 'pending') ORDER BY name;

Result:

name
Asha Rao
Chen Wei
NOT IN and NULL If the subquery returns even one NULL, NOT IN returns no rows at all. Use NOT EXISTS.
sql CREATE TABLE a (v INT); CREATE TABLE b (v INT); INSERT INTO a VALUES (1), (2); INSERT INTO b VALUES (1), (NULL); SELECT v AS not_in_result FROM a WHERE v NOT IN (SELECT v FROM b);

Result:

Result

(0 rows)

sql CREATE TABLE a (v INT); CREATE TABLE b (v INT); INSERT INTO a VALUES (1), (2); INSERT INTO b VALUES (1), (NULL); SELECT v AS not_exists_result FROM a WHERE NOT EXISTS (SELECT 1 FROM b WHERE b.v = a.v);

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):

sql SELECT p.name, p.category, p.price FROM products p WHERE p.price > (SELECT AVG(price) FROM products x WHERE x.category = p.category) ORDER BY p.category, p.price;

Result:

namecategoryprice
PhoneElectronics599.00
LaptopElectronics899.00
DeskFurniture249.00
Pen PackStationery5.00

EXISTS

sql SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.status = 'cancelled');

Result:

name
Ben Carter

EXISTS stops at the first match and the select list does not matter.

ANY and ALL

sql SELECT name, price FROM products WHERE price > ALL (SELECT price FROM products WHERE category = 'Furniture') ORDER BY price;

Result:

nameprice
Phone599.00
Laptop899.00

Derived Tables

A subquery in FROM must have an alias:

sql SELECT t.category, t.units FROM (SELECT category, SUM(stock) AS units FROM products GROUP BY category) AS t WHERE t.units > 100 ORDER BY t.units DESC;

Result:

categoryunits
Stationery800
Electronics145
sql SELECT * FROM (SELECT category FROM products GROUP BY category);
Error

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:

sql SELECT c.name, t.order_id, t.order_date FROM customers c JOIN LATERAL (SELECT o.id AS order_id, o.order_date FROM orders o WHERE o.customer_id = c.id ORDER BY o.order_date DESC LIMIT 1) t ORDER BY c.id;

Result:

nameorder_idorder_date
Asha Rao72025-04-20
Ben Carter102025-06-01
Chen Wei82025-05-05
Eli Brown62025-04-02
Fatima Khan92025-05-11

Each customer gets their latest order. Use LEFT JOIN LATERAL (...) t ON TRUE to keep customers without orders:

sql SELECT c.name, t.order_id FROM customers c LEFT JOIN LATERAL (SELECT o.id AS order_id FROM orders o WHERE o.customer_id = c.id ORDER BY o.order_date DESC LIMIT 1) t ON TRUE ORDER BY c.id;

Result:

nameorder_id
Asha Rao7
Ben Carter10
Chen Wei8
Dina CohenNULL
Eli Brown6
Fatima Khan9

Subquery or Join?

GoalGood choice
Existence checkEXISTS / NOT EXISTS
Compare with an aggregateScalar subquery or CTE
Latest row per groupROW_NUMBER() or LATERAL
Need columns from both tablesJOIN

Common Beginner Mistakes

MistakeWhat happensFix
NOT IN with a NULLEmpty resultNOT EXISTS
Derived table without aliasError 1248Add an alias
Scalar subquery returning many rowsError 1242Add LIMIT 1 or aggregate
Using LATERAL on MySQL 5.7 or 8.0.13Syntax errorUpgrade or use window functions

Practice

  1. Products priced above their category average.
  2. Customers with no orders using NOT EXISTS.
  3. Each customer's biggest order by item count using LATERAL.
  4. 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.

Quick Summary: scalar, IN, EXISTS, correlated, ANY/ALL, derived table, LATERAL.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators