Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check field if empty

Tags:

mysql

Is the query correct if I wanted to check if the field has other characters other than null and empty?

select CASE WHEN description IS NULL THEN 'null'
  WHEN description IS NOT NULL THEN 'not null' ELSE 'something else' END 
  AS 'description'from milestone where name like '%Test%' or name like '%test%';

+-------------+
| description |
+-------------+
| not null    |
+-------------+
1 row in set (0.00 sec)
like image 331
Efox Avatar asked Apr 02 '11 01:04

Efox


2 Answers

Null and empty means NULL + '' (empty string)?

select CASE WHEN description IS NULL or description = '' THEN 'null or empty'
  ELSE 'not null' END 
  AS 'description'

In your original query, there is no possibility of a third case because IS NULL and IS NOT NULL are complementary, between them they have covered all possibilities.

Also, unless you are using case-sensitive collation (very rare, and never by default unless you specifically nominate one), MySQL is not Oracle - these two queries will work the same:

where name like '%Test%' or name like '%test%'
where name like '%test%'

Because MySQL will match strings case-insensitively

like image 170
RichardTheKiwi Avatar answered Oct 14 '22 09:10

RichardTheKiwi


Simple IF solution:

IF (my_field = '', "not null", "null")

By the way, I personally like to use it like that (shorthand syntax):

IF (my_field = '', 1, 0)
like image 36
Sliq Avatar answered Oct 14 '22 09:10

Sliq