Aggregate Window Functions in PostgreSQL

From the PostgreSQL Advanced Features cheat sheet ยท Window Functions ยท verified Jul 2026

Aggregate Window Functions

Running totals, moving averages, and cumulative calculations

sql
-- Running total
SELECT
  date,
  amount,
  SUM(amount) OVER (ORDER BY date) as running_total
FROM sales;

-- Moving average (3-row window)
SELECT
  date,
  price,
  AVG(price) OVER (
    ORDER BY date
    ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
  ) as moving_avg_3
FROM stock_prices;

-- Cumulative percentage
SELECT
  product,
  revenue,
  SUM(revenue) OVER (ORDER BY revenue DESC) as cumulative,
  100.0 * SUM(revenue) OVER (ORDER BY revenue DESC) / 
    SUM(revenue) OVER () as cumulative_pct
FROM product_sales;

-- DETAILED_TAB:
-- Complex window frames
SELECT
  date,
  sales,
  -- Previous row
  LAG(sales, 1) OVER (ORDER BY date) as prev_sales,
  -- Next row
  LEAD(sales, 1) OVER (ORDER BY date) as next_sales,
  -- First value in window
  FIRST_VALUE(sales) OVER (
    PARTITION BY EXTRACT(YEAR FROM date)
    ORDER BY date
  ) as year_first,
  -- Difference from previous
  sales - LAG(sales, 1) OVER (ORDER BY date) as growth
FROM daily_sales;
๐Ÿ’ก ROWS BETWEEN defines the window frame
๐Ÿ“Œ LAG/LEAD access other rows without self-join
โšก Running totals much faster than correlated subqueries
๐ŸŸข Essential for time-series analysis
๐Ÿ”— Related: range-based windows with RANGE BETWEEN
window-functionsaggregates

More PostgreSQL tasks

Back to the full PostgreSQL Advanced Features cheat sheet