Use MySQL LIKE and NOT LIKE to display similar results?


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> CollegeCode varchar(100)
   -> );
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Col.1995.01.21');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable values('Col.2016.11.22');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values(null);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('Col.2018.12.01');
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values('Col.2019.03.12');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------------+
| CollegeCode    |
+----------------+
| Col.1995.01.21 |
| Col.2016.11.22 |
| NULL           |
| Col.2018.12.01 |
| Col.2019.03.12 |
+----------------+
5 rows in set (0.00 sec)

Following is the query for MySQL LIKE −

mysql> select *from DemoTable where CollegeCode LIKE '%Col%' or CollegeCode is NULL;

This will produce the following output −

+----------------+
| CollegeCode    |
+----------------+
| Col.1995.01.21 |
| Col.2016.11.22 |
| NULL           |
| Col.2018.12.01 |
| Col.2019.03.12 |
+----------------+
5 rows in set (0.00 sec)

Following is the query for NOT LIKE −

mysql> select *from DemoTable where CollegeCode NOT LIKE '%College%' or CollegeCode is NULL;

This will produce the following output −

+----------------+
| CollegeCode    |
+----------------+
| Col.1995.01.21 |
| Col.2016.11.22 |
| NULL           |
| Col.2018.12.01 |
| Col.2019.03.12 |
+----------------+
5 rows in set (0.00 sec)
raja
Published on 11-Jul-2019 15:17:14
Advertisements