How can I order entries in a UNION without ORDER BY?

markus picture markus · Mar 4, 2009 · Viewed 15.5k times · Source

How can I be sure that my result set will have a first and b second? It would help me to solve a tricky ordering problem.

Here is a simplified example of what I'm doing:

SELECT a FROM A LIMIT 1 
UNION 
SELECT b FROM B LIMIT 1;

Answer

Joel Coehoorn picture Joel Coehoorn · Mar 4, 2009
SELECT col
FROM 
   (
       SELECT a col, 0 ordinal FROM A LIMIT 1
       UNION ALL
       SELECT b, 1 FROM B LIMIT 1
   ) t
ORDER BY ordinal