Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MySQL, can you check if a field is NULL or empty using only one comparison?

Tags:

If I want to check to see if a field is NULL or empty using a MySQL query, I know I can do something like this:

column = '' OR column IS NULL

However, is there any way to check this without doing two separate comparisons?

like image 650
vertigoelectric Avatar asked Apr 12 '13 21:04

vertigoelectric


People also ask

How do I check if a column is NULL or empty in MySQL?

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 NULL and empty blank values compare?

In database terms, however, a null value is a value that doesn't exist: the field does not contain a value of any kind (not even a blank value). By contrast, a blank value is a real value: it just happens to be a string value containing 0 characters.

Does SQL Compare NULL values?

To handle NULLs correctly, SQL provides two special comparison operators: IS NULL and IS NOT NULL. They return only true or false and are the best practice for incorporating NULL values into your queries. Now the query will return every row, as we expected.

Can we compare NULL values?

The value NULL does not equal zero (0), nor does it equal a space (' '). Because the NULL value cannot be equal or unequal to any value, you cannot perform any comparison on this value by using operators such as '=' or '<>'.


2 Answers

Use COALESCE() to 'normalize' the value (convert NULL values to an empty string);

WHERE COALESCE(mycolumn, '') = ''

Read the documentation: COALESCE()

Or the other way around; convert empty strings to NULL;

WHERE NULLIF(mycolumn, '') IS NULL

Documentation: NULLIF()

Of those two, I would prefer COALESCE() as it is part of the ANSI SQL standard

You can experiment with it yourself, just do this;

SELECT 
    mycolumn                      AS orig_value,
    COALESCE(mycolumn, '')        AS coalesce_value,
    (COALESCE(mycolumn, '') = '') AS compare_result

FROM mytable;

This will show the original value, the 'coalesce' value and the result of the comparison side by side for every row in the table

like image 83
thaJeztah Avatar answered Sep 19 '22 19:09

thaJeztah


WHERE COALESCE(column, '') = ''
like image 20
Esailija Avatar answered Sep 21 '22 19:09

Esailija