stighy
stighy

Reputation: 7170

T-SQL: How to select one column or in alternative another one?

I need to do a query and get a date from one column if it is not null, alternatives from a second column.

For example, my table is

Date1         Date2        AnotherColumn
01-01-2012    02-01-2012      ABC
NULL          02-01-2012      CDE
03-01-2012    05-01-2012      XZY

My query has to return Date1 if Date1 is not null, otherwise Date2.

Query result:

   Date         AnotherColumn
   01-01-2012     ABC
   02-01-2012     CDE
   03-01-2012     XYZ

How can do this in T-SQL ?

Upvotes: 2

Views: 4608

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726779

The details depend on your RDBMS, but many engines offer some kind of a COALESCE function.

Here is how you do it in SQL Server:

select COALESCE(t.Date1, t.Date2) as Date
from MyTable t

When a coalesce function is not available, you can use a conditional expression. Here is the syntax for SQL Server:

select case
    when t.Date1 is not null then t.Date1
    else t.Date2
end as Date
from MyTable t

Upvotes: 7

MFix
MFix

Reputation: 229

ISNULL(datefield1, datefield2)

I hope it will work for you.

Upvotes: 3

Related Questions