RANGE Offset Needs One ORDER BY Column

RANGE frames with an offset need exactly one ORDER BY column; two ordering keys are rejected, while one timestamp column gives true time frames.

SqlData Integrity

Code

snippet
-- RANGE + 偏移的硬性规定:窗口定义里恰好一个 ORDER BY 列
-- (PostgreSQL SELECT 文档:In RANGE mode, use of an offset option requires
--   that there be exactly one ORDER BY column in the window definition)
CREATE TEMP TABLE sensor_readings (
    sensor   text NOT NULL,
    taken_at timestamptz NOT NULL,
    reading  numeric NOT NULL
);

INSERT INTO sensor_readings VALUES
    ('s1', '2026-11-01 10:00+00', 20.0),
    ('s1', '2026-11-01 10:30+00', 21.5),
    ('s1', '2026-11-01 11:00+00', 23.0);

-- 两个排序列会被直接拒绝(单列是硬约束)
-- SELECT sensor, avg(reading) OVER (ORDER BY sensor, taken_at
--        RANGE BETWEEN INTERVAL '1 hour' PRECEDING AND CURRENT ROW)
-- FROM sensor_readings;   -- 报错:RANGE 偏移要求 exactly one ORDER BY column

-- 正确:单一时间戳列,RANGE 偏移按时间距离圈行
SELECT sensor, taken_at, reading,
       round((avg(reading) OVER (
           ORDER BY taken_at
           RANGE BETWEEN INTERVAL '30 minutes' PRECEDING AND CURRENT ROW))::numeric, 2) AS rolling_avg
FROM sensor_readings
ORDER BY taken_at;

How the snippet works

What runs here is SELECT / INSERT / CREATE — sensor_readings are the objects involved.

sensor_readings is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.

Mechanically, the statements are built from: AVG aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Applying it

The file sets up its own scratch surface: it builds the session-local tables it works with (sensor_readings), so one full run against a throwaway database is enough.

Statements that matter

SELECT sensor, taken_at, reading,
       round((avg(reading) OVER (
           ORDER BY taken_at
           RANGE BETWEEN INTERVAL '30 minutes' PRECEDING AND CURRENT ROW))::numeric, 2) AS rolling_avg
FROM sensor_readings
ORDER BY taken_at;
INSERT INTO sensor_readings VALUES
    ('s1', '2026-11-01 10:00+00', 20.0),
    ('s1', '2026-11-01 10:30+00', 21.5),
    ('s1', '2026-11-01 11:00+00', 23.0);
CREATE TEMP TABLE sensor_readings (
    sensor   text NOT NULL,
    taken_at timestamptz NOT NULL,
    reading  numeric NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
The references are `sensor_readings`.