SQL Server LEAD() Function

This blog is going to illustrate the functionality of SQL LEAD() and how to use it.

The SQL LEAD () function gives the next row of data for the offset value. This functionality was introduced in SQL Server 2012. Let’s see how to use it.

The following is the SampleTable.

SELECT SampleID, [Year], Profit
FROM SampleTable

The following query illustrates how to use the LEAD() function.

SELECT SampleID, Year, Profit,
LEAD(Profit, 1) OVER (ORDER BY SampleID ASC) AS NextYearProfit
FROM SampleTable

The following image is the output of the query above. Here you will find the column NextYearProfit. This shows the next profit.


Default Value

In the previous example, you can see that the last NextYearProfit column value is null. You can set the default value instead of zero if you want.

SELECT SampleID, [Year], Profit,
LEAD(Profit, 1, 7000000) OVER (ORDER BY SampleID ASC) AS NextYearProfit
FROM SampleTable

In the image below you can see that the last NextYearProfit value is ‘7000000’ instead of null

OFFSET value 2

Also, you can get the OFFSET value 2. That is next year’s next year value.

SELECT SampleID, [Year], Profit,
LEAD(Profit, 2) OVER (ORDER BY SampleID ASC) AS OffSet2
FROM SampleTable

In the picture, the profit of 2018 appears in 2016, the profit of 2019 appears in 2017, and so on.

PARTITION BY

You can use the LEAD() function using the PARTITION BY clause.

SELECT SampleID, [Quarter], [Year], Profit,
LEAD(Profit, 1) OVER (PARTITION BY [Year] ORDER BY [Year] ASC) AS NextYearProfit
FROM SampleTable 

In the image below you can see the result partition by the year.


I hope this article helps you. Keep Coding

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Exploring EventCallback in Blazor: Building Interactive Components

A Step-by-Step Guide to Implementing Identity in ASP.NET Core MVC