LEAD() and LAG()

OVER() with RANK()

LEAD() reads a value from a following row and LAG() reads a value from a previous row in the window. Use them with OVER() to compare neighboring rows without a self join.

LEAD(value_expression) OVER (ORDER BY expression)
Using student sample table.
SELECT id, name, class, mark, gender,
       LEAD(mark) OVER (ORDER BY mark, id) AS next_mark
FROM student
WHERE class = 'Four';
The last row has NULL for next_mark because there is no following row in the window.
idnameclassmarkgendernext_mark
6Alex JohnFour55male55
10Big JohnFour55female60
4Krish StarFour60female60
5John MikeFour60female69
21Babby JohnFour69female75
1John DeoFour75female88
15Tade RowFour88male88
16GimmyFour88male88
31 Marry ToeeyFour88maleNULL

Using PARTITION BY

Each gender partition has its own final row, so each partition produces one NULL value for next_mark.
SELECT id, name, class, mark, gender,
       LEAD(mark) OVER (PARTITION BY gender ORDER BY mark, id) AS next_mark
FROM student
WHERE class = 'Four';
idnameclassmarkgendernext_mark
10Big JohnFour55female60
4Krish StarFour60female60
5John MikeFour60female69
21Babby JohnFour69female75
1John DeoFour75femaleNULL
6Alex JohnFour55male88
15Tade RowFour88male88
16GimmyFour88male88
31 Marry ToeeyFour88maleNULL

LAG()

LAG() returns a value from a previous row in the window. The first row in each window has no previous row, so it returns NULL.
SELECT id, name, class, mark, gender,
       LAG(mark) OVER (ORDER BY mark, id) AS previous_mark
FROM student
WHERE class = 'Four';
Output
idnameclassmarkgenderprevious_mark
6Alex JohnFour55maleNULL
10Big JohnFour55female55
4Krish StarFour60female55
5John MikeFour60female60
21Babby JohnFour69female60
1John DeoFour75female69
15Tade RowFour88male75
16GimmyFour88male88
31 Marry ToeeyFour88male88

Using PARTITION BY with LAG()

PARTITION BY gender creates a separate window for each gender, so the first row of each partition has a NULL previous value.
SELECT id, name, class, mark, gender,
       LAG(mark) OVER (PARTITION BY gender ORDER BY mark, id) AS previous_mark
FROM student
WHERE class = 'Four';
idnameclassmarkgenderprevious_mark
10 Big JohnFour55femaleNULL
4Krish StarFour60female55
5John MikeFour60female60
21Babby JohnFour69female60
1John DeoFour75female69
6Alex JohnFour55maleNULL
15Tade RowFour88male55
16GimmyFour88male88
31Marry ToeeyFour88male88

Over & partition window RANK() Sum Multiple column


Subscribe to our YouTube Channel here



plus2net.com




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer