Oracle LAG Function in 11g and 19c: Previous Row SQL Examples

Learn how Oracle LAG compares a row with the previous row in Oracle Database 11g and 19c, including PARTITION BY, deterministic ordering, default values, DATE literals, and DBMS_XPLAN performance checks.

Learn how Oracle LAG compares a row with the previous row in Oracle Database 11g and 19c, including PARTITION BY, deterministic ordering, default values, DATE literals, and DBMS_XPLAN performance checks.
Photo by AltumCode

Oracle Database 11g introduced the LAG() analytic function, and the same core syntax remains available in Oracle Database 19c. It returns a value from a previous row without requiring a self-join, making it useful for detecting changes, comparing consecutive records, and analyzing historical values within an ordered result set.

This example compares each address postcode with the previous postcode for the same site. PARTITION BY starts the comparison again for each site, while ORDER BY defines the row sequence. Unlike a self-join, the analytic expression keeps the comparison logic close to the selected value.

Oracle 11g and 19c compatibility

The basic LAG() syntax shown here works in both Oracle Database 11g and Oracle Database 19c. The important compatibility point is to keep the analytic window explicit: use PARTITION BY for independent histories and a deterministic ORDER BY for repeatable results. Oracle 19c also supports the same offset and default arguments, so an 11g query can usually be migrated without changing the window function itself.

Test the complete statement on the target schema because indexes, statistics, data types, privileges, and optimizer settings can affect execution plans. The examples below use standard Oracle SQL and do not claim that a sample result or explain plan proves production performance.

What the Oracle LAG function does

LAG(expression, offset, default) returns a value from an earlier row in the same analytic window. The expression is the value to retrieve, offset is the number of rows to look back, and default is returned when no previous row exists.

LAG syntax and parameters

The OVER clause controls how Oracle orders and groups rows. Use PARTITION BY when each customer, site, account, or other group needs an independent history.

The following illustrates the syntax of the LAG() function:

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

SQL query LAG

This query finds rows where the address postcode changed to 00-001 for a site. The previous postcode is calculated before the outer filter is applied, so the comparison uses the full history.

  SELECT  *
    FROM  (
              SELECT  t1.SITE_NUMBER
                     ,t1.JN_DATETIME
                     ,t1.ADR_POSTCODE
                     ,LAG (t1.ADR_POSTCODE, 1, '00-000') OVER (PARTITION BY t1.SITE_NUMBER ORDER BY t1.jn_datetime) AS PREV_ADR_POSTCODE
                FROM  t1 
          )
   WHERE      adr_postcode = '00-001'
          AND PREV_ADR_POSTCODE NOT IN ('00-001', '00-000')
          
ORDER BY  SITE_NUMBER;

Oracle 19c example with deterministic ordering

When multiple rows can share the same timestamp, add a stable tie-breaker such as a change ID to the analytic ordering. This prevents an arbitrary previous row from being selected. ANSI DATE literals also make the sample independent of session date formats.

SELECT site_number,
       jn_datetime,
       adr_postcode,
       LAG(adr_postcode, 1, 'UNKNOWN') OVER (
           PARTITION BY site_number
           ORDER BY jn_datetime, change_id
       ) AS previous_postcode
FROM site_address_history
WHERE jn_datetime >= DATE '2017-01-01'
ORDER BY site_number, jn_datetime, change_id;

Use LAG() when you need an earlier row and LEAD() when you need a later row. Both functions use the same OVER clause rules in Oracle 11g and Oracle 19c.

Test query data

CREATE TABLE T1
(
  SITE_NUMBER   VARCHAR2(16 BYTE),
  JN_DATETIME   DATE,
  ADR_POSTCODE  VARCHAR2(20 BYTE)
)
LOGGING 
NOCOMPRESS 
MONITORING;
SET DEFINE OFF;
Insert into KPREISKORN.T1
   (SITE_NUMBER, JN_DATETIME, ADR_POSTCODE)
 Values
   ('20001', DATE '2017-08-01', '00-001');
Insert into KPREISKORN.T1
   (SITE_NUMBER, JN_DATETIME, ADR_POSTCODE)
 Values
   ('20002', DATE '2017-04-20', '00-002');
Insert into KPREISKORN.T1
   (SITE_NUMBER, JN_DATETIME, ADR_POSTCODE)
 Values
   ('20001', DATE '2017-06-15', '00-003');
Insert into KPREISKORN.T1
   (SITE_NUMBER, JN_DATETIME, ADR_POSTCODE)
 Values
   ('20004', DATE '2017-06-20', '00-001');
Insert into KPREISKORN.T1
   (SITE_NUMBER, JN_DATETIME, ADR_POSTCODE)
 Values
   ('20001', DATE '2017-05-01', '00-001');
Insert into KPREISKORN.T1
   (SITE_NUMBER, JN_DATETIME, ADR_POSTCODE)
 Values
   ('20001', DATE '2017-09-25', '00-003');
Insert into KPREISKORN.T1
   (SITE_NUMBER, JN_DATETIME, ADR_POSTCODE)
 Values
   ('20001', DATE '2017-06-14', '00-001');
Insert into KPREISKORN.T1
   (SITE_NUMBER, JN_DATETIME, ADR_POSTCODE)
 Values
   ('20001', DATE '2017-03-25', '00-001');
Insert into KPREISKORN.T1
   (SITE_NUMBER, JN_DATETIME, ADR_POSTCODE)
 Values
   ('20001', DATE '2017-11-22', '00-001');
COMMIT;

SQL result

site_number jn_datetime adr_postcode prev_adr_postcode
20001 2017-08-01 15:01:31 00-001 00-003

Understanding the SQL result

The result shows site 20001 with the current postcode 00-001 and the previous postcode 00-003. Because the previous value is different, this row identifies a postcode change in the site history.

LAG versus a self-join

A self-join can compare rows from the same table, but it usually requires more join conditions and can be harder to maintain. LAG() expresses the previous-row relationship directly in the analytic window.

Common LAG mistakes

  • Using the wrong ORDER BY expression and therefore comparing rows in the wrong sequence.
  • Forgetting that the first row in each partition has no previous value unless a default is supplied.
  • Filtering rows before calculating LAG() when the comparison needs the complete history.
  • Ignoring duplicate timestamps, which can make row ordering nondeterministic.

Execution plans and performance checks

For a real Oracle 19c workload, inspect the plan instead of assuming that an analytic function is faster or slower than a self-join. After testing with representative data, review the plan with DBMS_XPLAN.DISPLAY:

EXPLAIN PLAN FOR
SELECT site_number,
       LAG(adr_postcode) OVER (PARTITION BY site_number ORDER BY jn_datetime, change_id)
FROM site_address_history;

SELECT *
FROM TABLE(DBMS_XPLAN.DISPLAY(NULL, NULL, 'BASIC'));

Keep the partition and ordering columns aligned with the access patterns of the query, gather current optimizer statistics, and compare plans on the target Oracle version. MATCH_RECOGNIZE is an optional advanced feature for multi-row pattern detection, but LAG() is usually the clearer choice for a simple previous-row comparison.

Frequently asked questions

What does Oracle LAG return?

LAG() returns a value from a previous row in the ordered analytic window.

What is the difference between LAG and LEAD?

LAG() looks backward, while LEAD() looks forward to a later row.

Does LAG require a self-join?

No. LAG compares rows within an analytic window without a self-join.

What happens when there is no previous row?

Oracle returns NULL unless the optional default argument is supplied.

Does the LAG syntax change in Oracle 19c?

No. The core LAG(expression, offset, default) OVER (...) syntax used in this article is compatible with Oracle Database 11g and 19c. Validate the surrounding schema, privileges, and execution plan when migrating.

How should I check LAG performance in Oracle 19c?

Test with representative data, use a deterministic analytic ORDER BY, and inspect the resulting plan with DBMS_XPLAN.DISPLAY rather than relying on a generic benchmark.

How it works together

Run the examples in an SQL playground, or explore the related SQL articles and PL/SQL database examples:

2026-04-10sql Off Comments off on Oracle LAG Function in 11g and 19c: Previous Row SQL Examples1176