Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a column if other column is null

I need to select a field called ProgramID from a table and if the ProgramID is NULL then I need to select the value in the InterimProgramID from the same table and alias it as ProgramID.

How can I make a conditional SELECT statement to do this?

like image 256
Ronald McDonald Avatar asked Mar 26 '12 19:03

Ronald McDonald


People also ask

Can we use != NULL in SQL?

Both evaluate for values, which NULL is not -- NULL is a placeholder to say there is the absence of a value. Which is why you can only use IS NULL / IS NOT NULL as predicates for such situations. This behavior is not specific to SQL Server.

How do you check if a column is empty or NULL?

SELECT * FROM yourTableName WHERE yourSpecificColumnName IS NULL OR yourSpecificColumnName = ' '; The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.


1 Answers

You need the ISNULL function.

SELECT ISNULL(a, b) 

b gets selected if a is null.

Also, you can use the WHEN/THEN select option, lookup in BOL. Essentially: its c switch/case block meets SQL.

like image 125
Peter Aron Zentai Avatar answered Sep 22 '22 11:09

Peter Aron Zentai