← Back to SQL, page 15

sql-0289 · Hard senior

When does an optimizer turn a correlated subquery into a join, and when does it really run once per row?

Optimizers decorrelate simple EXISTS, IN and some scalar subqueries into semi-joins, anti-joins or joins with aggregation, so they do not literally run per row. Subqueries with LIMIT, complex expressions or scalar results used in SELECT often stay correlated and run per outer row, which is fine with an index on the correlated column and slow without one.

Full answer

SQLite shows correlated scalar subqueries explicitly:

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
EXPLAIN QUERY PLAN
SELECT name, (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.id) AS last_order FROM customers c;
text
QUERY PLAN
SCAN c
CORRELATED SCALAR SUBQUERY 1
  SEARCH o

CORRELATED SCALAR SUBQUERY means it runs for each customer row, and the inner step names no index. After an index on orders(customer_id, order_date) is created, the plan shows a covering index search, so each per-row run is a direct lookup:

sql
CREATE INDEX orders_customer_date ON orders(customer_id, order_date);
EXPLAIN QUERY PLAN
SELECT name, (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.id) AS last FROM customers c;
text
QUERY PLAN
SCAN c
CORRELATED SCALAR SUBQUERY 1
  SEARCH o USING COVERING INDEX orders_customer_date (customer_id=?)

PostgreSQL rewrites EXISTS and IN into semi-joins but usually keeps a scalar subquery in SELECT as a SubPlan executed per row, unless it can be rewritten safely.

Practical rule: correlated subqueries are not automatically slow. They are slow when each execution scans a large table. Check the plan, index the correlated column, and rewrite as a join plus GROUP BY when the outer table is large and the subquery would scan.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

EXPLAIN QUERY PLAN
SELECT name, (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.id) AS last_order FROM customers c;

CREATE INDEX orders_customer_date ON orders(customer_id, order_date);
EXPLAIN QUERY PLAN
SELECT name, (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.id) AS last FROM customers c;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Simple EXISTS and IN become semi-joins
  • Scalar subqueries in SELECT often run per row
  • An index on the correlated column makes per-row runs cheap
  • Check the plan before rewriting

Common mistakes

  • Assuming every correlated subquery is slow
  • Rewriting into joins that change results (duplicates)

Follow-ups

  • How do you read a SubPlan in PostgreSQL EXPLAIN?
  • When would you rewrite with LATERAL?

Tips

  • Point to the plan line