Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Order by first non-null result that comes from two different columns

I want to browse through all values of two columns in a table:

  • if the value in column 1 is not null, select it, otherwise select the value in column 2 instead.
  • then sort the final result in alphabetical ascending order, wherever column its values came from.

I tried the following query but it doesn’t work and I’m not even sure it is supposed to do what I want to do.

SELECT * 
FROM table 
ORDER BY (CASE WHEN col1 IS NOT NULL THEN 1 ELSE 2 END ), 
         col1 DESC, 
         col2 DESC)

Besides the fact that it doesn’t work (nothing outputted), it seems to sort the values of each column separately while I want to sort the final set of values retrieved, regardless of the column they are from.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you for your help.

>Solution :

If you want to fix it with the CASE expression, it’d look like the following:

SELECT *, 
       CASE WHEN col1 IS NOT NULL 
            THEN col1 
            ELSE col2 
       END AS col
FROM table 
ORDER BY col

Although a nice option is using the COALESCE function. It returns the first non-null value in the list of arguments.

SELECT *, COALESCE(col1, col2) AS col
FROM table 
ORDER BY col
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading