Search notes:

Oracle: Analytic functions LAG and LEAD

The analytic function LAG returns a value of a «previous», LEAD a value of a «following» record.
create table tq84_lag_vs_lead (
  a number,
  t varchar2(10)
);

insert into tq84_lag_vs_lead values (1, 'one'  );
insert into tq84_lag_vs_lead values (2, 'two'  );
insert into tq84_lag_vs_lead values (3, 'three');
insert into tq84_lag_vs_lead values (4, 'four' );
insert into tq84_lag_vs_lead values (5, 'five' );


select
  t,
  lead(t   ) over (order by a) lead_1,
  lag (t   ) over (order by a) lag_1,
  lead(t, 3) over (order by a) lead_3,
  lag (t, 3) over (order by a) lag_3
from
  tq84_lag_vs_lead;

drop table tq84_lag_vs_lead purge;
Github repository Oracle-Patterns, path: /SQL/select/analytical_functions/lag-vs-lead.sql
The previous SQL statement returns
T          LEAD_1     LAG_1      LEAD_3     LAG_3     
---------- ---------- ---------- ---------- ----------
one        two                   four                 
two        three      one        five                 
three      four       two                             
four       five       three                 one       
five                  four                  two   

See also

Fill missing values (gaps) with previous value.
Compare with FIRST_VALUE, NTH_VALUE etc.
SQL: LAG and LEAD
Analytic functions in Oracle

Index