I wonder if is it possible to run mysql command which can select an alternative field if the first given field is empty, on the same table.

Example : I have table called "posts" which have "intro" and "content". In the same statement I would like to select as a result "content" if "intro" is empty, but not having both in the result array.

Thanks in advance


You can use IF function:

SELECT IF(LENGTH(intro)>0, intro, content) 
FROM posts

Or you can test for NULL if you mean that empty is NULL

  • 1
    +1: CASE would be a viable alternative, but the LENGTH keyword isn't supported on all other databases (Oracle, Postgres but not SQL Server - have to use LEN) which makes query portability almost moot. – OMG Ponies Mar 20 '10 at 21:13

Coalesce is what you are looking for.

SELECT COALESCE(intro, content) AS column1
FROM table

Assuming intro is null and not a zero length string.


There two potential ways. When way is with a case statement.

Select case when field1 <> '' then field2 else field1 end

or you you can use coalesce.

select coalesce(field1, field2)
  • There are a more than two. You have IF, IFNULL, CASE WHEN, CASE fiel1 WHEN, and COALESCE off the top of my head. And "<> '' won't work in the obvious case when "empty" means NULL. – dkretz Mar 20 '10 at 20:53

Your Answer

