Abdalla Ismail Abdalla Ismail - 3 days ago 7
SQL Question

Sql sort by query

I have an Sql query that is the union of three queries, for example :

query1
Union
query2
Union
query3


I want to ask if there is a way to have the output respective by queries , such that the results of query1 are first in the ResultSet , query2 second and query3 at then end.

Thank you

Answer

You would normally do this by including a column specifying the query and ordering by that:

select . . .
from ((select q.*, 1 as ordering from (<query1>) q) union all
      (select q.*, 2 as ordering from (<query2>) q) union all
      (select q.*, 3 as ordering from (<query3>) q)
     ) q
order by ordering;

Note: This replaces the union with union all, so duplicates are not removed.

Comments