Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL : Selecting alternative field if given field is empty

Tags:

mysql

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

like image 585
Kyobul Avatar asked Mar 20 '10 20:03

Kyobul


People also ask

How do I check if a field is empty in MySQL?

SELECT * FROM yourTableName WHERE yourSpecificColumnName IS NULL OR yourSpecificColumnName = ' '; The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.

IS NULL MySQL select?

To search for column values that are NULL , you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression: mysql> SELECT * FROM my_table WHERE phone = NULL; To look for NULL values, you must use the IS NULL test.

How do I check if a column is not null in MySQL?

Here is an example of how to use the MySQL IS NOT NULL condition in a SELECT statement: SELECT * FROM contacts WHERE last_name IS NOT NULL; This MySQL IS NOT NULL example will return all records from the contacts table where the last_name does not contain a null value.


1 Answers

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

like image 197
True Soft Avatar answered Nov 15 '22 13:11

True Soft