Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ORDER BY for each SELECT in a UNION with MySQL

Tags:

php

mysql

Using PHP and MySQL, is there a way to use a different ORDER BY for each of the SELECT statements in a UNION?

SELECT * FROM the_table WHERE color = 'blue' ORDER BY price ASC LIMIT 5
UNION ALL
SELECT * FROM the_table WHERE color = 'red' ORDER BY RAND() LIMIT 10

The above statement does not work. It seems you can only do an ORDER BY on the final result set. Is there a way to do an ORDER BY on the first SELECT then a different ORDER BY on the second SELECT using UNION?

like image 583
Marcus Avatar asked Jun 27 '10 18:06

Marcus


People also ask

Can I use ORDER BY in UNION?

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.

Why does ORDER BY not work with UNION?

use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows. Basically the only time an ORDER in a union will be useful is if you are using LIMIT as well.

Do columns need to be in the same order for UNION SQL?

Syntax for Using the SQL UNION Operator The columns in the same position in each SELECT statement should have similar data types. For example, “char” and “varchar” are identical data types. The columns must be in the correct order in the SELECT statements.


2 Answers

(SELECT * FROM the_table WHERE color = 'blue' ORDER BY price ASC LIMIT 5)
UNION ALL
(SELECT * FROM the_table WHERE color = 'red' ORDER BY RAND() LIMIT 10)
like image 166
Tobias P. Avatar answered Sep 30 '22 17:09

Tobias P.


Please note that this does not work if you don't specify a LIMIT (though you can specify a very large dummy limit). See mysql documentation (13.2.7.3. UNION Syntax):

"Use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows... "To cause rows in a UNION result to consist of the sets of rows retrieved by each SELECT one after the other, select an additional column in each SELECT to use as a sort column and add an ORDER BY following the last SELECT:

"(SELECT 1 AS sort_col, col1a, col1b, ... FROM t1) UNION (SELECT 2, col2a, col2b, ... FROM t2) ORDER BY sort_col; To additionally maintain sort order within individual SELECT results, add a secondary column to the ORDER BY clause:

"(SELECT 1 AS sort_col, col1a, col1b, ... FROM t1) UNION (SELECT 2, col2a, col2b, ... FROM t2) ORDER BY sort_col, col1a;"

like image 42
NZN Avatar answered Sep 30 '22 16:09

NZN