SQL LEAD Function: Usage Guide

In SQL, the LEAD function is used to access data from a specified number of rows after the current row. It can be used to retrieve the next row’s value without changing the original query result’s order. The LEAD function is commonly used with the ORDER BY clause to ensure that results are returned in a specific order.

The basic syntax of the LEAD function is as follows:

LEAD(expression, offset, default) OVER (PARTITION BY partition_col ORDER BY order_col)

Among them:

  1. Column or expression needed to retrieve the value of the next row.
  2. offset: the offset of the line to be accessed. The default is 1, which means accessing the value of the next line.
  3. Default: optional parameter that indicates the default value to return when there is no value on the next line.
  4. PARTITION BY is an optional clause used to specify the columns for grouping.
  5. ORDER BY: Used to specify the sorting of the results.

Here is an example of the LEAD function:

SELECT 
    product_id,
    product_name,
    LEAD(product_name, 1, 'N/A') OVER (ORDER BY product_id) AS next_product
FROM products;

This will return a result set that includes product ID, product name, and the name of the next product. If there is no next product, the default value is ‘N/A’.

bannerAds