Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: select * from table where col IN (null, "") possible without OR

Tags:

null

mysql

Is it somehow possible to do a select for empty strings and NULL values in MySQL without using or?

This:

   select * from table where col IN (null, ""); 

doesn't work, it ignores the null (or possibly matches it with the string 'null').

like image 291
pvgoddijn Avatar asked Jan 27 '10 14:01

pvgoddijn


People also ask

How do I select only NULL values in MySQL?

To look for NULL values, you must use the IS NULL test. The following statements show how to find the NULL phone number and the empty phone number: mysql> SELECT * FROM my_table WHERE phone IS NULL; mysql> SELECT * FROM my_table WHERE phone = ''; See Section 3.3.

Is NULL in MySQL in WHERE clause?

To test for NULL in a query, you use the IS NULL or IS NOT NULL operator in the WHERE clause. You can use the IS NOT operator to get all leads who provided the email addresses. Even though the NULL is not equal to NULL , two NULL values are equal in the GROUP BY clause.

How do I ignore NULL values in select query?

SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator.


1 Answers

SELECT  * FROM    mytable WHERE   COALESCE(col, '') = '' 

Note, however, than OR query will be much more efficient if the column is indexed:

SELECT  * FROM    mytable WHERE   col = '' OR col IS NULL 

This will use ref_or_null access path on the index.

If you need to select from a list of values along with NULLs, just put all not-null values into the list and add a single OR IS NULL condition:

SELECT  * FROM    mytable WHERE   col IN ('val1', 'val2', 'val3') OR col IS NULL 

This will use an index on col as well.

like image 165
Quassnoi Avatar answered Sep 30 '22 07:09

Quassnoi