
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select All Duplicate MySQL Rows Based on One or Two Columns
For this, use subquery along with HAVING clause. Let us first create a table −
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFirstName varchar(20), StudentLastName varchar(20) ); Query OK, 0 rows affected (0.27 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Smith'); Query OK, 1 row affected (0.04 sec) mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('Carol','Taylor'); Query OK, 1 row affected (0.04 sec) mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Doe'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Brown'); Query OK, 1 row affected (0.05 sec) mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('David','Miller'); Query OK, 1 row affected (0.06 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+------------------+-----------------+ | StudentId | StudentFirstName | StudentLastName | +-----------+------------------+-----------------+ | 1 | John | Smith | | 2 | Carol | Taylor | | 3 | John | Doe | | 4 | John | Brown | | 5 | David | Miller | +-----------+------------------+-----------------+ 5 rows in set (0.00 sec)
Following is the query to select all duplicate rows based on one or two columns. Here, we are counting the names appearing more than once i.e. duplicates −
mysql> select StudentId from DemoTable where StudentFirstName=(select StudentFirstName from DemoTable having count(StudentFirstName) > 1);
This will produce the following output −
+-----------+ | StudentId | +-----------+ | 1 | | 3 | | 4 | +-----------+ 3 rows in set (0.03 sec)
Advertisements