22013
PostgreSQLERRORNotableData ExceptionHIGH confidence

invalid preceding or following size in window function

What this means

SQLSTATE 22013 is raised when a window frame ROWS or RANGE clause specifies a preceding or following value that is negative or otherwise invalid.

Why it happens
  1. 1Using a negative value in ROWS BETWEEN N PRECEDING AND M FOLLOWING
  2. 2A dynamic expression for the frame size evaluates to a negative number
How to reproduce

Window function with negative frame size.

trigger — this will error
trigger — this will error
SELECT SUM(amount) OVER (
  ORDER BY date
  ROWS BETWEEN -1 PRECEDING AND CURRENT ROW
) FROM sales;

expected output

ERROR:  frame starting offset must not be negative

Fix

Ensure frame PRECEDING and FOLLOWING values are non-negative

WHEN When the frame size is computed dynamically.

Ensure frame PRECEDING and FOLLOWING values are non-negative
SELECT SUM(amount) OVER (
  ORDER BY date
  ROWS BETWEEN GREATEST(frame_size, 0) PRECEDING AND CURRENT ROW
) FROM sales;

Why this works

GREATEST clamps the frame offset to 0 or above, preventing 22013.

Sources
Official documentation ↗

Class 22 — Data Exception

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PostgreSQL errors