Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query - Using Order By in UNION

How can one programmatically sort a union query when pulling data from two tables? For example,

SELECT table1.field1 FROM table1 ORDER BY table1.field1 UNION SELECT table2.field1 FROM table2 ORDER BY table2.field1 

Throws an exception

Note: this is being attempted on MS Access Jet database engine

like image 779
Curtis Inderwiesche Avatar asked Oct 17 '08 21:10

Curtis Inderwiesche


People also ask

Can I use ORDER BY with 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.

Can we use ORDER BY clause in UNION in SQL Server?

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.

Can we use ORDER BY in UNION all in SQL?

The UNION ALL operator can use the ORDER BY clause to order the results of the query in SQL Server (Transact-SQL).


1 Answers

Sometimes you need to have the ORDER BY in each of the sections that need to be combined with UNION.

In this case

SELECT * FROM  (   SELECT table1.field1 FROM table1 ORDER BY table1.field1 ) DUMMY_ALIAS1  UNION ALL  SELECT * FROM (    SELECT table2.field1 FROM table2 ORDER BY table2.field1 ) DUMMY_ALIAS2 
like image 163
ajgreyling Avatar answered Sep 17 '22 15:09

ajgreyling