Pages

OracleEBSpro is purely for knowledge sharing and learning purpose, with the main focus on Oracle E-Business Suite Product and other related Oracle Technologies.

I'm NOT responsible for any damages in whatever form caused by the usage of the content of this blog.

I share my Oracle knowledge through this blog. All my posts in this blog are based on my experience, reading oracle websites, books, forums and other blogs. I invite people to read and suggest ways to improve this blog.


Wednesday, February 27, 2013

Oracle PL/SQL: Lag Function


In Oracle/PLSQL, the lag function is an analytic function that lets you query more than one row in a table at a time without having to join the table to itself. It returns values from a previous row in the table. To return a value from the next row, try using the lead function.

Syntax

The syntax for the lag function is:

lag ( expression [, offset [, default] ] )
over ( [ query_partition_clause ] order_by_clause )

expression is an expression that can contain other built-in functions, but can not contain any analytic functions.
offset is optional. It is the physical offset from the current row in the table. If this parameter is omitted, the default is 1.
default is optional. It is the value that is returned if the offset goes out of the bounds of the table. If this parameter is omitted, the default is null.

Applies To

  • Oracle 11g, Oracle 10g, Oracle 9i, Oracle 8i

For Example

Let's take a look at an example. If we had an orders table that contained the following data:

ORDER_DATEPRODUCT_IDQTY
25/09/2007100020
26/09/2007200015
27/09/200710008
28/09/2007200012
29/09/200720002
30/09/200710004

And we ran the following SQL statement:


select product_id, order_date,
lag (order_date,1) over (ORDER BY order_date) AS prev_order_date
from orders;

It would return the following result:

PRODUCT_IDORDER_DATEPREV_ORDER_DATE
100025/09/2007<NULL>
200026/09/200725/09/2007
100027/09/200726/09/2007
200028/09/200727/09/2007
200029/09/200728/09/2007
100030/09/200729/09/2007

Since we used an offset of 1, the query returns the previous order_date.

If we had used an offset of 2 instead, it would have returned the order_date from 2 orders before. If we had used an offset of 3, it would have returned the order_date from 3 orders before....and so on.

If we wanted only the orders for a given product_id, we could run the following SQL statement:


select product_id, order_date,
lag (order_date,1) over (ORDER BY order_date) AS prev_order_date
from orders
where product_id = 2000;


It would return the following result:
PRODUCT_IDORDER_DATEPREV_ORDER_DATE
200026/09/2007<NULL>
200028/09/200726/09/2007
200029/09/200728/09/2007

In this example, it returned the previous order_date for product_id = 2000 and ignored all other orders.

No comments:

Post a Comment