22013ERRORTier 2 — Caution✅ HIGH confidenceinvalid preceding or following size in window function
Category: Data ExceptionVersions: All Postgres versions
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
- 1Using a negative value in ROWS BETWEEN N PRECEDING AND M FOLLOWING
- 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
SELECT SUM(amount) OVER (
ORDER BY date
ROWS BETWEEN -1 PRECEDING AND CURRENT ROW
) FROM sales;ERROR: frame starting offset must not be negative
Fix 1: Ensure frame PRECEDING and FOLLOWING values are non-negative
When the frame size is computed dynamically.
fix
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 docs: https://www.postgresql.org/docs/current/errcodes-appendix.html
🔧 Source ref: Class 22 — Data Exception
Confidence assessment
✅ HIGH confidence
Standard SQLSTATE for window frame validation. Stable across versions.
See also
🔗 Related errors
📄 Reference pages
Window FunctionsFrame Clause
⚙️ This error reference was generated with AI assistance and reviewed for accuracy. Examples are provided to illustrate common scenarios and may not cover every case. Always test fixes in a development environment before applying to production. Spotted an error? Suggest a correction →