r/SQL • u/db_tech_dev • Sep 03 '26
Discussion Built a small CLI tool to find/clean duplicate rows in MySQL & PostgreSQL, feedback welcome
been dealing with duplicate customer records in a project for uni and kept rewriting the same GROUP BY/HAVING query every time so i just built a cli tool for it in the end - works with both mysql and postgres, dry run by default so nothing gets deleted unless u explicitly pass --confirm and it backs up to json first just in case. still a student so the detection logic is prob missing some edge cases; that's the part i actually want feedback on tbh. happy to share the repo if anyone's curious, can drop the repo link
3
Upvotes
4
u/Phil_P Sep 03 '26
Look into the concepts around integrity constraints, particularly unique constraints in this case. The goal is to not allow bad data to be saved to the database rather than cleaning it up later.
1
u/Einar_Son_of_Bjorn Sep 03 '26
Dry-run by default plus a JSON backup is the right shape.
That’s the part most “just DELETE FROM …” scripts skip.The detection logic is the whole product. GROUP BY / HAVING COUNT(*) > 1 is fine for exact copies. It lies when “duplicate” means same email different id, or same name different whitespace. Worth handling:
If you built it against MySQL, run the same suite on MariaDB. Same protocol, slightly different GROUP BY / ONLY_FULL_GROUP_BY habits depending on sql_mode.Drop the repo. The interesting bit is how you pick the survivor, not the CLI wrapper.
1
u/kantorcodes1 Sep 03 '26
does the CLI make you choose both the duplicate key columns and the survivor row before
--confirm, or does it infer either of those?1
u/LukaGOGO Sep 04 '26
Dry-run by default and a JSON backup first is the right shape. Most “just DELETE” scripts skip that.Detection is the actual product. GROUP BY / HAVING COUNT(*) > 1 only catches exact copies. It misses “same email, different id” and “same name, extra spaces.” Worth deciding:
Add MariaDB as a third test target, not a rewrite. It speaks the MySQL protocol, so your CLI will probably connect. What can still drift is sql_mode / ONLY_FULL_GROUP_BY and how GROUP BY treats NULL. One extra fixture database labeled MariaDB saves you from “works on MySQL 8, surprises on a host running MariaDB.”
Drop the repo. The interesting part is how you pick the survivor, not the CLI wrapper.
1
u/gumnos Sep 03 '26
I usually do this with a pair of queries, an initial one to identify duplicates, something like
I can then view the set of first-duplicates with
I can then change that
SELECT *to aDELETEand delete the first duplicate. If records have more than one duplicate I can rerun theDELETEuntil it deletes 0 rows.