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

SQL QUERY: If NULL then take another column but if NULL again ignore it

[SQL QUERY]
Hi, I need to have a date value from a column, if this column has the value NULL het should refer to another column, this should be translated like this:

SELECT * ISNULL(column1, column2)
FROM [Table1]

But now if the second column (column2) has also a NULL value he needs to ignore it, how can I please handle this?

Many thanks in advance!!

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

>Solution :

ISNULL will do that for you.

   SELECT ISNULL(Modified, Created) as LastTouched
     FROM Table

If modified is null and created is null, LastTouched will be null.

If you want to filter the row if both values are null, then you need to use the where clause

   SELECT ISNULL(Modified, Created) as LastTouched
     FROM Table
    WHERE Modified IS NOT NULL AND Created IS NOT NULL

As a side note, you have a syntax error in your query: you are missing a comma after the star in the select clause. It has to look like this:

SELECT *, ISNULL(column1, column2)
FROM [Table1]

Coalesce is good for multiple columns. Not sure if there is any performance difference if only using it for two columns.

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