SQL intermediate

How to Calculate Differences Between Rows Using LAG?

The SQL LAG function allows you to access data from the previous row, making it easy to calculate differences in a time series.

Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.

The formula

Prompt

"Calculate the difference between each row and the previous row in a time series using LAG"

SQL
SELECT value, value - LAG(value) OVER (ORDER BY date_column) AS difference FROM your_table;

This SQL query calculates the difference between the current row's value and the previous row's value based on a specified order.

Step-by-step breakdown

  1. Use the LAG function to access the previous row's value.
  2. Specify the column to order by, typically a date or timestamp.
  3. Subtract the previous row's value from the current row's value.
  4. Alias the result as 'difference' for clarity.

Edge cases & warnings

  • The first row will return NULL since there is no previous row.
  • Rows with NULL values may affect the calculation if not handled.
  • If the ordering column has duplicate values, the results may be inconsistent.
  • Data types must be compatible for subtraction; otherwise, an error will occur.

Examples

Prompt

"Value: 100, Previous Value: 90"

SQL
Difference: 10
Prompt

"Value: 150, Previous Value: NULL"

SQL
Difference: NULL

Frequently asked questions

What happens if there is no previous row?

The result will be NULL for the first row.

Can I use LAG with multiple columns?

Yes, you can use LAG for multiple columns by repeating the function for each.

How do I handle NULL values in my calculations?

You can use COALESCE to replace NULLs with a default value before performing calculations.

Can't find what you need?

Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.