Correlated Subqueries, Derived Tables and LATERAL Joins
Subqueries that depend on the outer row: how correlated subqueries are evaluated, the name-resolution trap that silently matches every row, derived tables in FROM, and LATERAL joins (CROSS APPLY in SQL Server) for top-N per group and per-row calculations.
kvi5hnuCode Sprout team member14 min readOn this page
The subqueries in the previous article were uncorrelated: each had one answer, the same for every row of the outer query. Many questions need a different answer for each row. "Is this product dearer than the average of its own category?" needs one average for the tents, another for the packs. "When did this customer last order?" needs one date per customer.
A subquery that refers to a column of the outer query is correlated, and its answer can change from row to row. This article explains how correlated subqueries work, shows a scoping rule that causes one of SQL's sneakiest bugs, and then covers two related tools: derived tables, which are subqueries in FROM, and LATERAL joins, which let a subquery in FROM be correlated too.
Correlated subqueries
Here's "products dearer than their category's average":
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Products priced above the average of their own category
SELECT p.name, p.category, p.price
FROM products p
WHERE p.price > (SELECT AVG(p2.price)
FROM products p2
WHERE p2.category = p.category) -- p.category comes from the outer row
ORDER BY p.category;
name | category | price
-------------------+----------+--------
Glow head torch | lighting | 34.50
Trail 30 backpack | packs | 89.95
Summit 4 tent | tents | 489.00
(3 rows)
The subquery uses two aliases for the same table. p2 is the subquery's own copy of products, and p is the outer query's current row. The condition p2.category = p.category ties them together: for the Ridge 2 tent, the subquery averages the tents. For the head torch, it averages the lighting products. That reference to p.category is what makes the subquery correlated.
The way to think about it, the logical model, is a loop: for each row of the outer query, plug that row's values into the subquery, run it, and use its result.

The socks are dropped because they're the only clothing product, so they equal their own average rather than exceeding it.
The loop is only the meaning. The database doesn't have to run it that way, and often doesn't: an optimizer can compute all the category averages in one pass and join them back. More on that in the performance section.
Correlated subqueries in SELECT
A correlated scalar subquery in the SELECT list computes one value per output row:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- One value per customer, computed by correlated scalar subqueries
SELECT c.name,
(SELECT COUNT(*)
FROM orders o
WHERE o.customer_id = c.customer_id) AS orders,
(SELECT MAX(o.placed_on)
FROM orders o
WHERE o.customer_id = c.customer_id) AS last_order
FROM customers c
ORDER BY c.customer_id;
name | orders | last_order
--------------+--------+------------
Asha Rao | 2 | 2026-03-09
Ben Okafor | 1 | 2026-03-05
Chen Wei | 1 | 2026-03-15
Dana Cruz | 1 | 2026-03-20
Eli Novak | 0 | (null)
Farah Haddad | 0 | (null)
(6 rows)
Each customer gets their own order count and most recent order date. Notice how naturally this handles customers with no orders. COUNT(*) over no rows is 0, and MAX over no rows is NULL. There's no outer join to get right and no COUNT(*) versus COUNT(column) trap, which article 19 showed is easy to fall into with LEFT JOIN and GROUP BY.
The rules for scalar subqueries from the previous article still apply, now per row: the subquery must return at most one row for every outer row, and returns NULL when there's none.
Correlated EXISTS
The most common correlated subquery is EXISTS, which article 16 covered in depth:
SELECT c.name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
For each customer, the subquery looks for an order with that customer's ID. Correlation is what makes EXISTS useful. An uncorrelated EXISTS gives the same answer for every row.
How names are resolved in a subquery
A subquery can see its own tables and the tables of every query around it. When you write an unqualified column name, SQL looks for it in the subquery's own FROM first. If no table there has a column of that name, it looks outward, in the enclosing query. That rule is necessary for correlation, but it creates a dangerous bug:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- customers has no product_id column. What does this return?
SELECT name
FROM products
WHERE product_id IN (SELECT product_id FROM customers)
ORDER BY name;
-- Qualifying the column turns the silent bug into an error
SELECT name
FROM products
WHERE product_id IN (SELECT c.product_id FROM customers c);
name
-------------------
Basecamp lantern
Day 18 backpack
Glow head torch
Merino socks
Ridge 2 tent
Summit 4 tent
Trail 30 backpack
(7 rows)
psql:/workspace/solution.sql:71: ERROR: column c.product_id does not exist
LINE 3: WHERE product_id IN (SELECT c.product_id FROM customers c);
^
The customers table has no product_id column. You might expect an error, but the first query runs and returns all seven products. Here's why:
- SQL looks for
product_idin the subquery'sFROM, which iscustomers. It isn't there. - It looks in the outer query, finds
products.product_id, and uses it. The subquery is now correlated: for each product, it returns that product's own ID, once per customer row. - Every product's ID is in a list made of its own ID, so
INis true for every row.
The real-world version of this bug: you meant to write SELECT product_id FROM order_items, typed the wrong table name, and a "products that were ordered" report silently lists every product. With NOT IN, the mistake makes the result empty instead. No error appears in either case.
The second query shows the defence: qualify column names in subqueries with a table alias. With c.product_id, SQL looks only in customers, finds no such column, and reports the error. It's a good habit in every query that has more than one table, and essential in subqueries.
Derived tables
A subquery in FROM is a derived table: the database runs it, and the outer query uses its result like a table. You saw one in the previous article and in article 17, where aggregating in a derived table before joining prevented fan-out:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Aggregate in a derived table, then join the result to customers
SELECT c.name, s.orders, s.order_value
FROM customers c
JOIN (SELECT o.customer_id,
COUNT(DISTINCT o.order_id) AS orders,
SUM(oi.qty * oi.unit_price) AS order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.customer_id) AS s
ON s.customer_id = c.customer_id
ORDER BY s.order_value DESC;
-- Column aliases can be given after the table alias
SELECT cat, n
FROM (SELECT category, COUNT(*) FROM products GROUP BY category) AS t (cat, n)
ORDER BY cat;
name | orders | order_value
------------+--------+-------------
Chen Wei | 1 | 489.00
Asha Rao | 2 | 452.44
Ben Okafor | 1 | 69.00
Dana Cruz | 1 | 54.00
(4 rows)
cat | n
----------+---
clothing | 1
lighting | 2
packs | 2
tents | 2
(4 rows)
The derived table s computes each customer's number of orders and total order value, one row per customer. The outer query joins that small summary to customers to show names. Because the aggregation happens inside the derived table, the join can't multiply anything.
Rules for derived tables:
- Give it an alias.
AS snames the derived table so the outer query can refer to its columns. PostgreSQL 16 and later, and Oracle, accept a derived table without one, but MySQL, SQL Server and older PostgreSQL versions require it. - Name its columns. Every computed column needs a name, from an alias inside (
AS orders) or from a column list after the table alias, as in the second query:AS t (cat, n)renames the columns tocatandn(not supported by Oracle). Without either, PostgreSQL would name the count columncount, and other databases may refuse. ORDER BYinside doesn't carry over. The outer query sees a set of rows. Sort in the outer query.- It can't see its siblings. A derived table can't refer to other tables in the same
FROMclause. That's what the next section is about.
Derived tables are useful for:
- Aggregating before joining, as above.
- Filtering on a computed column. A column alias defined in a derived table's
SELECTcan be used in the outerWHERE, which isn't possible in a single query, becauseWHEREruns beforeSELECT. - Breaking a query into steps. The inner query does one job, the outer query another.
When steps pile up, derived tables nest deeper and deeper, and the query reads from the inside out. Common table expressions (the next article) write the same steps from top to bottom.
LATERAL: correlated subqueries in FROM
Sometimes you want a correlated subquery that returns several rows or several columns, for example each customer's most recent order, with its ID and date. A scalar subquery in SELECT can return only one value. A derived table can return many rows and columns, but it can't refer to the other tables in FROM:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- A plain derived table can't see the other tables in FROM
SELECT c.name, x.n
FROM customers c
JOIN (SELECT COUNT(*) AS n FROM orders o WHERE o.customer_id = c.customer_id) AS x ON true;
-- LATERAL can: each customer's most recent order (customers with none are dropped)
SELECT c.name, t.order_id, t.placed_on
FROM customers c
CROSS JOIN LATERAL (SELECT o.order_id, o.placed_on
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY o.placed_on DESC
LIMIT 1) AS t
ORDER BY c.customer_id;
-- LEFT JOIN LATERAL ... ON true keeps customers with no orders
SELECT c.name, t.order_id, t.placed_on
FROM customers c
LEFT JOIN LATERAL (SELECT o.order_id, o.placed_on
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY o.placed_on DESC
LIMIT 1) AS t ON true
ORDER BY c.customer_id;
psql:/workspace/solution.sql:67: ERROR: invalid reference to FROM-clause entry for table "c"
LINE 3: ...COUNT(*) AS n FROM orders o WHERE o.customer_id = c.customer...
^
DETAIL: There is an entry for table "c", but it cannot be referenced from this part of the query.
HINT: To reference that table, you must mark this subquery with LATERAL.
name | order_id | placed_on
------------+----------+------------
Asha Rao | 103 | 2026-03-09
Ben Okafor | 102 | 2026-03-05
Chen Wei | 104 | 2026-03-15
Dana Cruz | 105 | 2026-03-20
(4 rows)
name | order_id | placed_on
--------------+----------+------------
Asha Rao | 103 | 2026-03-09
Ben Okafor | 102 | 2026-03-05
Chen Wei | 104 | 2026-03-15
Dana Cruz | 105 | 2026-03-20
Eli Novak | (null) | (null)
Farah Haddad | (null) | (null)
(6 rows)
The first query fails, and PostgreSQL's hint says exactly what to do: mark the subquery LATERAL. A LATERAL subquery may refer to tables that appear before it in the FROM clause, so it's evaluated, logically, once per row of those tables, just like a correlated subquery.
CROSS JOIN LATERAL (...)combines each customer with the rows the subquery returns for them. If the subquery returns no rows, the customer disappears, the same way an inner join drops rows with no match. Eli and Farah have no orders, so they're missing from the second query.LEFT JOIN LATERAL (...) ON truekeeps the customer and fills the subquery's columns with NULLs when it returns nothing, like any left join. The join condition isON truebecause the matching already happens inside the subquery'sWHERE.
The subquery here sorts the customer's orders newest first and keeps one with LIMIT 1. That's something an ordinary join can't express directly: "join each customer to their latest order".
Top-N per group
Change LIMIT 1 to LIMIT 2, and you get the two latest orders per customer. This top-N per group pattern is one of the main uses of LATERAL:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Top-N per group: the two most valuable lines of each order with 2+ lines
SELECT o.order_id, top_lines.name, top_lines.line_value
FROM orders o
CROSS JOIN LATERAL (SELECT p.name, oi.qty * oi.unit_price AS line_value
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
WHERE oi.order_id = o.order_id
ORDER BY line_value DESC
LIMIT 2) AS top_lines
WHERE o.order_id IN (101, 103)
ORDER BY o.order_id, top_lines.line_value DESC;
order_id | name | line_value
----------+-------------------+------------
101 | Ridge 2 tent | 249.99
101 | Merino socks | 48.00
103 | Trail 30 backpack | 89.95
103 | Glow head torch | 34.50
(4 rows)
For each of the two orders, the lateral subquery sorts that order's lines by value and keeps two. The ranking functions in article 27 solve the same problem in another way, by numbering the rows within each group and filtering on the number. LATERAL is often faster when the outer table is small and an index lets each subquery read only the rows it needs, because it can stop after N rows per group.
LATERAL in other databases
| Database | Syntax |
|---|---|
| PostgreSQL (9.3+) | CROSS JOIN LATERAL, LEFT JOIN LATERAL ... ON true |
| MySQL (8.0.14+) | JOIN LATERAL, LEFT JOIN LATERAL ... ON true |
| Oracle (12c+) | LATERAL, and also CROSS APPLY and OUTER APPLY |
| SQL Server | CROSS APPLY and OUTER APPLY |
| SQLite, MariaDB | not supported; use a correlated subquery or a window function |
SQL Server's CROSS APPLY corresponds to CROSS JOIN LATERAL, and OUTER APPLY to LEFT JOIN LATERAL ... ON true. There, the latest-order query looks like this:
SELECT c.name, t.order_id, t.placed_on
FROM customers c
OUTER APPLY (SELECT TOP (1) o.order_id, o.placed_on
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY o.placed_on DESC) AS t;
LATERAL isn't limited to subqueries. In PostgreSQL, a set-returning function in FROM, such as generate_series or jsonb_array_elements, can also refer to earlier tables (it's implicitly lateral). You'll see that in articles 41 and 43.
Performance
The "run the subquery once per row" model suggests that correlated subqueries are slow. Sometimes they are, and sometimes the optimizer makes them as fast as a join:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A correlated scalar subquery appears as a SubPlan, run for each outer row
EXPLAIN (COSTS OFF)
SELECT c.name,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id) AS orders
FROM customers c;
-- The same result from one grouped join
EXPLAIN (COSTS OFF)
SELECT c.name, COUNT(o.order_id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name;
QUERY PLAN
-------------------------------------------------------
Seq Scan on customers c
SubPlan 1
-> Aggregate
-> Seq Scan on orders o
Filter: (customer_id = c.customer_id)
(5 rows)
QUERY PLAN
----------------------------------------------------
HashAggregate
Group Key: c.customer_id
-> Hash Right Join
Hash Cond: (o.customer_id = c.customer_id)
-> Seq Scan on orders o
-> Hash
-> Seq Scan on customers c
(7 rows)
The first plan has a SubPlan: PostgreSQL really does run the counting subquery for each customer. With six customers that's nothing. With a million customers, it's a million small queries, each fast only if orders.customer_id has an index. The second plan reads both tables once, joins them with a hash join, and groups the result: one pass, whatever the number of customers.
What optimizers can do with correlated subqueries varies:
EXISTSandNOT EXISTSare routinely turned into semi-joins and anti-joins by every major database (article 16).INsubqueries are turned into joins. PostgreSQL 17 extended this to correlatedINsubqueries.- Correlated scalar subqueries in
SELECTorWHEREare where databases differ most. SQL Server and Oracle often decorrelate them into joins. PostgreSQL usually runs them as a SubPlan per row.
The practical advice:
- For a handful of rows, or with an index on the correlated column, a correlated subquery is fine and often the clearest form.
- For reports over large tables, prefer a join with
GROUP BY, a derived table aggregated once, or a window function (Part 6), and compare plans withEXPLAIN(article 67). - Several correlated subqueries against the same table, like the order count and last order date above, run separately. One derived table that computes both, or one
LATERALsubquery returning both columns, reads the table once per customer instead of twice.
Choosing between the forms
The same question can often be written several ways. "Each customer's number of orders":
| Form | Strengths |
|---|---|
Correlated scalar subquery in SELECT | Clear, handles "none" naturally (0 or NULL), one value per row |
LEFT JOIN + GROUP BY | One pass over large tables, several aggregates at once, but watch COUNT(*) and fan-out |
| Derived table aggregated first, then joined | No fan-out, aggregation done once, easy to add more joins |
LATERAL / APPLY | Several columns or several rows per outer row, top-N per group |
| Window function | Per-group values while keeping every row (Part 6) |
Start with the form that states the question most clearly, and change it if the plan shows a problem.
What's current
- PostgreSQL 17 can turn correlated
IN (subquery)conditions into joins, which earlier versions ran as a SubPlan per row. - PostgreSQL 16 made the alias of a derived table optional.
LATERALhas been in PostgreSQL since 9.3, Oracle since 12c and MySQL since 8.0.14, and SQL Server has hadAPPLYsince 2005. SQLite and MariaDB still don't support it.
Common questions
What makes a subquery correlated?
A reference to a column of the outer query, such as p.category inside the subquery. Without one, the subquery is uncorrelated and has a single answer.
Is a correlated subquery really run once per row? That's what it means, and sometimes what the database does. Often the optimizer rewrites it into a join or a semi-join. Check the plan.
Why did my IN (subquery) return every row?
Probably a column in the subquery that doesn't exist in the subquery's table, so SQL took it from the outer query. Qualify columns with aliases in subqueries to turn this into an error.
When do I need LATERAL?
When a subquery in FROM has to refer to a table that comes before it in the same FROM, for example to get the top N rows per outer row, or several columns from one correlated lookup.
What's the difference between CROSS JOIN LATERAL and LEFT JOIN LATERAL ... ON true?
The first drops outer rows for which the subquery returns nothing. The second keeps them with NULLs.
Does a derived table need an alias? In MySQL, SQL Server and PostgreSQL before 16, yes. Always adding one is the portable choice.
Can a correlated subquery refer to a table two levels out? Yes. A subquery can refer to any enclosing query, not only the one directly around it.
Can I use LIMIT inside a correlated subquery?
Yes, in SELECT, WHERE and LATERAL subqueries, and it's the basis of the top-N-per-group pattern.
Summary
- A correlated subquery refers to the outer query's current row. Logically, it's evaluated once per outer row, so its answer can differ from row to row.
- Correlated scalar subqueries in
SELECTcompute one value per row and handle rows with no matches naturally. - Unqualified names in a subquery are looked up in the subquery first, then outward. A misspelt or missing column can silently correlate the subquery and make
INmatch every row. Qualify columns. - A derived table is a subquery in
FROM. Give it an alias and named columns, and use it to aggregate before joining or to filter on computed columns. - A derived table can't refer to other tables in the same
FROM. ALATERALsubquery can, which gives top-N per group and multi-column lookups. SQL Server and Oracle also call itAPPLY. - Optimizers turn
EXISTSandINinto joins, but correlated scalar subqueries may run per row. Use joins, derived tables or window functions on large data, and check the plan.
Practice questions
Write a query that lists each order with its number of lines, using a correlated subquery. Include all six orders.
Answer
SELECT o.order_id,
(SELECT COUNT(*) FROM order_items oi WHERE oi.order_id = o.order_id) AS lines
FROM orders o
ORDER BY o.order_id;
Order 101 has 2 lines, 103 has 3, and the others have 1 each. An order with no lines would show 0, because COUNT(*) over no rows is 0.
A developer writes SELECT name FROM customers WHERE customer_id NOT IN (SELECT customer_id FROM products) to find customers with no orders, by mistake using products instead of orders. What does the query return, and why is there no error?
Answer
No rows. products has no customer_id, so the name is resolved to the outer customers.customer_id. For each customer, the subquery returns that customer's own ID once per product, and NOT IN a list containing your own ID is false. Writing SELECT p.customer_id FROM products p would have raised an error and revealed the mistake.
Write a query that returns each product category with its most expensive product's name and price, using LATERAL.
Answer
SELECT cat.category, top.name, top.price
FROM (SELECT DISTINCT category FROM products) AS cat
CROSS JOIN LATERAL (SELECT p.name, p.price
FROM products p
WHERE p.category = cat.category
ORDER BY p.price DESC
LIMIT 1) AS top
ORDER BY cat.category;
It returns Merino socks for clothing, Glow head torch for lighting, Trail 30 backpack for packs and Summit 4 tent for tents. If two products shared the top price, LIMIT 1 would keep only one of them. Add a second sort key, such as p.product_id, to make the choice predictable.
Why does this fail, and how do you fix it? SELECT c.name, t.total FROM customers c JOIN (SELECT SUM(qty * unit_price) AS total FROM orders o JOIN order_items oi ON oi.order_id = o.order_id WHERE o.customer_id = c.customer_id) AS t ON true;
Answer
A derived table can't refer to c, which is another table in the same FROM clause. Either add LATERAL (JOIN LATERAL (...) AS t ON true, or LEFT JOIN LATERAL to keep customers without orders), or remove the correlation: group the derived table by o.customer_id, select that column, and join on t.customer_id = c.customer_id.
In SQL Server, how do you write "each customer with their latest order, keeping customers who have no orders"?
Answer
With OUTER APPLY, SQL Server's equivalent of LEFT JOIN LATERAL ... ON true, and TOP (1) instead of LIMIT 1:
SELECT c.name, t.order_id, t.placed_on
FROM customers c
OUTER APPLY (SELECT TOP (1) o.order_id, o.placed_on
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY o.placed_on DESC) AS t;
CROSS APPLY would drop the customers with no orders.
Previous: SQL Subqueries: Scalar, IN, EXISTS, ANY and ALL
Next: Common Table Expressions (WITH): Writing Readable SQL in Steps

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.