Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 305
markus Avatar asked Mar 04 '09 15:03

markus


People also ask

Can you have an ORDER BY in a UNION?

MySQL a-z in Telugu Union is a type of operator in MySQL. We can use ORDER BY with this to filter records. Use UNION if you want to select rows one after the other from several tables or several sets of rows from a single table all as a single result set. Let us see an example.

Can we use ORDER BY before UNION?

It is not possible to use two different ORDER BY in the UNION statement. UNION returns single resultsetand as per the Logical Query Processing Phases.


4 Answers

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
like image 58
Joel Coehoorn Avatar answered Sep 19 '22 05:09

Joel Coehoorn


I don't think order is guaranteed, at least not across all DBMS.

What I've done in the past to control the ordering in UNIONs is:

(SELECT a, 0 AS Foo FROM A LIMIT 1)
UNION
(SELECT b, 1 AS Foo FROM B LIMIT 1)
ORDER BY Foo
like image 23
Dana Avatar answered Sep 22 '22 05:09

Dana


Your result set with UNION will eliminate distinct values.

I can't find any proof in documentation, but from 10 years experience I can tell that UNION ALL does preserve order, at least in Oracle.

Do not rely on this, however, if you're building a nuclear plant or something like that.

like image 31
Quassnoi Avatar answered Sep 21 '22 05:09

Quassnoi


No, the order of results in a SQL query is controlled only by the ORDER BY clause. It may be that you happen to see ordered results without an ORDER BY clause in some situation, but that is by chance (e.g. a side-effect of the optimiser's current query plan) and not guaranteed.

What is the tricky ordering problem?

like image 39
Tony Andrews Avatar answered Sep 22 '22 05:09

Tony Andrews