Skip to content

Commit 4e3d348

Browse files
authored
Merge pull request #355 from kapilbk1996/SQL-187
SQL-187:- Deleting One of Two Identical Rows in SQL
2 parents 995a648 + 47a3598 commit 4e3d348

File tree

4 files changed

+72
-0
lines changed

4 files changed

+72
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
-- Create sample table
2+
CREATE TABLE DuplicateRecords (
3+
RecordID SERIAL PRIMARY KEY, -- Use INT AUTO_INCREMENT for MySQL
4+
Value1 VARCHAR(50),
5+
Value2 INT,
6+
Value3 DATE
7+
);
8+
9+
-- Insert sample data with duplicates
10+
INSERT INTO DuplicateRecords (Value1, Value2, Value3) VALUES
11+
('Apple', 10, '2023-01-01'),
12+
('Banana', 20, '2023-02-01'),
13+
('Apple', 10, '2023-01-01'), -- Identical to the first row (logical duplicate)
14+
('Cherry', 30, '2023-03-01'),
15+
('Banana', 20, '2023-02-01'), -- Identical to the second row (logical duplicate)
16+
('Apple', 10, '2023-01-01'); -- Another identical row
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
-- PostgreSQL
2+
DELETE FROM DuplicateRecords DR1
3+
USING DuplicateRecords DR2
4+
WHERE
5+
DR1.Value1 = DR2.Value1 AND
6+
DR1.Value2 = DR2.Value2 AND
7+
DR1.Value3 = DR2.Value3 AND
8+
DR1.RecordID > DR2.RecordID;
9+
10+
-- MySQL
11+
DELETE FROM DR1
12+
USING DuplicateRecords DR1
13+
JOIN DuplicateRecords DR2 ON
14+
DR1.Value1 = DR2.Value1 AND
15+
DR1.Value2 = DR2.Value2 AND
16+
DR1.Value3 = DR2.Value3 AND
17+
DR1.RecordID > DR2.RecordID;
18+
19+
-- MS SQL Server
20+
DELETE DR1
21+
FROM DuplicateRecords DR1
22+
JOIN DuplicateRecords DR2
23+
ON DR1.Value1 = DR2.Value1
24+
AND DR1.Value2 = DR2.Value2
25+
AND DR1.Value3 = DR2.Value3
26+
AND DR1.RecordID > DR2.RecordID;
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
-- PostgreSQL / MS SQL Server
2+
DELETE FROM DuplicateRecords
3+
WHERE RecordID NOT IN (
4+
SELECT MIN(RecordID)
5+
FROM DuplicateRecords
6+
GROUP BY Value1, Value2, Value3
7+
);
8+
9+
-- MySQL
10+
DELETE FROM DuplicateRecords
11+
WHERE RecordID NOT IN (
12+
SELECT T2.MinRecordID FROM (
13+
SELECT MIN(RecordID) AS MinRecordID
14+
FROM DuplicateRecords
15+
GROUP BY Value1, Value2, Value3
16+
) AS T2
17+
);
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
-- PostgreSQL / MS SQL Server / MySQL Server
2+
WITH CTE_DuplicateRecords AS (
3+
SELECT
4+
RecordID,
5+
Value1,
6+
Value2,
7+
Value3,
8+
ROW_NUMBER() OVER (PARTITION BY Value1, Value2, Value3 ORDER BY RecordID) as rn
9+
FROM
10+
DuplicateRecords
11+
)
12+
DELETE FROM DuplicateRecords
13+
WHERE RecordID IN (SELECT RecordID FROM CTE_DuplicateRecords WHERE rn > 1);

0 commit comments

Comments
 (0)