Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql server union but keep order

Tags:

sql-server

Is there a way to union two tables, but keep the rows from the first table appearing first in the result set?

For example:

Table1

name        surname ------------------- John         Doe Bob          Marley Ras          Tafari 

Table2

name       surname ------------------ Lucky      Dube Abby       Arnold 

I want the result set to be:

name        surname ------------------- John         Doe Bob          Marley  Ras          Tafari Lucky      Dube Abby       Arnold 

Unfortunately, union somehow reorders the table. Is there a way around this?

like image 296
Afroman Makgalemela Avatar asked Jan 17 '14 09:01

Afroman Makgalemela


People also ask

Does UNION maintain order?

UNIONS cause orders to be lost as it does a match up. You can fake it by adding a bogus limit to the union, then order the whole result.

Does order matter in UNION SQL?

Within UNION each SELECT statement must have the same columns number. The columns must have analogous data types. In each SELECT statement, the columns must be in the same order.

Does UNION all sort the data?

You can use UNION ALL to avoid sorting, but UNION ALL will return duplicates. So you only use UNION ALL to avoid sorting if you know that there are no duplicate rows in the tables).


2 Answers

Try this :-

Select *  from (  Select name,surname, 1 as filter from  Table1 Union all Select name,surname , 2 as filter from Table2 ) order by filter 
like image 50
praveen Avatar answered Sep 20 '22 20:09

praveen


The only way to guarantee output order is to use ORDER BY:

SELECT name,surname,1 as rs FROM table1 UNION ALL SELECT name,surname,2 FROM table2 ORDER BY rs 

If you don't want rs to appear in the final result set, do the UNION as a subquery:

SELECT name,surname FROM (   SELECT name,surname,1 as rs   FROM table1   UNION ALL   SELECT name,surname,2   FROM table2 ) t ORDER BY rs 
like image 33
Damien_The_Unbeliever Avatar answered Sep 17 '22 20:09

Damien_The_Unbeliever