// window reference

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.

Categoria
Janela
Returns
type of the expression
In this category
5 of 79

Sintaxe

LEAD(expression [, offset [, default]]) OVER (PARTITION BY g ORDER BY x)

Suporte a mecanismos

MotorSupportNotas
SQL Server Sim Supported under this name.
PostgreSQL Sim Supported under this name.
MySQL Sim MySQL 8.0+
SQLite Sim SQLite 3.25+
Oracle Sim Supported under this name.

Exemplos

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;

Bom saber

  • 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.

// fewer lookups

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.