PostgreSQL分区后结果顺序保持疑惑:滚动最小值计算解析
问题:窗口函数排序是否会影响后续查询的行顺序?
我有一个定义如下的MyData表:
create table MyData ( id integer not null primary key, group_id uuid not null, enroll_info text not null, enroll_age integer not null default 0, enroll_information varchar not null, created_stamp date unique not null default now(), );
我使用以下查询计算滚动最小值:
with main_information as ( select *, ROW_NUMBER() OVER (partition by (group_id) order by (created_stamp)) as row_num -- -- -- NOTE_THIS from myTable) select *, case when count(*) over (partition by group_id rows between current row and following 3) >=3 then min(enroll_age) over (partition by (group_id) rows between current row and following 3) else 0 end as rolling_min_value from main_information;
滚动最小值的正确结果依赖于行按created_stamp排序,但我的查询中并未使用包含order by的窗口函数写法:min(enroll_age) over (partition by (group_id) order by (created_stamp) rows between current row and following 3)。
我原本预期分区内的行不会按created_stamp排序,但实际测试发现结果符合预期,且输出的created_stamp列均为有序状态(单个分区示例如下):
...|created_stamp |....//other columns including rolling_min_value _____________________________________ ...|2017-03-17 23:43:41 | ... ...|2017-04-17 23:43:41 | ... ...|2017-05-17 23:43:41 | ... ...|2017-06-17 23:43:41 | ... ...|2017-07-17 23:43:41 | ... ...|2017-08-17 23:43:41 | ... ...|2017-09-17 23:43:41 | ... ...|2017-10-17 23:43:41 | ...
我对此感到困惑:这种顺序是源于之前row_num的分区排序,还是仅仅是巧合?我的表中有220行数据,所有分区均呈有序状态。
回答
这不是巧合,但本质是数据库实现的默认行为,而非SQL标准规定的必然结果:
- 你在CTE的
ROW_NUMBER()窗口中指定了partition by group_id order by created_stamp,数据库为了计算行号,必须对每个group_id分区内的行按created_stamp排序。 - 当主查询从CTE读取数据时,多数主流数据库(如PostgreSQL、MySQL 8.0+)在没有其他排序指令的情况下,会保留CTE处理后的行顺序。这就导致你看到每个分区的
created_stamp是有序的,滚动最小值的计算也刚好符合预期。 - 但这种行为不具备通用性:SQL标准明确规定,除非在最外层查询显式添加
order by子句,否则结果集的行顺序是不保证的。哪怕CTE里有排序,数据库也可能在优化查询时调整行的顺序。 - 正确且严谨的做法是:在
min()窗口函数中明确添加order by created_stamp(确保滚动窗口的范围是按时间排序的),同时在主查询末尾加上order by group_id, created_stamp(确保最终输出的行顺序稳定)。修改后的关键代码如下:
min(enroll_age) over (partition by group_id order by created_stamp rows between current row and following 3)
内容的提问来源于stack exchange,提问作者juztcode
相关产品推荐
相关产品推荐

