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!