bcoughlan
bcoughlan

Reputation: 26627

MySQL: How to select a column with a value from another column, depending on which columns are empty?

I have a query that looks like this:

SELECT id, description, default_error, custom_error  FROM  `table1`;

Which gives me

(int) (Text)       (Varchar)          (Varchar)
id    Description  Default_Error      custom_error
---------------------------------------------------
 1    Hello        Error 123            
 2    World        Error 456          This is a custom Error

I'd like to select an extra column ("error") that has the value of default_error if custom_error is EMPTY, and the value of custom_error if custom_error is NOT EMPTY.

Any idea how to do this in MySQL?

Upvotes: 0

Views: 141

Answers (3)

Pradeep Singh
Pradeep Singh

Reputation: 3634

SELECT id, description, default_error, custom_error,
  IF(custom_error='', default_error, custom_error) as error
FROM  `table1`;

Upvotes: 0

skajfes
skajfes

Reputation: 8265

If custom_error is null when empty than you can use this:

select id, description, coalesce(custom_error, default_error)

Upvotes: 2

ajreal
ajreal

Reputation: 47321

Try

SELECT id, description, default_error, custom_error,
  IF(custom_error='', default_error, custom_error) as error
FROM  `table1`;

OR - if custom_error is NULL by default

SELECT id, description, default_error, custom_error,
  ISNULL(custom_error, default_error) as error
FROM  `table1`;

Upvotes: 1

Related Questions