SQL PRACTICE: SQL SERVER - Duplicate Records
Q3. How to select duplicate records from a table using SQL?
N.B: I am using the following:
Database -> MSSQL
SQL Dialect -> T-SQL
I have a table given below:
Table1. Employee Table
To find duplicate records from the table, we need to use a row_number function to uniquely identify each row.
select Empid,
Name,
Salary,
ROW_NUMBER() over(partition by empid, Name, Salary order by empid) as Row_Num
from employee
Table2. Row_Number FunctionIf you see the Row_Num column above, it is uniquely identifying each row. Now, we need to fetch a duplicate records having Row_Num grater than one.
Let's see the SQL query:
With cte as (select Empid,
Name,
Salary,
ROW_NUMBER() over(partition by empid, Name, Salary order by empid) as Row_Num
from employee)
select Empid,
Name,
Salary
from cte
where Row_Num > 1;
Table3. Duplicate Records
Comments
Post a Comment