Skip to content

LEAD

LEAD(value_expression [, offset [, default_value]]) OVER ( [ partition_by_clause ] order_by_clause )

Section titled “LEAD(value_expression [, offset [, default_value]]) OVER ( [ partition_by_clause ] order_by_clause )”
  • value_expression: It is an argument defining the value for which the lead value is returned. The expression should return a single value. It could be any valid expression or column of a table.
  • offset: This optional argument specifies the number of rows forward from the current row from which to return the value. The default is 1, meaning it will return the value in the next row.
  • default_value: Another optional parameter, it specifies the value to return if the offset goes beyond the scope of the result set.
  • partition_by_clause: A part of the OVER () clause, it divides the result set into partitions. The LEAD function is applied to each partition separately and restarts the counting in every new partition.
  • order_by_clause: Also part of the OVER () clause. This defines the logical order of the data rows in each partition by one or more columns within the scope of the function. The LEAD function applies to this ordered list.
SELECT
id,
value,
LEAD(value) OVER (ORDER BY id) as next_value
FROM
myTable;
| id | value | next_value |
|----|-------|------------|
| 1 | 10 | 20 |
| 2 | 20 | 30 |
| 3 | 30 | NULL |

The aforementioned SQL code includes the LEAD() function, which is utilized to retrieve the subsequent row’s data. In our case, the LEAD(value) function is ordered by id, envisioning the following value in the dataset. The output signifies that for id 1, the following value is 20, and for id 2, the succeeding value is 30. The NULL in the last row’s next_value column indicates that there is no follow-up row for id 3.