Skip to content

LEAD / LAG

Selecting all and the previous (LAG) or next (LEAD) ordered by certain columns

SELECT id,
LAG(id, 1, 0) OVER (ORDER BY filter, date, id) AS previous_entity
FROM table

Selecting all of the previouus entity provided the current ID

``` SELECT * FROM table WHERE id = ( SELECT previous_entity FROM ( SELECT id, LAG(id, 1, 0) OVER (ORDER BY filter, date, id) AS previous_entity FROM table ) WHERE id = ? )