On this page
  1. LAG
  2. Syntax & Overview
  3. Notes & Best Practices
  4. Example

LAG

Prev: `RANK` | Up: functions | Next: `LOWER`
Rel: functions, Aggregations, CTEs & Window Functions
Ref: PostgreSQL — SQL Commands
Tags: #public #databases #sql #functions #tier/core


Syntax & Overview

LAG(total, 1, 0) OVER (PARTITION BY user_id ORDER BY day)  /* + LEAD() */

Accesses the previous (LAG) or next (LEAD) row's value without a self-join.

Notes & Best Practices

Example

SELECT day, revenue,
       revenue - LAG(revenue, 1, revenue) OVER (ORDER BY day) AS daily_delta
FROM daily_sales;

Linked from

Related notes