简体   繁体   中英

how to show null value at the end when using union all in sql

I am using this code to list numbers ASC and null values listing after the value in ms sql:

ORDER BY -ur.sira_no DESC

But if i use two select query with "UNION ALL" and than my query is not working.

Error :

ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

How can we order null values after the numbers using UNION ALL?

Use a subquery:

select x.*
from ((select . . .
      ) union all
      (select . . .
      )
     ) x
ORDER BY - x.sira_no DESC;

However, I would recommend being more explicit:

ORDER BY (CASE WHEN sira_no IS NOT NULL THEN 1 ELSE 2 END),
         sira_no ASC

in your original query. SQL Server allows you to order by column names in a union all query, but not on expressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM