Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use order by with union all in sql?

Tags:

sql

sql-server

I tried the sql query given below:

SELECT * FROM (SELECT *  FROM TABLE_A ORDER BY COLUMN_1)DUMMY_TABLE UNION ALL  SELECT * FROM TABLE_B  

It results in the following error:

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

I need to use order by in union all. How do I accomplish this?

like image 326
Wella Avatar asked Mar 18 '13 05:03

Wella


People also ask

Can we use ORDER BY in UNION all?

The UNION ALL operator can use the ORDER BY clause to order the results of the query in SQL Server (Transact-SQL).

Can we use ORDER BY in UNION All in Oracle?

You can use UNION ALL to avoid sorting, but UNION ALL will return duplicates.

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.


2 Answers

SELECT  *  FROM          (             SELECT * FROM TABLE_A              UNION ALL              SELECT * FROM TABLE_B         ) dum -- ORDER BY ..... 

but if you want to have all records from Table_A on the top of the result list, the you can add user define value which you can use for ordering,

SELECT  *  FROM          (             SELECT *, 1 sortby FROM TABLE_A              UNION ALL              SELECT *, 2 sortby FROM TABLE_B         ) dum ORDER   BY sortby  
like image 123
John Woo Avatar answered Sep 28 '22 23:09

John Woo


You don't really need to have parenthesis. You can sort directly:

SELECT *, 1 AS RN FROM TABLE_A UNION ALL  SELECT *, 2 AS RN FROM TABLE_B ORDER BY RN, COLUMN_1 
like image 20
Giorgi Nakeuri Avatar answered Sep 29 '22 01:09

Giorgi Nakeuri