Tuesday, January 21, 2020

Lag and lead in sql

LEAD() and LAG() Function

The LEAD() and LAG() function in MySQL are used to get preceding and succeeding value of any row within its partition. These functions are termed as nonaggregate Window functions.

The Window functions are those functions which perform operations for each row of the partition or window. These functions produce the result for each query row unlikely to the aggregate functions that group them and results in a single row.
  • The row on which operation occur is termed as current row.
  • The set of rows which are realted to current row or using which function opaerates on current row is termed as Window.
The LAG() function is used to get value from row that precedes the current row.
The LEAD() function is used to get value from row that succedes the current row.
For LEAD() function-
LEAD(expr, N, default) 
          OVER (Window_specification | Window_name)
For LAG() function-
LAG(expr, N, default) 
          OVER (Window_specification | Window_name)
The N and default argument in the function is optional.
Parameters used:
  1. expr: It can be a column or any bulit-in function.
  2. N: It is a positive value which determine number of rows preceding/succeeding the current row. If it is omitted in query then its default value is 1.
  3. default: It is the default value return by function in-case no row precedes/succeedes the current row by N rows. If it is missing then it is by default NULL.
  4. OVER(): It defines how rows are partitioned into groups. If OVER() is empty then function compute result using all rows.
  5. Window_specification: It consist of query partition clause which determines how the query rows are partitioned and ordered.
  6. Window_name: If window is specified elsewhere in the query then it is referenced using this Window_name.

No comments:

Post a Comment