Skip to content
Advertisement

How to order by with union in SQL to make first select query value first?

In this query:

SELECT NM, DEP_CD FROM EMP WHERE DEP_CD='1100' and (SELECT COUNT(1) FROM BBS_TABLE WHERE UP_DEP_CD = '1100') > 0
UNION
SELECT NM, DEP_CD FROM EMP WHERE DEP_CD '1110'

First
select query ( SELECT NM, DEP_CD FROM EMP WHERE DEP_CD='1100'
and
(SELECT COUNT(1) FROM BBS_TABLE WHERE UP_DEP_CD = '1100') > 0)
always returns 1 result.
I want to put this one first in the result values, but there are no regular rules for results so I couldn’t use order by.

How can I put the first query’s result in the first row? I use oracle db.

Advertisement

Answer

Here is an option to do it.

Define a dummy column as rnk, giving the first query rnk=1 and the one below the union as 2. After that order by the rnk column

SELECT NM, DEP_CD,1 as rnk FROM EMP WHERE DEP_CD='1100' and (SELECT COUNT(1) FROM BBS_TABLE WHERE UP_DEP_CD = '1100') > 0
UNION
SELECT NM, DEP_CD,2 as rnk FROM EMP WHERE DEP_CD '1110'
ORDER BY 3 ASC

In case you dont want the final output to have the rnk field then use an outer query as follows

select x.NM,x.DEP_CD from (
    SELECT NM, DEP_CD,1 as rnk FROM EMP WHERE DEP_CD='1100' and (SELECT COUNT(1) FROM BBS_TABLE WHERE UP_DEP_CD = '1100') > 0
    UNION
    SELECT NM, DEP_CD,2 as rnk FROM EMP WHERE DEP_CD '1110'
)x
ORDER BY x.rnk ASC
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement