SQL LEAD function
The mirror of LAG: reads a value from a later row in the partition. Time until the next event, the next step in a funnel and is-last flags all come from it.
- 類別
- 視窗
- Returns
type of the expression- In this category
- 5 of 79
語法
LEAD(expression [, offset [, default]]) OVER (PARTITION BY g ORDER BY x)
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | 是 | Supported under this name. |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | 是 | MySQL 8.0+ |
| SQLite | 是 | SQLite 3.25+ |
| Oracle | 是 | Supported under this name. |
範例
PostgreSQL
SELECT user_id, at,
LEAD(at) OVER (PARTITION BY user_id ORDER BY at) - at AS until_next
FROM events;
Any engine
SELECT step, LEAD(step) OVER (ORDER BY position) AS next_step FROM funnel_steps;
小知識
- The last row has no next one: LEAD returns NULL by default, or your chosen default value.
- LEAD(at, 1, at) makes the last event's time-until-next zero instead of NULL.
- Offsets must be non-negative on SQL Server, Oracle and MySQL; PostgreSQL and SQLite accept LEAD(x, -1) and treat it as LAG(x). Write LAG when you mean the previous row.
- LEAD(x) IS NULL marks the last row of each partition only when x itself is never NULL. Test LEAD(id) or ROW_NUMBER instead.
Questions about LEAD
What is the difference between LEAD and LAG?
Direction: LAG looks at earlier rows, LEAD at later ones, both according to the OVER clause's ORDER BY.
How do I compute time until the next event?
LEAD(at) OVER (PARTITION BY user ORDER BY at) - at. Pass a default (LEAD(at, 1, at)) if the last event's open-ended duration should be zero rather than NULL.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.