Exclude some ID records from a list and display rest in MySQL


To exclude records, use MySQL NOT IN(). Let us first create a table −

mysql> create table DemoTable
(
   Id int
);
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(2);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(3);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(4);
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable values(5);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(6);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+
| Id   |
+------+
| 1    |
| 2    |
| 3    |
| 4    |
| 5    |
| 6    |
+------+
6 rows in set (0.00 sec)

Following is the query to exclude records −

mysql> select *from DemoTable where Id NOT IN(1,4,6,3);

This will produce the following output −

+------+
| Id   |
+------+
| 2    |
| 5    |
+------+
2 rows in set (0.00 sec)
raja
Published on 09-Oct-2019 15:52:10
Advertisements