Click here to Skip to main content
15,895,606 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an SQL database with 5 fields, I want a select statement that will choose value from one field if it is not null or else it will choose from second. I found the case condition but not sure how to state it.

SQL
SELECT CASE 
            WHEN tel is not null
               THEN select tel 
               ELSE select mob 
       END as Saleable 
FROM Product


What I have tried:

I have tried nothing so far but I would try the above code
Posted
Updated 23-Jun-16 20:07pm

The simplest way is to use COALESCE function[^].


SQL
SELECT COALESCE(tel, mob) as Saleable 
FROM Product


Using CASE ... WHEN ... END statement:
SQL
SELECT CASE WHEN tel IS NULL THEN mob ELSE tel END as Saleable 
FROM Product
 
Share this answer
 
v2
Comments
Karthik_Mahalingam 24-Jun-16 2:13am    
Counter 5 for simpler solution.
Maciej Los 24-Jun-16 2:14am    
Thank you, Karthik.
try this

SQL
SELECT CASE 
            WHEN tel is not null
               THEN   tel 
               ELSE   mob 
       END as Saleable 
FROM Product
 
Share this answer
 
Comments
Maciej Los 24-Jun-16 2:05am    
Karthik, is there any difference to OP query? I do not see... ;(
Karthik_Mahalingam 24-Jun-16 2:08am    
HI Maciej
I executed his code and it thrown syntax error, so i just removed the "select" and executed it gave the correct result.

Maciej Los 24-Jun-16 2:10am    
I missed that "SELECT" is inside CASE... WHEN...END statement. Good catch!
A 4, because there's simplest way to achieve that ;)
Karthik_Mahalingam 24-Jun-16 2:12am    
:) Thank You Maciej

Yes, Agree, i just edited OP's query..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900