MySQL 5.6 – NULL Safe NOT LIKE Operation

mysql-5.6

I have InnoDB table with two columns (1) account(int) (2) comment(varchar).

I have index on (account,comment)

Now I want to run query like

select * from table where account = 1111 AND comment NOT LIKE 'abcd%';

How can i make the NOT LIKE null safe?

I mean, include all records whose comment not starts with 'abcd', even if its null value.

Best Answer

mysql > create table nsnl(a varchar(20));
Query OK, 0 rows affected (0.00 sec)

mysql > insert into nsnl values (null), ('asdf');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

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

mysql > select * from nsnl where a not like 'as%';
Empty set (0.00 sec)

mysql > select * from nsnl where a not like 'as%' or a is null;
+------+
| a    |
+------+
| NULL |
+------+
1 row in set (0.00 sec)

And that's how you can easily find that out yourself. Plus, when you do it yourself, you memorize it better. At least that works for me.