Skip to content
Related Articles
Open in App
Not now

Related Articles

SQL Server LEAD() function Overview

Improve Article
Save Article
  • Last Updated : 09 Sep, 2020
Improve Article
Save Article

At many instances, user would really like to check the worth of the present row with the worth of the subsequent row. to resolve this problem in SQL Server’s LEAD() window function are often used.

LEAD() :
Function provides access to a row at a set physical offset following this row. LEAD() function will allows to access data of the following row, or the row after the subsequent row, and continue on.

Syntax :

LEAD(return_value, offset [, default])  
OVER (
   [PARTITION BY partition_expression]
   ORDER BY sort_expression [ASC | DESC]
)

Where :

  1. return_value –
    The return_value of the subsequent row supported a specified offset. The return_value must be one value.

  2. offset –
    The offset is that the number of rows forward from the present row from where to access data. The offset should be a positive integer. If you don’t define the default value of offset is 1.

  3. default –
    The LEAD() function results default if offset is beyond the scope of the partition. If not defined, default is NULL.

  4. PARTITION BY clause –
    The PARTITION BY clause is optional, it differs rows of the result set into partitions to where the LEAD() function is used.

  5. ORDER BY clause –
    The ORDER BY clause define logical order of the rows in each partition to where the LEAD() function is used.

Example-1:
Let us suppose we have below table named “CompanySales” :

Select * 
from CompanySales;
CompanyYearAmount
ABC Ltd.20155000
XYZ Ltd.20154600
ABC Ltd.20175500
ABC Ltd.20165400
XYZ Ltd.20166500
ABC Ltd.20185400
XYZ Ltd.20174700
XYZ Ltd.20185400

Example-2:

SELECT TOP 10 [Company], [Year], [Amount],
LEAD(Amount, 1) OVER (
PARTITION BY Company
ORDER BY Year DESC
) AS Lead_amount
FROM [CompanySales] ;

Output –

CompanyYearAmountLead_amount
ABC Ltd.201854005500
ABC Ltd.201755005400
ABC Ltd.201654005000
ABC Ltd.20155000NULL
XYZ Ltd.201854004700
XYZ Ltd.201747006500
XYZ Ltd.201665004600
XYZ Ltd.20154600NULL
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!