SQL LEAD()
SQL LEAD()

SQL LEAD()

The LEAD() window function takes a column and an integer offset as arguments and returns the value of the cell in that column that is the specified number of rows after the current row. A third argument can be added to fill cells that do not have a corresponding row.

Table of Contents

Syntax





LEAD(column1_name, offset) OVER(
  ORDER BY column2_name
)
  • The ORDER BY clause is required.
  • There is also a third, optional argument that sets the value of cells where the corresponding row does not exist. The third argument will be NULL by default.
  • When using LEAD() with partitions, any cells with a corresponding row in another partition will be filled with the default value. Think of it as treating each partition as a separate table.

Example

Suppose there’s a yearly_sales table that looks like this:

monthsales
11000
2500
3750
4800
5500
6400
7300
8500
9700
10800
111000
121250

Running the following query shows the next month’s sales for every month, with the last month having NA as its value.

SELECT month,  sales,  LEAD(sales, 1, "NA") OVER(    ORDER BY month  ) AS next_month_salesFROM yearly_sales;

This will be the output:

monthsalesnext_month_sales
11000500
2500750
3750800
4800500
5500400
6400300
7300500
8500700
9700800
108001000
1110001250
121250NA

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *