tags:

views:

28

answers:

3

I am retuning table results for different queries but each table will be in the same format and will all be in one final table. If I want the results for query 1 to be listed first and query2 second etc, what is the easiest way to do it?

Does UNION append the table or are is the combination random?

A: 

UNION appends the second query to the first query, so you have all the first rows first.

Tor Valamo
+3  A: 

The SQL standard does not guarantee an order unless explicitly called for in an order by clause. In practice, this usually comes back chronologically, but I would not rely on it if the order is important.

Across a union you can control the order like this...

select
   this,
   that
from
   (
   select
      this,
      that
   from
       table1
   union
   select
     this,
     that
   from
     table2
   )
order by
   that,
   this;
dacracot
My sql is Oracle syntax. Not sure if this is implemented the same for other RDBMS.
dacracot
another way to control order is to put a"1 as rank" field in the first part and then a "2 as rank" in the second part, and then "order by rank"
Tor Valamo
A: 

You can use:

SELECT Col1, Col2,...
FROM (
    SELECT Col1, Col2,..., 1 AS intUnionOrder
    FROM ...
) AS T1
UNION ALL (
    SELECT Col1, Col2,..., 2 AS intUnionOrder
    FROM ...
) AS T2
ORDER BY intUnionOrder, ...
Paul