Home > Database > Mysql Tutorial > Does `UNION ALL` Preserve the Order of Rows in SQL Result Sets?

Does `UNION ALL` Preserve the Order of Rows in SQL Result Sets?

Linda Hamilton
Release: 2024-12-31 00:24:09
Original
272 people have browsed it

Does `UNION ALL` Preserve the Order of Rows in SQL Result Sets?

Does UNION ALL Guarantee Order in Result Sets?

In SQL, the UNION ALL operator combines the results of multiple SELECT statements. However, it does not guarantee the order of the results. In the absence of an ORDER BY clause, the order of the rows is undefined and may vary.

Consider the example provided in the question:

SELECT 'O'
UNION ALL
SELECT 'R'
UNION ALL
SELECT 'D'
UNION ALL
SELECT 'E'
UNION ALL
SELECT 'R'
Copy after login

It is possible that the results will be displayed in the order "O-R-D-E-R," but there is no guarantee. The order may differ depending on factors such as the database engine, data distribution, and other optimizations.

To enforce a specific order, an ORDER BY clause must be used. For the given example, the SortOrder column can be added to each SELECT statement:

SELECT 'O', 1 SortOrder
UNION ALL
SELECT 'R', 2
UNION ALL
SELECT 'D', 3
UNION ALL
SELECT 'E', 4
UNION ALL
SELECT 'R', 5
ORDER BY SortOrder
Copy after login

This query will explicitly sort the results in the order "O-R-D-E-R." Please note that adding the SortOrder column is only necessary if the desired order is different from the default order (which is undefined in this case).

The above is the detailed content of Does `UNION ALL` Preserve the Order of Rows in SQL Result Sets?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template