MySQL query to avoid displaying duplicates values?

MySQLMySQLi Database

For this, you can use GROUP BY and use COUNT to get only non-duplicate values. Following is the syntax −

select yourColumnName from yourTableName group by yourColumnName having count(*)=1;

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Subject varchar(100)
   -> );
Query OK, 0 rows affected (0.70 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Subject) values('MySQL');
Query OK, 1 row affected (0.21 sec)

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

mysql> insert into DemoTable(Subject) values('Java');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable(Subject) values('C');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Subject) values('C++');
Query OK, 1 row affected (0.11 sec)

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

mysql> insert into DemoTable(Subject) values('C');
Query OK, 1 row affected (0.23 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+---------+
| Id | Subject |
+----+---------+
| 1  | MySQL   |
| 2  | MongoDB |
| 3  | Java    |
| 4  | MongoDB |
| 5  | C       |
| 6  | C++     |
| 7  | Java    |
| 8  | C       |
+----+---------+
8 rows in set (0.00 sec)

Here is the query to avoid displaying duplicates −

mysql> select Subject from DemoTable group by Subject having count(*)=1;

Output

+---------+
| Subject |
+---------+
| MySQL   |
| C++     |
+---------+
2 rows in set (0.00 sec)
raja
Published on 09-Jul-2019 12:21:31
Advertisements