Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: how to use UNION and order by a specific select?

Tags:

I have two selects:

SELECT id FROM a -- returns 1,4,2,3 UNION SELECT id FROM b -- returns 2,1 

I'm receiving correct num of rows, like: 1,4,2,3.

But I want b table results first: 2,1,4,3 or 2,1,3,4

How can I do this?

(I'm using Oracle)

like image 362
Topera Avatar asked May 17 '11 20:05

Topera


People also ask

Can we use UNION with ORDER BY?

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 you ORDER BY a SELECT statement?

SQL queries initiated by using a SELECT statement support the ORDER BY clause. The result of the SELECT statement is sorted in an ascending or descending order.


1 Answers

You want to do this:

select * from  (     SELECT id, 2 as ordered FROM a -- returns 1,4,2,3     UNION     SELECT id, 1 as ordered FROM b -- returns 2,1 ) order by ordered 

Update

I noticed that even though you have two different tables, you join the IDs, that means, if you have 1 in both tables, you are getting only one occurrence. If that's the desired behavior, you should stick to UNION. If not, change to UNION ALL.

So I also notice that if you change to the code I proposed, You would start getting both 1 and 2 (from both a and b). In that case, you might want to change the proposed code to:

select distinct id from  (     SELECT id, 2 as ordered FROM a -- returns 1,4,2,3     UNION     SELECT id, 1 as ordered FROM b -- returns 2,1 ) order by ordered 
like image 178
Adriano Carneiro Avatar answered Oct 11 '22 13:10

Adriano Carneiro