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?
9条答案
按热度按时间ppcbkaq51#
but if you want to have all records from
Table_A
on the top of the result list, then you can add a user defined value, which you can use for ordering:6ju8rftf2#
You don't really need to have parenthesis. You can sort directly:
emeijp433#
Not an OP direct response, but I thought I would jimmy in here responding to the the OP's ERROR messsage, which may point you in another direction entirely!
All these answers are referring to an overall ORDER BY once the record set has been retrieved and you sort the lot.
What if you want to ORDER BY each portion of the UNION independantly, and still have them "joined" in the same SELECT?
Note the TOP 1000 is an arbitary number. Use a big enough number to capture all of the data you require.
x0fgdtte4#
This solved my SELECT statement:
where id and name columns available in tables and you can use your columns .
aamkag615#
There will be times when you need to do something like this :
Pull top 5 from table 1 based on a sort
and bottom 5 from table 2 based on another sort
and union these together.
solution
this was the only way i was able to get around the error and worked fine for me.
isr3a4wc6#
2 is column number here .. In Oracle SQL you can use the column number by which you want to sort the data
x4shl7ld7#
Simply use that , no need parenthesis or anything else
ygya80vv8#
ORDER BY after the last UNION should apply to both datasets joined by union.
The solution shown below:
p4tfgftt9#