可以保证子选择的排序顺序吗?

时间:2018-09-10 11:02:28

标签: sql oracle

是否保证语句的排序顺序

SELECT nr
FROM
(
    SELECT 1 AS nr FROM dual
    UNION
    SELECT 2 AS nr FROM dual
    UNION
    SELECT 3 AS nr FROM dual
);

结果集始终为

1
2
3

2 个答案:

答案 0 :(得分:7)

不,不能保证。 SQL表表示无序集。 SQL结果集也是无序的-除非代码中有明确的ORDER BY

如果没有ORDER BY,将获得相同的三行,但值可以为任意顺序。我强烈建议您执行以下操作:

SELECT nr
FROM (SELECT 1 AS nr FROM dual
      UNION ALL
      SELECT 2 AS nr FROM dual
      UNION ALL
      SELECT 3 AS nr FROM dual
     ) x
ORDER BY nr;

请注意,这使用UNION ALL而不是UNIONUNION会导致删除重复项的开销-该数据不需要这样做。

答案 1 :(得分:1)

使用订单-可以保证

SELECT nr
FROM
(
    SELECT 1 AS nr FROM dual
    UNION
    SELECT 2 AS nr FROM dual
    UNION
    SELECT 3 AS nr FROM dual
)a order by nr