Syntax error MySQL query to find single value from duplicates with certain condition by excluding other records using NOT IN

MySQL query to find single value from duplicates with certain condition by excluding other records using NOT IN



Let us first create a table −

mysql> create table DemoTable
(
   Id int,
   FirstName varchar(100)
);
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(100,'Robert');
Query OK, 1 row affected (0.48 sec)
mysql> insert into DemoTable values(100,'Mike');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(100,'Sam');
Query OK, 1 row affected (0.48 sec)
mysql> insert into DemoTable values(101,'David');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(101,'Robert');
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable values(210,'Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(210,'Bob');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(210,'Sam');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
|  100 | Chris     |
|  100 | Robert    |
|  100 | Mike      |
|  100 | Sam       |
|  101 | David     |
|  101 | Robert    |
|  210 | Chris     |
|  210 | Bob       |
|  210 | Sam       |
+------+-----------+
9 rows in set (0.00 sec)

Here is the query to find a single value from duplicates with certain condition −

mysql> select distinct Id from DemoTable
where Id not in
(
   select Id from DemoTable where FirstName='Chris'
);

This will produce the following output −

+------+
| Id   |
+------+
| 101  |
+------+
1 row in set (0.08 sec)
Updated on: 2019-09-26T07:08:35+05:30

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements