Lag Function in BigQuery: Syntax & Examples

Formulas & functions · Updated November 22, 2026

The LAG function in BigQuery is a window function that returns the value of an expression from a previous row within the same result set, based on a specified offset. For example, LAG(sales, 1) OVER (ORDER BY date) gives you the sales from the immediately preceding row, which is essential for calculating day-over-day changes or comparing a value to its prior occurrence.

What Exactly Does LAG Do?

LAG lets you access data from a row that comes before the current row in the result set, without needing a self-join. It is part of BigQuery’s analytic (window) functions, which compute values across a set of rows related to the current row. The function returns a value from a column in a prior row, determined by an offset (default 1) and an optional partitioning and ordering.

Think of it as a way to “look backward” in your data. If your table contains daily stock prices, LAG can fetch yesterday’s price for each row. If your data has multiple entities (like multiple products), you can use PARTITION BY to reset the “previous row” for each product, so you compare within each group, not across the whole table.

LAG Syntax and Parameters

The basic syntax is:

LAG(expression [, offset [, default_expression]]) OVER ( [PARTITION BY partition_expression] ORDER BY sort_expression [ASC|DESC] )

Parameters:

  • expression: The column or value you want to retrieve from the previous row.
  • offset: An integer (default 1) indicating how many rows back to look. Offset 0 returns the current row’s value.
  • default_expression: The value returned if the offset goes beyond the partition (e.g., the first row). If omitted, NULL is returned.
  • PARTITION BY: Divides the result set into groups; LAG operates independently within each partition.
  • ORDER BY: Defines the logical order of rows within each partition. This is mandatory – without it, the “previous row” is undefined.

Example: Suppose you have a table sales with columns date and amount. To get the previous day’s amount:

SELECT date, amount, LAG(amount) OVER (ORDER BY date) AS prev_amount FROM sales ORDER BY date;

If the first row has no previous row, prev_amount will be NULL. To use a default instead:

LAG(amount, 1, 0) OVER (ORDER BY date)

This returns 0 for the first row.

Practical Use Cases for LAG

LAG is widely used in time-series and comparative analysis. Common scenarios include:

  • Period-over-period changes: Compare current sales to previous month’s sales.
  • Calculating differences: Subtract the previous value from the current to get the change (e.g., amount - LAG(amount) OVER (ORDER BY date)).
  • Growth rates: Compute percentage change: (amount - LAG(amount)) / LAG(amount) * 100.
  • Session or sequence analysis: Identify when a user returns after a gap by comparing timestamps.
  • Filling gaps: Use the previous non-null value to replace NULLs (though LEAD or other techniques may be more appropriate).

For example, to get the daily difference in a stock price table:

SELECT date, close, close - LAG(close) OVER (ORDER BY date) AS daily_change FROM stock_prices;

LAG vs LEAD: Which to Use?

LEAD is the mirror image of LAG – it fetches a value from a following row. The choice depends on your direction of comparison:

  • Use LAG when you need the previous row’s value (e.g., compare today to yesterday).
  • Use LEAD when you need the next row’s value (e.g., compare today to tomorrow).

Both share the same syntax structure, with the same offset and default parameters. In many cases, you could swap them by reversing the order, but using the right one keeps your query readable.

Common Pitfalls and How to Avoid Them

Several mistakes trip up users new to LAG:

  • Forgetting ORDER BY: Without it, the function may return arbitrary rows. Always include an ORDER BY that defines the logical sequence.
  • Misunderstanding PARTITION BY: If you omit it, LAG treats the entire result set as one partition. For multi-entity data, you must partition by the entity column (e.g., PARTITION BY product_id).
  • Offsets beyond the partition: When the offset goes past the start of the partition, the default (or NULL) is returned. Be aware that default_expression is not evaluated until needed, so it can be a literal or a column.
  • Ignoring NULLs in the previous row: If the previous row’s value is NULL, LAG returns NULL, which can affect calculations. Use IFNULL or COALESCE to handle it.
  • Performance with large datasets: Window functions can be memory-intensive. Ensure your query is optimized by filtering data early and using appropriate partitioning.

Another subtle issue: the ORDER BY columns should be unique to get a deterministic result. If you have ties (e.g., same date for multiple rows), the order among ties is not guaranteed. Add a tiebreaker column to the ORDER BY.

Performance and Cost Considerations

In BigQuery, you are billed for the amount of data processed, not the number of queries. LAG itself does not add extra cost beyond the data scanned by the query. However, window functions can increase computation time, especially with large partitions. To keep costs down:

  • Filter your data with WHERE clauses before applying window functions.
  • Use partitioning and clustering on your tables to reduce the data scanned.
  • Avoid using LAG on unpartitioned tables with billions of rows if you only need a small slice.

Also, note that BigQuery caches results, so repeated queries on the same data may be free if the cache is hit.

Alternatives to LAG

Sometimes LAG isn’t the best tool. Alternatives include:

  • Self-join: Join the table to itself on a condition like t1.date = t2.date - 1. This can be slower and more verbose but works in older SQL dialects.
  • LEAD: As mentioned, for forward-looking comparisons.
  • FIRST_VALUE / LAST_VALUE: To get the first or last value in a partition, which is different from a fixed offset.
  • ROW_NUMBER: If you need to identify a specific row number, you can combine it with a subquery to emulate LAG, but it’s more complex.

For most cases, LAG is the cleanest and most efficient choice.

Frequently Asked Questions

Can I use LAG without an ORDER BY?

Technically, BigQuery requires an ORDER BY clause in the OVER() for LAG. If you omit it, you’ll get an error. The ORDER BY defines what “previous” means, so it’s essential.

What is the difference between LAG and ROW_NUMBER?

ROW_NUMBER assigns a sequential number to each row, while LAG retrieves a value from a previous row. They serve different purposes: ROW_NUMBER is for ranking, LAG is for accessing prior values.

Does LAG work with NULL values?

Yes, LAG returns NULL if the previous row’s value is NULL, or if the offset goes beyond the partition and no default is specified. You can use IFNULL to replace NULLs after the fact.

Can I use LAG in a WHERE clause?

No, window functions like LAG cannot be used directly in a WHERE clause. You need to wrap the query in a subquery or use a CTE, then filter on the result.

Is LAG available in standard SQL or only legacy?

LAG is available in BigQuery’s standard SQL, which is the default. It is not available in legacy SQL; you’d need to use a self-join there.

How do I calculate a moving average with LAG?

LAG alone only gives one previous value. For a moving average, you’d typically use AVG with a ROWS frame, like AVG(amount) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW). LAG can be used to get a specific prior value, but not a range.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.