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

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

Barbara Streisand
Release: 2025-01-11 07:12:41
Original
370 people have browsed it

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

Sorting Results from Combined SELECT and UNION Queries

Combining multiple SELECT queries using UNION presents a common challenge: how to sort the resulting dataset. Let's explore this issue and its solution.

The Challenge

When retrieving data from various tables or using multiple SELECT statements joined by UNION, achieving a specific column sort order can be tricky.

Detailed Explanation

Consider this scenario:

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

This query selects data from two distinct groups within the Student table. However, a simple ORDER BY name clause placed within either SELECT statement won't correctly sort the combined results.

The Solution

The correct approach is to apply the ORDER BY clause after the UNION statement. The following query demonstrates the proper method:

<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 name;</code>
Copy after login

This ensures that the ORDER BY clause operates on the complete dataset produced by the UNION operation, guaranteeing the desired sorted output.

The above is the detailed content of How to Order Results from Multiple SELECT Queries 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