Salar
Salar

Reputation: 5509

replace a column with another column when column is null in SELECT statement

Here is my dummy Schema in MYSQL:
A column: which is a nullable string
B column: which is a string but its not null

enter image description here
I only want to select A columns but when facing a null, I want it to be replaced with the B column.
How can I do that?
this is my desired output
enter image description here

Upvotes: 0

Views: 2329

Answers (3)

Rajat
Rajat

Reputation: 5803

Or use ifnull, the sound of which makes it easy to remember. Note that it only works for 2 columns/values

select ifnull(a, b) as a
from t;

Upvotes: 0

luna80
luna80

Reputation: 153

coalesce() or

SELECT CASE WHEN A IS NOT NULL THEN A ELSE B END AS value FROM tablename;

Upvotes: 3

Gordon Linoff
Gordon Linoff

Reputation: 1271161

Use coalesce():

select coalesce(a, b) as a
from t;

Upvotes: 2

Related Questions