tags:

views:

41

answers:

3

Hi, 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

+3  A: 

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

True Soft
Also thank you , also works great !
Kyobul
+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
+2  A: 

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.

Joel Potter
Thank you, works great !
Kyobul
I just learned something today. Great answer.
Vinny
+1  A: 

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)
codingguy3000
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.
le dorfier
Thanks to you, third method, works great too !
Kyobul