Remove duplicate rows in SQL Server

by

Assuming no nulls, you GROUP BY the unique columns (eg. col_1, col_2, col_3), and SELECT the MIN (or MAX) Row ID (eg. row_id) as the row to keep. Then, delete everything that didn’t have a row id:

DELETE my_table
FROM my_table
	LEFT OUTER JOIN (
	SELECT MIN(row_id) as row_id, col_1, col_2, col_3
	FROM my_table
	GROUP BY col_1, col_2, col_3
) as keep_rows ON
	my_table.row_id = keep_rows.row_id
WHERE
	keep_rows.row_id IS NULL

Use

CONVERT(uniqueidentifier, MIN(CONVERT(char(36), my_guid_column)))

instead of MIN(row_id) if you have a GUID instead of an integer.

Relative links:

Remove duplicate rows in MySQL

Remove duplicate rows in Oracle

Some SQL Server tools you can try: https://www.withdata.com/sql-server/

2 thoughts on “Remove duplicate rows in SQL Server

  1. Pingback: Remove duplicate rows in MySQL | Withdata Software

  2. Pingback: Remove duplicate rows in Oracle | Withdata Software