Search code examples
sqloracle-databaseselectunion

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


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)


Solution

  • Using @Adrian tips, I found a solution:

    I'm using GROUP BY and COUNT. I tried to use DISTINCT with ORDER BY but I'm getting error message: "not a SELECTed expression"

    select id from 
    (
        SELECT id FROM a -- returns 1,4,2,3
        UNION ALL -- changed to ALL
        SELECT id FROM b -- returns 2,1
    )
    GROUP BY id ORDER BY count(id);
    

    Thanks Adrian and this blog.