Home > Database > Mysql Tutorial > How to Properly Order Results from a SQL UNION?

How to Properly Order Results from a SQL UNION?

Susan Sarandon
Release: 2025-01-11 06:03:42
Original
472 people have browsed it

How to Properly Order Results from a SQL UNION?

UNION and sorting in SQL

In SQL, the UNION operator allows us to combine multiple SELECT statements into a single result set. However, sorting combined data can be tricky when each SELECT statement may return different data.

Consider the following query that retrieves data from the Student table based on two criteria:

<code class="language-sql">SELECT id, name, age
FROM Student
WHERE age > 20
UNION
SELECT id, name, age
FROM Student
WHERE Name LIKE "%a%";</code>
Copy after login

We want to sort the combined result set by the name column. Unfortunately, the following query does not work as expected:

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

In this query, the ORDER BY clause is applied to the combined results of the WHERE conditions, rather than the complete result set of the UNION. Therefore, the data is not sorted.

To sort the combined result set by name, simply move the ORDER BY clause outside the UNION operator:

<code class="language-sql">SELECT id, name, age
FROM Student
WHERE age > 20
UNION
SELECT id, name, age
FROM Student
WHERE Name LIKE "%a%"
ORDER BY name;</code>
Copy after login

In this modified query, the ORDER BY clause is applied to the complete result set, ensuring that the combined data is sorted correctly.

The above is the detailed content of How to Properly Order Results from a SQL 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