Home >Database >Mysql Tutorial >How to Order Results from Multiple SELECT Statements Combined with UNION?

How to Order Results from Multiple SELECT Statements Combined with UNION?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-11 07:52:42598browse

How to Order Results from Multiple SELECT Statements Combined with UNION?

Sorting Combined SELECT Statement Results using UNION

The UNION operator combines results from multiple SELECT statements. While you might expect to order the final result set with a single ORDER BY clause, this isn't directly supported. The ORDER BY clause must be applied to the entire combined result set.

Here's the correct approach:

<code class="language-sql">SELECT id, name, age
FROM Student
WHERE age < 20
UNION
SELECT id, name, age
FROM Student
WHERE age >= 20
ORDER BY age;</code>

By placing ORDER BY age after the final SELECT statement, the sorting is applied to the unified output, correctly ordering all rows by the age column. This ensures proper ordering after the data from both queries has been merged.

The above is the detailed content of How to Order Results from Multiple SELECT Statements Combined with UNION?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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