Skip to content

Instantly share code, notes, and snippets.

@monadplus
Created February 6, 2020 13:20
Show Gist options
  • Save monadplus/8dc4373900825dbea1b1ce4b3a36e371 to your computer and use it in GitHub Desktop.
Save monadplus/8dc4373900825dbea1b1ce4b3a36e371 to your computer and use it in GitHub Desktop.
Lateral Join

LATERAL JOIN

Data:

                Table "public.orders"
   Column   |            Type             | Modifiers
------------+-----------------------------+-----------
 id         | integer                     | not null
 user_id    | integer                     |
 created_at | timestamp without time zone |


 id | user_id |         created_at
----+---------+----------------------------
  1 |       1 | 2017-06-20 04:35:03.582895
  2 |       2 | 2017-06-20 04:35:07.564973
  3 |       3 | 2017-06-20 04:35:10.986712
  4 |       1 | 2017-06-20 04:58:10.137503
  5 |       3 | 2017-06-20 04:58:17.905277
  6 |       3 | 2017-06-20 04:58:25.289122

Problem: the time of the first order created by each user and what is the ID and time of the next order

Solution:

SELECT user_id, first_order_time, next_order_time, id FROM
  (SELECT user_id, min(created_at) AS first_order_time FROM orders GROUP BY user_id) o1
  LEFT JOIN LATERAL
  (SELECT id, created_at AS next_order_time
   FROM orders
   WHERE user_id = o1.user_id AND created_at > o1.first_order_time
   ORDER BY created_at ASC LIMIT 1)
   o2 ON true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment