LEAD/LAG are analytic functions that provide access to more than one row of a table at the same time, without a self join. Let’s see how.
Take a table that stores the master list of exam grades, mapped to the upper limit up to which the grade applies. The table (GRADE_MASTER) has two columns: {GRADE_CODE, SCORE_UPTO}. For exam scores in the range 0-100, GRADE_MASTER specifies the A-F.
SQL> desc grade_master
Name Null? Type
----------------- -------- -----------
GRADE_CODE NOT NULL VARCHAR2(2)
SCORE_UPTO NOT NULL NUMBER(3)
SQL> select * from grade_master;
GR SCORE_UPTO
-- ----------
F 59
D 69
C 79
B 89
A 100
The above data means that grade F applies to scores 0-59, D applies to scores 60-69, C to scores 70-79, and so on.
To find the grade for a given the examination score, the SQL needs to compare the EXTENT values across *two* rows. Comparing a column’s value across more than one row can be tricky to implement – unless you turn to Oracle functions LEAD/LAG.
Read more