LATERAL queries

LATERAL queries allow you to select more than one column and one row in a correlated subquery. This is very useful when creating Top-N subqueries and trying to join table functions together, thus making unnesting them a clear possibility. The LATERAL query can then be thought of as a sort of SQL foreach loop.

Let's give a simple example that would illustrate how a LATERAL query would work. Let's say that we have two hypothetical tables that contain data on films and actors:

SELECT    film.id,    film.title,    actor_bio.name,    actor_bio.biographyFROM film,    LATERAL (SELECT                  actor.name,                 actor.biography             FROM actor             WHERE actor.film_id = film.id) AS actor_bio;

As we can see, the LATERAL subquery is selecting multiple columns from the actor ...

Get Mastering The Faster Web with PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.