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

Time:01-12

[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!!

CodePudding user response:

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.

CodePudding user response:

If you need to ignore if both are null try

SELECT coalesce(column1, column2)
FROM [Table1]
where column1 is not null and column2 is not null

I use coalesce here

I assume by 'needs to ignore it' you mean that if both null the record should not be in the data set

  •  Tags:  
  • Related