Last active
November 8, 2024 09:21
-
-
Save rob-murray/b3528ffcd71040a9fdf1 to your computer and use it in GitHub Desktop.
Rails find duplicate records
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
columns_that_make_record_distinct = [:some_id, :another_name] | |
duplicate_records = Model.where.not(id: Model.select("MIN(id) as id").group(columns_that_make_record_distinct)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also the
.map(&:id)
makes the whole query more inefficient, note the difference between these 2 snippets:That is, the current version does a first query to load the IDs that later are passed to the 2nd query as an array of IDs (which can be very large). The improved version, instead, does not eager load the result of the 1st query, it just does a single query passing the IDs as a subquery, which is more efficient.