Sunday, May 17, 2015

How to get the Duplicate and Unique Records by using SQL Query?

CREATE TABLE student (id int, name varchar(30), age int, gender char(6));

INSERT INTO student VALUES
(1 ,'Ranga', 27, 'Male'),
(2 ,'Reddy', 26, 'Male'),
(3 ,'Vasu', 50, 'Female'),
(4 ,'Ranga', 27, 'Male'),
(5 ,'Raja', 10, 'Male'),
(6 ,'Pavi', 52, 'Female'),
(7 ,'Vinod', 27, 'Male'),
(8 ,'Vasu', 50, 'Female'),
(9 ,'Ranga', 27, 'Male');

Getting the duplicate records:
---------------------------------------
SELECT DISTINCT name AS Name, COUNT(name) as Count FROM student GROUP BY name HAVING COUNT(name) > 1;

Output:
---------------------------------------
Name Count
Ranga 3
Vasu 2

Getting the Unique records:
---------------------------------------
SELECT DISTINCT name AS Name FROM student GROUP BY name;

Output:
---------------------------------------
Name
Pavi
Raja
Ranga
Reddy
Vasu
Vinod

0 comments: