Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make WHERE col LIKE '%' select NULL values too?

Tags:

select

mysql

I am trying to make a selection from a MySQL database using the syntax WHERE col LIKE '%' but I want to select even NULL values with that query. Is there some command/operator that can select any data, including null?

like image 471
Pizdabol Avatar asked May 06 '11 11:05

Pizdabol


People also ask

Can we use NULL in WHERE clause?

Generally, NULL data represents data does not exist or missing data or unknown data. IS NULL & IS NOT NULL in SQL is used with a WHERE clause in SELECT, UPDATE and DELETE statements/queries to validate whether column has some value or data does not exist for that column.

How do I avoid 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.


4 Answers

SELECT * FROM table WHERE (job LIKE '%' OR job IS NULL)
like image 63
RemoteSojourner Avatar answered Oct 29 '22 17:10

RemoteSojourner


Use the IFNULL operator

WHERE IFNULL(xxx, '') LIKE '%'
like image 21
BlueMonkMN Avatar answered Oct 29 '22 17:10

BlueMonkMN


Use COALESCE instead of IFNULL if you want to use it with java createQuery

WHERE COALESCE (xxx, '') LIKE '%'
like image 42
Annu Avatar answered Oct 29 '22 15:10

Annu


If you want column1 LIKE '%' and want column1 IS NULL, why not just drop the WHERE clause?

Try:

SELECT * FROM TABLE;

Here's what I tried:

mysql> create table foo (a char(30));
Query OK, 0 rows affected (0.02 sec)

mysql> insert into foo values ( '' );
Query OK, 1 row affected (0.01 sec)

mysql> insert into foo values ( NULL );
Query OK, 1 row affected (0.00 sec)

mysql> select * from foo;
+------+
| a    |
+------+
|      |
| NULL |
+------+
2 rows in set (0.00 sec)

mysql> select * from foo where a like '%' or a is null;
+------+
| a    |
+------+
|      |
| NULL |
+------+
2 rows in set (0.00 sec)

mysql> select * from foo where ifnull (a, 1) like '%';
+------+
| a    |
+------+
|      |
| NULL |
+------+
2 rows in set (0.00 sec)

mysql> 

After all, IFNULL(column1, 1) LIKE '%' is effectively a NO-OP ...

like image 29
amrith Avatar answered Oct 29 '22 16:10

amrith