Using the LEAD() and LAG() Analytic Functions in Oracle
Hello, we will look at how to use the LEAD() and LAG() functions, analytic functions that everyone working with Oracle has surely heard of, even if they have not used them yet.
To define them in general terms;
LEAD() : In an ordered data set, returns the value that any column of the current row takes in the next row. (By changing the offset value, we can also reach the column value 2 or more rows ahead.)
Syntax : LEAD ( TARGET_COLUMN, [offset]) OVER ( ORDER BY ORDERING_COLUMN)
Syntax : LEAD ( TARGET_COLUMN, [offset]) OVER ( ORDER BY ORDERING_COLUMN)
We can understand the purpose and usage of the functions more easily by working through an example. Let’s say we have a table (T_ORTALAMA_SICAKLIK) that stores average temperatures by month.
CREATE TABLE T_ORTALAMA_SICAKLIK (ID NUMBER, AY NUMBER, AY_STR VARCHAR2(20), ORT_SICAKLIK NUMBER);
and the rows containing sensible values so that we can test with this table,

after adding these records, when we first query the table we will get a view like the one below,

To see how the temperature changes between months, if we want to add the previous and next months’ averages next to the ORT_SICAKLIK column of each month, we will need the LEAD() and LAG() functions.
Thanks to these functions, we can easily get the values in the previous or next row of the current row.
In our example, the logical ordering is on the AY column, and the values we want to fetch from the preceding and following rows are the values in the ORT_SICAKLIK column. (previous month’s value) LAG() should be used in our example as follows: LAG(ORT_SICAKLIK, 1) OVER(ORDER BY AY), and (next month’s value) the LEAD() function will take the form LEAD(ORT_SICAKLIK, 1) OVER(ORDER BY AY). The complete query;
SELECT AY_STR, LAG (ORT_SICAKLIK, 1) OVER (ORDER BY AY) ONCEKI_AY_ORT, ORT_SICAKLIK, LEAD (ORT_SICAKLIK, 1) OVER (ORDER BY AY) SONRAKI_AY_ORT FROM T_ORTALAMA_SICAKLIK;
and the result we get from this query will be as shown below.

Looking at a specific month, we can see that while the average temperature (ORT_SICAKLIK) for MAYIS 2012 (May 2012) is 17.5, the previous month’s average (ONCEKI_AY_ORT) in the same row is 12.7 and the next month’s average (SONRAKI_AY_ORT) is 22.1. This also makes it possible to perform operations on these three columns in the same row and calculate things such as percentage change. Good luck.
