Skip to main content

How to use CTE to remove duplicates



--One use of Common table Expressions (CTEs) is to remove duplicates
--To see this lets create a table 'Employee'
CREATE table Employee  (name NVARCHAR(100), age INT, salary INT)

--insert some duplicate data into the 'Employee Table'.
INSERT  into Employee
VALUES ('Mark', 42, 120000), ('Susan', 29, 125000), ('Mark', 42, 120000)
--you could see there is a duplicate record in the table by querying the table
--select * from  Employee
--we could use CTE to remove this duplicate. 
WITH CTE_Employee(name, age, salary, rownumber) AS (
select name,   age,   salary,   row_number() OVER (
PARTITION BY name, age, salary ORDER BY name, age, salary
) AS rownumber from Employee
)

DELETE
FROM CTE_Employee
WHERE rownumber <> 1
--query the table to see if there are still duplicates
--select * from  Employee

Comments

Popular posts from this blog

Lucidchart is a diagramming solution for UML with deep integration with third-party apps. Make the diagram itself in Lucidchart, and create your use case scenario document with a program like Google Docs! Want to make a UML diagram of your own? Try Lucidchart. It's quick, easy, and completely free. Make a UML diagram By registering I agree to Lucid Software's  Terms of Service  and  Privacy Policy . What is a use case diagram in UML? A use case collects scenarios. By writing out the main parts of your process, including alternative paths, you’ll have a clearer outlook on the scope of your project. Although you can copy and paste text and make simple edits in the Lucidchart editor, you may want to first write your use case scenario in a program like Google Docs. The  Lucidchart add-on for Google Docs  is an ideal solution for bringing together the visual diagramming and written aspects of project management. Outline your use case diagram Use case scenario docu

UML Use Case Diagram Tutorial