views:

3519

answers:

4

This is my first attempt at answering my own question, since someone may well run into this and so it might be of help. Using Firebird, I want to combine the results of two queries using UNION ALL, then sort the resulting output on a given column. Something like:

(select C1, C2, C3 from T1)
union all 
(select C1, C2, C3 from T2)
order by C3

The parentheses came from valid syntax for other databases, and are needed to make sure the arguments to UNION ALL (an operation that's defined to work on tables - i.e. an unordered set of records) don't try to be ordered individually. However I couldn't get this syntax to work in Firebird - how can it be done?

+1  A: 

Perform the UNION ALL in a view (without the ORDER BY clause), then select from the view using ORDER BY.

Chris
+1 for "backwards" compatibility, the other answers doesn't work in Firebird 1.5
Eliseo Ocampos
+4  A: 
SELECT C1, C2, C3
FROM (
    select C1, C2, C3 from T1
    union all 
    select C1, C2, C3 from T2
)
order by C3
Cade Roux
Thank you so much... I couldn't work out how to get the inner clause without the intermediate view.
Chris
+5  A: 

Field names are not required to be equal. That's why you can't use the field name in the order by.
You may use the field index instead. As in:

(select C1, C2, C3 from T1)
union all 
(select C7, C8, C9 from T2)
order by 3
Douglas Tosi
+2  A: 

In Firebird 1.5 this works for me

create view V1 (C1, C2, C3) as
  select C1, C2, C3 from T1
  union all 
  select C1, C2, C3 from T2

and then

select C1, C2, C3 from V1 order by C3
Tiago Moraes
+1 for "backwards" compatibility, the other answers doesn't work in Firebird 1.5
Eliseo Ocampos