Averages and SQL Functions

How to use lag() in SQL?

Learn how to use lag() in SQL to read a value from the previous row, with PARTITION BY and ORDER BY examples, default values and a running-average comparison.

On this page
  1. The syntax
  2. Previous score for each student
  3. Change from the last test
  4. Setting the offset and default
  5. Comparing lag() with a running average
  6. Database support

LAG() is a window function. For each row, it returns a value from an earlier row, using the order you choose. By default it looks one row back, and if no earlier row exists, it returns NULL.

The syntax

LAG(column_name, offset, default_value) OVER (
  PARTITION BY partition_column
  ORDER BY sort_column
)

The offset and the default value are optional. The offset is how many rows back to look, and it defaults to 1. The default value is returned when no row exists that far back, and it defaults to NULL.

Previous score for each student

SELECT
  student_id,
  test_date,
  score,
  LAG(score) OVER (PARTITION BY student_id ORDER BY test_date) AS previous_score
FROM test_results;

PARTITION BY restarts the lookup for each student, so a student’s first test gets NULL rather than another student’s last score. ORDER BY sets which row counts as earlier. Without ORDER BY, the database has no guaranteed order, so “previous” has no meaning.

Change from the last test

SELECT
  student_id,
  test_date,
  score,
  score - LAG(score) OVER (PARTITION BY student_id ORDER BY test_date) AS change_from_last
FROM test_results;

The first test for each student returns NULL for the change, because there is no earlier score to subtract.

Setting the offset and default

LAG(score, 2, 0) OVER (PARTITION BY student_id ORDER BY test_date)

This looks two rows back, and returns 0 when there is no row that far back.

Comparing lag() with a running average

lag() returns one earlier value. AVG() with a ROWS frame reads a set of rows, so the two are often used side by side:

SELECT
  student_id,
  test_date,
  score,
  LAG(score) OVER (PARTITION BY student_id ORDER BY test_date) AS previous_score,
  AVG(score) OVER (
    PARTITION BY student_id
    ORDER BY test_date
    ROWS BETWEEN 1 PRECEDING AND CURRENT ROW
  ) AS avg_of_two
FROM test_results;

Here avg_of_two is the average of the current score and the one before it. The first row’s average uses only its own score.

Database support

MySQL 8.0 and later, PostgreSQL, SQL Server 2012 and later, and SQLite 3.25 and later support lag(). MySQL 5.7 and earlier do not have window functions, so lag() is not available there.

The complete guide to averages and sql functions

How to Calculate the Average for Each Row in SQL
Read the guide

Keep exploring

Guides from other topics

All topics →