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
Release: 2025-01-11 07:52:42
Original
593 people have browsed it

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>
Copy after login

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!

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