Abdalla Ismail Abdalla Ismail - 1 year ago 88
SQL Question

Sql sort by query

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


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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download