Available in versions: Dev (3.19) | Latest (3.18) | 3.17 | 3.16 | 3.15 | 3.14 | 3.13 | 3.12 | 3.11 | 3.10 | 3.9

LAG

Applies to ✅ Open Source Edition   ✅ Express Edition   ✅ Professional Edition   ✅ Enterprise Edition

The LAG window function allows for getting the value of an expression evaluated on the previous row, or the nth previous row if an offset is given.

SELECT
  ID,
  lag(ID) OVER (ORDER BY ID),
  lag(ID, 2) OVER (ORDER BY ID),
  lag(ID, 2, -1) OVER (ORDER BY ID)
FROM
  BOOK;
create.select(
         BOOK.ID,
         lag(BOOK.ID).over(orderBy(BOOK.ID)),
         lag(BOOK.ID, 2).over(orderBy(BOOK.ID)),
         lag(BOOK.ID, 2, -1).over(orderBy(BOOK.ID)))
     .from(BOOK)
     .fetch();

Producing:

+----+------+------+------+
| id |  lag |  lag |  lag |
+----+------+------+------+
|  1 |      |      |   -1 |
|  2 |    1 |      |   -1 |
|  3 |    2 |    1 |    1 |
|  4 |    3 |    2 |    2 |
+----+------+------+------+

Dialect support

This example using jOOQ:

lag(BOOK.ID).over(orderBy(BOOK.ID))

Translates to the following dialect specific expressions:

-- AURORA_POSTGRES, BIGQUERY, COCKROACHDB, DB2, DUCKDB, EXASOL, FIREBIRD, H2, HANA, INFORMIX, MARIADB, MEMSQL, MYSQL, 
-- ORACLE, POSTGRES, REDSHIFT, SNOWFLAKE, SQLDATAWAREHOUSE, SQLITE, SQLSERVER, TERADATA, TRINO, VERTICA, YUGABYTEDB
lag(BOOK.ID) OVER (ORDER BY BOOK.ID)

-- ACCESS, ASE, AURORA_MYSQL, DERBY, HSQLDB, SYBASE
/* UNSUPPORTED */

(These are currently generated with jOOQ 3.19, see #10141), or translate your own on our website

References to this page

Feedback

Do you have any feedback about this page? We'd love to hear it!

The jOOQ Logo