Bird
Raised Fist0
PostgreSQLquery~20 mins

LATERAL join for correlated subqueries in PostgreSQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
LATERAL Join Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of LATERAL join with correlated subquery
Given the tables departments and employees, what is the output of this query?
SELECT d.name, e.name
FROM departments d
JOIN LATERAL (SELECT name FROM employees WHERE department_id = d.id ORDER BY salary DESC LIMIT 1) e ON true
ORDER BY d.id;
PostgreSQL
CREATE TABLE departments (id INT PRIMARY KEY, name TEXT);
CREATE TABLE employees (id INT PRIMARY KEY, name TEXT, department_id INT, salary INT);

INSERT INTO departments VALUES (1, 'HR'), (2, 'Engineering');
INSERT INTO employees VALUES (1, 'Alice', 1, 50000), (2, 'Bob', 1, 60000), (3, 'Charlie', 2, 70000), (4, 'Diana', 2, 65000);
A[{"department": "HR", "employee": "Bob"}, {"department": "Engineering", "employee": "Diana"}]
B[{"department": "HR", "employee": "Alice"}, {"department": "Engineering", "employee": "Charlie"}]
C[{"department": "HR", "employee": "Alice"}, {"department": "Engineering", "employee": "Diana"}]
D[{"department": "HR", "employee": "Bob"}, {"department": "Engineering", "employee": "Charlie"}]
Attempts:
2 left
💡 Hint
Look for the employee with the highest salary in each department.
📝 Syntax
intermediate
1:30remaining
Identify the syntax error in LATERAL join usage
Which option contains a syntax error when using LATERAL join in PostgreSQL?
PostgreSQL
SELECT d.name, e.name FROM departments d JOIN LATERAL (SELECT name FROM employees WHERE department_id = d.id) e ON true;
ASELECT d.name, e.name FROM departments d JOIN LATERAL SELECT name FROM employees WHERE department_id = d.id e ON true;
BSELECT d.name, e.name FROM departments d JOIN LATERAL (SELECT name FROM employees WHERE department_id = d.id) e ON true;
CSELECT d.name, e.name FROM departments d JOIN LATERAL (SELECT name FROM employees WHERE department_id = d.id) AS e ON true;
DSELECT d.name, e.name FROM departments d JOIN LATERAL (SELECT name FROM employees WHERE department_id = d.id) e ON d.id = e.department_id;
Attempts:
2 left
💡 Hint
Check if the subquery is properly enclosed in parentheses.
❓ optimization
advanced
2:00remaining
Optimizing a LATERAL join query for performance
You have this query:
SELECT d.name, e.name
FROM departments d
JOIN LATERAL (SELECT name FROM employees WHERE department_id = d.id ORDER BY salary DESC LIMIT 1) e ON true;

Which change will most likely improve performance on large tables?
AAdd an index on employees(department_id, salary DESC)
BRemove the ORDER BY clause inside the subquery
CReplace LATERAL join with a CROSS JOIN
DAdd a WHERE clause filtering departments by name
Attempts:
2 left
💡 Hint
Think about how the database finds the top salary employee per department efficiently.
🔧 Debug
advanced
2:00remaining
Why does this LATERAL join query return no rows?
Given these tables:
departments(id, name), employees(id, name, department_id, salary INT)

Why does this query return no rows?
SELECT d.name, e.name
FROM departments d
JOIN LATERAL (SELECT name FROM employees WHERE department_id = d.id AND salary > 100000) e ON true;
AThe lateral subquery must not have a WHERE clause referencing outer table columns
BJOIN LATERAL requires ON condition to compare columns from both tables, ON true is invalid
CNo employees have salary > 100000, so the lateral subquery returns no rows, causing JOIN to behave like INNER JOIN
DThe query is missing GROUP BY clause for aggregation
Attempts:
2 left
💡 Hint
Consider what happens when the lateral subquery returns no rows in a JOIN.
🧠 Conceptual
expert
2:30remaining
Understanding LATERAL join behavior with multiple rows
Consider this query:
SELECT d.name, e.name
FROM departments d
JOIN LATERAL (SELECT name FROM employees WHERE department_id = d.id LIMIT 2) e ON true
ORDER BY d.id, e.name;

How many rows will this query return if each department has 3 employees?
A3 rows per department, total rows = number_of_departments * 3
B2 rows per department, total rows = number_of_departments * 2
C1 row per department, total rows = number_of_departments
Dnumber_of_departments rows, but only employees with highest salary
Attempts:
2 left
💡 Hint
LATERAL runs the subquery for each row of the left table and returns all rows from the subquery.

Practice

(1/5)
1. What is the main purpose of using a LATERAL join in PostgreSQL?
easy
A. To run a subquery for each row of the main table using that row's data
B. To join two tables without any condition
C. To create a temporary table for all rows at once
D. To speed up queries by caching results

Solution

  1. Step 1: Understand what LATERAL join does

    A LATERAL join allows a subquery to use columns from the current row of the main query.
  2. Step 2: Identify the main purpose

    This means the subquery runs once per row, using that row's data to produce related results.
  3. Final Answer:

    To run a subquery for each row of the main table using that row's data -> Option A
  4. Quick Check:

    LATERAL join = per-row subquery execution [OK]
Hint: LATERAL runs subqueries per row using that row's data [OK]
Common Mistakes:
  • Thinking LATERAL joins all rows at once
  • Confusing LATERAL with regular JOIN
  • Assuming LATERAL speeds up queries by caching
2. Which of the following is the correct syntax to use a LATERAL join in PostgreSQL?
easy
A. SELECT a.id, b.value FROM table_a a JOIN (SELECT value FROM table_b WHERE b.a_id = a.id) b ON true;
B. SELECT a.id, b.value FROM table_a a JOIN LATERAL (SELECT value FROM table_b WHERE b.a_id = a.id) b ON true;
C. SELECT a.id, b.value FROM table_a a LEFT JOIN LATERAL table_b b ON b.a_id = a.id;
D. SELECT a.id, b.value FROM table_a a CROSS JOIN table_b b WHERE b.a_id = a.id;

Solution

  1. Step 1: Identify correct LATERAL syntax

    LATERAL must be explicitly stated before the subquery or table function to allow referencing outer query columns.
  2. Step 2: Check each option

    SELECT a.id, b.value FROM table_a a JOIN LATERAL (SELECT value FROM table_b WHERE b.a_id = a.id) b ON true; correctly uses JOIN LATERAL with a subquery referencing outer alias 'a'. SELECT a.id, b.value FROM table_a a JOIN (SELECT value FROM table_b WHERE b.a_id = a.id) b ON true; misses LATERAL keyword. SELECT a.id, b.value FROM table_a a LEFT JOIN LATERAL table_b b ON b.a_id = a.id; uses LATERAL but tries to join a table directly without subquery syntax. SELECT a.id, b.value FROM table_a a CROSS JOIN table_b b WHERE b.a_id = a.id; uses CROSS JOIN without LATERAL, so no correlation.
  3. Final Answer:

    SELECT a.id, b.value FROM table_a a JOIN LATERAL (SELECT value FROM table_b WHERE b.a_id = a.id) b ON true; -> Option B
  4. Quick Check:

    Correct LATERAL syntax includes keyword before subquery [OK]
Hint: LATERAL keyword must precede subquery to access outer columns [OK]
Common Mistakes:
  • Omitting LATERAL keyword before subquery
  • Using regular JOIN without correlation
  • Trying to join tables directly without subquery
3. Given the tables:
users(id, name)
orders(id, user_id, amount)
What will this query return?
SELECT u.name, o.amount FROM users u JOIN LATERAL (SELECT amount FROM orders WHERE user_id = u.id ORDER BY amount DESC LIMIT 1) o ON true;
medium
A. Users with all their orders listed
B. All orders with user names repeated
C. Syntax error due to missing ON condition
D. Each user with their highest order amount

Solution

  1. Step 1: Understand the LATERAL subquery

    The subquery selects the highest order amount per user by ordering descending and limiting to 1.
  2. Step 2: Analyze the JOIN LATERAL effect

    For each user row, the subquery runs and returns that user's top order amount, joining on true to include all users with orders.
  3. Final Answer:

    Each user with their highest order amount -> Option D
  4. Quick Check:

    LATERAL subquery returns top order per user [OK]
Hint: LATERAL runs subquery per user to get top order [OK]
Common Mistakes:
  • Thinking it returns all orders per user
  • Assuming syntax error due to ON true
  • Confusing join with CROSS JOIN
4. Identify the error in this query:
SELECT u.name, o.amount FROM users u JOIN LATERAL (SELECT amount FROM orders WHERE user_id = u.id ORDER BY amount DESC LIMIT 1) o;
medium
A. Subquery cannot reference outer query columns
B. Incorrect alias usage for orders table
C. Missing ON clause after LATERAL join
D. ORDER BY not allowed in subqueries

Solution

  1. Step 1: Check JOIN syntax

    Every JOIN requires an ON clause or USING clause to specify join condition.
  2. Step 2: Verify the query

    The query uses JOIN LATERAL but omits ON clause, causing syntax error.
  3. Final Answer:

    Missing ON clause after LATERAL join -> Option C
  4. Quick Check:

    JOIN must have ON or USING clause [OK]
Hint: Always add ON clause after JOIN LATERAL [OK]
Common Mistakes:
  • Forgetting ON clause after JOIN LATERAL
  • Thinking subquery can't use outer columns
  • Believing ORDER BY is disallowed in subqueries
5. You want to list each customer with their two most recent orders using LATERAL join. Which query correctly achieves this?
hard
A. SELECT c.name, o.order_id FROM customers c JOIN LATERAL (SELECT order_id FROM orders WHERE customer_id = c.id ORDER BY order_date DESC LIMIT 2) o ON true;
B. SELECT c.name, o.order_id FROM customers c JOIN orders o ON o.customer_id = c.id ORDER BY o.order_date DESC LIMIT 2;
C. SELECT c.name, o.order_id FROM customers c CROSS JOIN LATERAL orders o WHERE o.customer_id = c.id LIMIT 2;
D. SELECT c.name, o.order_id FROM customers c LEFT JOIN LATERAL (SELECT order_id FROM orders WHERE customer_id = c.id ORDER BY order_date ASC LIMIT 2) o ON true;

Solution

  1. Step 1: Understand the requirement

    We want two most recent orders per customer, so order by order_date DESC and limit 2 in subquery.
  2. Step 2: Check each option

    SELECT c.name, o.order_id FROM customers c JOIN LATERAL (SELECT order_id FROM orders WHERE customer_id = c.id ORDER BY order_date DESC LIMIT 2) o ON true; uses JOIN LATERAL with correct ordering and limit, joining on true to include all customers with orders. SELECT c.name, o.order_id FROM customers c JOIN orders o ON o.customer_id = c.id ORDER BY o.order_date DESC LIMIT 2; limits total rows, not per customer. SELECT c.name, o.order_id FROM customers c CROSS JOIN LATERAL orders o WHERE o.customer_id = c.id LIMIT 2; uses CROSS JOIN LATERAL incorrectly without subquery. SELECT c.name, o.order_id FROM customers c LEFT JOIN LATERAL (SELECT order_id FROM orders WHERE customer_id = c.id ORDER BY order_date ASC LIMIT 2) o ON true; orders ASC, which gives oldest orders, not recent.
  3. Final Answer:

    SELECT c.name, o.order_id FROM customers c JOIN LATERAL (SELECT order_id FROM orders WHERE customer_id = c.id ORDER BY order_date DESC LIMIT 2) o ON true; -> Option A
  4. Quick Check:

    LATERAL with ORDER BY DESC and LIMIT 2 per customer [OK]
Hint: Use LATERAL with ORDER BY DESC and LIMIT for top N per row [OK]
Common Mistakes:
  • Limiting total rows instead of per customer
  • Ordering ascending instead of descending
  • Using CROSS JOIN LATERAL without subquery
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard