Oracle Database

Oracle Lag Function

In Oracle, an analytic function refers to functions that are used to calculate a set of rows. Analytic functions are mainly used to determine the various metrics such as percentiles, standard deviations, etc.

In this tutorial, we will learn how to use one of the Oracle LAG functions to access a row at a specific offset from the current row.

Oracle LAG() Function

The lag() function is used to fetch the value of a row in a table from the current row. For example, you can use it to get the value from five rows from your current position. You can use it to perform the calculations or comparisons between values over time.

The following shows the basic syntax of the function:

LAG(expr [, offset] [, default])
OVER (
    [ query_partition_clause]
    order_by_clause
)

The function accepts the following parameters:

  1. Expr – This defines the expression which is evaluated against the specified row value at the offset parameter.
  2. Offset – It sets the number of rows that you wish to go backward from the current row. By default, the function fetches the row that is behind your current one.
  3. Default – It allows the function to return a default value when it goes beyond the scope of the specified offset instead of a NULL value.
  4. Query_partition_clause – It specifies the partition by clause to organize the rows into various groups.
  5. Order_by_clause – It sets the order for the rows.

Oracle LAG() Function Example

This example demonstrates how to use the LAG() function.

select FIRST_NAME, LAST_NAME, SALARY, JOB_ID, lag(SALARY) over (order by SALARY asc)
from EMPLOYEES emp;

Result:

As you can see, the lag column contains the salary of the row behind it. If there is no row behind it such as the first column, the function returns NULL.

We can avoid this by setting the default parameter.

select FIRST_NAME, LAST_NAME, SALARY, lag(SALARY, 1, 0) over (order by SALARY asc) as prev
from EMPLOYEES emp;

Output:

We can also specify the offset value as shown in the following:

select FIRST_NAME, LAST_NAME, SALARY, lag(SALARY, 5, 0) over (order by SALARY asc) as prev
from EMPLOYEES emp;

In this case, the query should fetch five columns behind it as follows:

To use the lag function with a partition by clause, we can run the following command:

select FIRST_NAME, LAST_NAME, JOB_ID SALARY, lag(SALARY, 1, 0) over (partition by JOB_ID order by SALARY asc) as prev
from EMPLOYEES emp;

Result:

Conclusion

In this post, we discussed how to use the Oracle lag() function to fetch the previous rows from the current position at a given offset.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list