This is a slightly strange use case admittedly, but how do you order the results of a simple union like this alphabetically?
select name
from Reviewer
union
select model
from Car;
This is a slightly strange use case admittedly, but how do you order the results of a simple union like this alphabetically?
select name
from Reviewer
union
select model
from Car;
Ironically, in many databases, your query would return the values in alphabetical order. The sorting is done during the duplicate removal for union
.
Of course, you can't depend on that. So, you should include an order by
clause:
select name
from Reviewer
union
select model
from Car
order by name;
The order by
applies to the complete union
. The column name comes from the first subquery.
select val
from (
select name as val
from Reviewer
union
select model as val
from Car
) as x
order by val
Here is how to set alias
and ORDER BY
:
SELECT
name AS NameModel
FROM Reviewer
UNION
SELECT
model AS NameModel
from Car
ORDER BY
NameModel;
The ORDER BY
is evaluated after UNION
.
your sql :
select name
from Reviewer
union
select model
from Car;
Answer 1 :
select name from Reviewer
union
select model from Car
order by name;
Answer 2 :
select * from
(select name "id" from Reviewer
union
select model from Car) x
order by x.id;
select val
from (
select name as val
from Reviewer
union
select model as val
from Car
) as x
order by val
My answer and above both are same. In SQL, we can write in different ways.
We can also ignore as
operator.