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?
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.
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.
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.
(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)
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;"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With