Override default alphabetically ORDER BY with UNION from 2+ tables?

A really quick question ... I have 4 tables that are UNIONlike this:

SELECT * FROM table1  
UNION
SELECT * FROM table2  
UNION
SELECT * FROM table3  
UNION
SELECT * FROM table4

Without an indication, ORDER BYqueries are ordered by the first column in ascending order in alphabetical order (which in my case is a type varchar). I do not want to ORDER BY [Column1] DESC.

I just want to order the results in the same order as the UNION-ed tables themselves . 1, 2, 3, 4.

Is there an easy way to do this?

Thank!!

+3
source share
1 answer

One of the methods

SELECT *,1 as SortOrder FROM table1  
UNION
SELECT *,2 FROM table2  
UNION
SELECT *,3 FROM table3  
UNION
SELECT *,4 FROM table4
order by SortOrder 

what happens is that you use UNION, the sql server then makes the result set great, to do this, to sort the tables

UNION ALL?

+4

All Articles