Apply order by first, then combine result set
First attempt
The following example puts the
select
statements with the
order by
clauses within parentheses so that the the records of
tq84_tab_1
are ordered independently from those of
tq84_tab_2
. Additionally, the records of
tq84_tab_1
are returned first,
then the records of
tq84_tab_2
.
(select * from tq84_tab_1 order by id) union all
(select * from tq84_tab_2 order by id)
Unfortunately, I was only able to execute this query without errors on MySQL.
Using subqueries
The order by
clause might be put into a subquery in order to achieve the same result on Oracle 18c, MySQL and SQLite.
select * from (select * from tq84_tab_1 order by id) t union all
select * from (select * from tq84_tab_2 order by id) t;
SQL Server complains with The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified..
Using an additional column
In order to finally make the desired ordering possible in SQL Server, too, an additional column might be added to the select
statements:
select t.*, 1 o from tq84_tab_1 t union all
select t.*, 2 o from tq84_tab_2 t
order by
o, id
This also works with SQLite and MySQL, but Oracle fails with ORA-00904: "ID": invalid identifier.