How to order by with union in SQL?
Solution 1:
Just write
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
Order by name
the order by is applied to the complete resultset
Solution 2:
Select id,name,age
from
(
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
) results
order by name
Solution 3:
In order to make the sort apply to only the first statement in the UNION
, you can put it in a subselect with UNION ALL
(both of these appear to be necessary in Oracle):
Select id,name,age FROM
(
Select id,name,age
From Student
Where age < 15
Order by name
)
UNION ALL
Select id,name,age
From Student
Where Name like "%a%"
Or (addressing Nicholas Carey's comment) you can guarantee the top SELECT
is ordered and results appear above the bottom SELECT
like this:
Select id,name,age, 1 as rowOrder
From Student
Where age < 15
UNION
Select id,name,age, 2 as rowOrder
From Student
Where Name like "%a%"
Order by rowOrder, name