Databases · Middle · Question 31 of 75

What does LEFT JOIN LATERAL allow?

SELECT u.name, o.*
FROM users u
LEFT JOIN LATERAL (
  SELECT * FROM orders WHERE orders.user_id = u.id
  ORDER BY created_at DESC LIMIT 3
) o ON true;

Explanation

It's a clean way to write 'top N per group'. With an index on (user_id, created_at) each lookup is cheap.

Further reading

Problem with a question

Databases · Middle · question 31

Test yourself

Take the Databases · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz