SQL Server UNION - What is the default ORDER BY Behaviour

前端 未结 6 1996
生来不讨喜
生来不讨喜 2020-11-27 20:38

If I have a few UNION Statements as a contrived example:

SELECT * FROM xxx WHERE z = 1
UNION 
SELECT * FROM xxx WHERE z = 2
UNION
SELECT * FROM xxx WHERE z =         


        
6条回答
  •  庸人自扰
    2020-11-27 21:14

    A UNION can be deceptive with respect to result set ordering because a database will sometimes use a sort method to provide the DISTINCT that is implicit in UNION , which makes it look like the rows are deliberately ordered -- this doesn't apply to UNION ALL for which there is no implicit distinct, of course.

    However there are algorithms for the implicit distinct, such as Oracle's hash method in 10g+, for which no ordering will be applied.

    As DJ says, always use an ORDER BY

提交回复
热议问题