LATERAL subqueries in PostgreSQL - Time & Space Complexity
When using LATERAL subqueries in PostgreSQL, it is important to understand how the query's execution time changes as the data grows.
We want to know how the number of operations increases when the input tables get bigger.
Analyze the time complexity of the following query using a LATERAL join.
SELECT c.customer_id, o.order_id
FROM customers c
JOIN LATERAL (
SELECT order_id
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY order_date DESC
LIMIT 1
) o ON true;
This query finds the most recent order for each customer by joining each customer to their latest order using a LATERAL subquery.
Look for repeated actions in the query.
- Primary operation: For each customer, the database runs a subquery to find their latest order.
- How many times: Once per customer, so the number of times equals the number of customers.
The query runs the subquery once for each customer. If there are more customers, the total work grows proportionally.
| Input Size (customers) | Approx. Operations |
|---|---|
| 10 | 10 subqueries |
| 100 | 100 subqueries |
| 1000 | 1000 subqueries |
Pattern observation: The total work increases directly with the number of customers.
Time Complexity: O(n * m)
This means the query's execution time grows linearly with the number of customers and the cost of finding the latest order per customer.
[X] Wrong: "The LATERAL subquery runs only once for the whole query."
[OK] Correct: The LATERAL subquery runs separately for each row from the main table, so it repeats as many times as there are customers.
Understanding how LATERAL subqueries scale helps you write efficient queries and explain their performance clearly in real situations.
"What if we replaced the LATERAL subquery with a simple JOIN on orders without LIMIT? How would the time complexity change?"
Practice
LATERAL in a PostgreSQL query?Solution
Step 1: Understand the role of LATERAL
LATERAL allows a subquery to access columns from tables that appear earlier in the FROM clause.Step 2: Compare with other options
The other options describe different features unrelated to LATERAL's purpose.Final Answer:
To allow a subquery to reference columns from tables listed before it in the FROM clause -> Option AQuick Check:
LATERAL = subquery uses previous table columns [OK]
- Thinking LATERAL creates temporary tables
- Confusing LATERAL with query parallelism
- Assuming LATERAL enforces constraints
Solution
Step 1: Identify correct LATERAL syntax
The correct syntax uses CROSS JOIN LATERAL with a subquery in parentheses and an alias.Step 2: Check each option
SELECT * FROM table1, (SELECT * FROM table2 WHERE table2.id = table1.id) sub; misses LATERAL keyword causing reference error; SELECT * FROM table1 JOIN LATERAL table2 ON table2.id = table1.id; uses JOIN LATERAL incorrectly without parentheses; SELECT * FROM table1 LATERAL JOIN table2 ON table2.id = table1.id; has invalid syntax.Final Answer:
SELECT * FROM table1 CROSS JOIN LATERAL (SELECT * FROM table2 WHERE table2.id = table1.id) sub; -> Option CQuick Check:
Correct LATERAL syntax = SELECT * FROM table1 CROSS JOIN LATERAL (SELECT * FROM table2 WHERE table2.id = table1.id) sub; [OK]
- Omitting LATERAL keyword
- Not aliasing the subquery
- Using LATERAL without parentheses
users(id, name) and orders(user_id, amount), what does this query return?SELECT u.name, o.total FROM users u CROSS JOIN LATERAL (SELECT SUM(amount) AS total FROM orders WHERE user_id = u.id) o;
Solution
Step 1: Analyze the LATERAL subquery
The subquery sums orders per user using user_id = u.id, so it calculates total per user.Step 2: Understand CROSS JOIN LATERAL effect
It runs the subquery for each user, returning their name and total order amount, including users with zero orders (total will be NULL).Final Answer:
Each user with the total amount of their orders -> Option AQuick Check:
LATERAL sums orders per user = Each user with the total amount of their orders [OK]
- Thinking it returns all orders without grouping
- Assuming only users with orders appear
- Confusing CROSS JOIN LATERAL with INNER JOIN
SELECT t1.id, t2.val FROM table1 t1 JOIN LATERAL (SELECT val FROM table2 WHERE table2.ref = t1.id) t2;
Solution
Step 1: Check alias usage
The subquery is aliased as t2, so no issue there.Step 2: Verify JOIN LATERAL syntax
JOIN LATERAL without CROSS is valid syntax in PostgreSQL; CROSS JOIN LATERAL is one form, but JOIN LATERAL alone is allowed as INNER JOIN LATERAL.Step 3: Confirm subquery column count
Subquery returns one column 'val', which is acceptable.Final Answer:
No error; query is correct -> Option DQuick Check:
JOIN LATERAL syntax without CROSS is valid = No error [OK]
- Using JOIN LATERAL without CROSS
- Forgetting subquery alias
- Expecting subquery to return multiple columns
SELECT c.name, o.order_id, o.amount FROM customers c CROSS JOIN LATERAL (SELECT order_id, amount FROM orders WHERE customer_id = c.id ORDER BY amount DESC LIMIT 2) o;
Solution
Step 1: Understand LATERAL with LIMIT
The subquery selects top 2 orders per customer by ordering and limiting results.Step 2: Check if query returns all customers
CROSS JOIN LATERAL runs subquery per customer; if no orders, no rows for that customer appear.Step 3: Confirm correctness
The query correctly lists each customer with up to 2 highest orders; no syntax or logic errors.Final Answer:
This query correctly lists each customer with their top 2 orders -> Option BQuick Check:
LATERAL with LIMIT works for top N per row [OK]
- Thinking GROUP BY is needed here
- Believing LATERAL disallows LIMIT
- Assuming all customers appear even without orders
Ready to prove it?
Pass the test and this pattern moves unknown
