Skip to content

SQL-187:- Deleting One of Two Identical Rows in SQL #355

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions sql-queries-11/delete-identical-rows/create-table.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- Create sample table
CREATE TABLE DuplicateRecords (
RecordID SERIAL PRIMARY KEY, -- Use INT AUTO_INCREMENT for MySQL
Value1 VARCHAR(50),
Value2 INT,
Value3 DATE
);

-- Insert sample data with duplicates
INSERT INTO DuplicateRecords (Value1, Value2, Value3) VALUES
('Apple', 10, '2023-01-01'),
('Banana', 20, '2023-02-01'),
('Apple', 10, '2023-01-01'), -- Identical to the first row (logical duplicate)
('Cherry', 30, '2023-03-01'),
('Banana', 20, '2023-02-01'), -- Identical to the second row (logical duplicate)
('Apple', 10, '2023-01-01'); -- Another identical row
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-- PostgreSQL
DELETE FROM DuplicateRecords DR1
USING DuplicateRecords DR2
WHERE
DR1.Value1 = DR2.Value1 AND
DR1.Value2 = DR2.Value2 AND
DR1.Value3 = DR2.Value3 AND
DR1.RecordID > DR2.RecordID;

-- MS SQL Server / MySQL
DELETE FROM DR1
USING DuplicateRecords DR1
JOIN DuplicateRecords DR2 ON
DR1.Value1 = DR2.Value1 AND
DR1.Value2 = DR2.Value2 AND
DR1.Value3 = DR2.Value3 AND
DR1.RecordID > DR2.RecordID;

17 changes: 17 additions & 0 deletions sql-queries-11/delete-identical-rows/using-min-max-subquery.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-- PostgreSQL / MS SQL Server
DELETE FROM DuplicateRecords
WHERE RecordID NOT IN (
SELECT MIN(RecordID)
FROM DuplicateRecords
GROUP BY Value1, Value2, Value3
);

-- MySQL
DELETE FROM DuplicateRecords
WHERE RecordID NOT IN (
SELECT T2.MinRecordID FROM (
SELECT MIN(RecordID) AS MinRecordID
FROM DuplicateRecords
GROUP BY Value1, Value2, Value3
) AS T2
);
13 changes: 13 additions & 0 deletions sql-queries-11/delete-identical-rows/using-row-number.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- PostgreSQL / MS SQL Server / MySQL Server
WITH CTE_DuplicateRecords AS (
SELECT
RecordID,
Value1,
Value2,
Value3,
ROW_NUMBER() OVER (PARTITION BY Value1, Value2, Value3 ORDER BY RecordID) as rn
FROM
DuplicateRecords
)
DELETE FROM DuplicateRecords
WHERE RecordID IN (SELECT RecordID FROM CTE_DuplicateRecords WHERE rn > 1);