3181
MySQLERRORNotableWindow FunctionsHIGH confidence

RANGE frame requires ORDER BY

Production Risk

Low — caught at validation time.

Why it happens
  1. 1Specifying RANGE frame bounds without an ORDER BY clause in the window definition.
How to reproduce
trigger — this will error
trigger — this will error
SELECT SUM(val) OVER (RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) FROM t1;

expected output

ERROR 3181 (HY000): RANGE frame with PRECEDING or FOLLOWING requires exactly one ORDER BY expression.

Fix 1

Add an ORDER BY clause to the window

Add an ORDER BY clause to the window
SELECT SUM(val) OVER (ORDER BY id RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) FROM t1;

Why this works

RANGE semantics require an ordering expression to define the range.

Fix 2

Use ROWS instead if ordering is unavailable

Use ROWS instead if ordering is unavailable
SELECT SUM(val) OVER (ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM t1;

Why this works

ROWS frame does not require ORDER BY.

What not to do

Sources
Official documentation ↗

MySQL 8.0 — 3181 ER_WINDOW_RANGE_BOUND_WITHOUT_ORDERBY

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

← All MySQL errors