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?
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.
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.
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.
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 '<>'.
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
WHERE COALESCE(column, '') = ''
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With