Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Selecting duplicate records
Michal Bryxí
Michal Bryxí

Posted on • Edited on

     

Selecting duplicate records

Selecting duplicate records might be useful in cases when you want to introduce newmulti column index on existing data.


duplicates=ActiveRecord::Base.connection.execute('  SELECT items.id, items.name    FROM items    WHERE items.id IN (      SELECT        id        FROM (          SELECT          id,          ROW_NUMBER() OVER w AS rnum          FROM items          WINDOW w AS (            PARTITION BY entity_id, barcode            ORDER BY id            )          ) t          WHERE t.rnum > 1       );    ')
Enter fullscreen modeExit fullscreen mode

Our exported data set will haveid andname, so that we can tell which rows we want to delete. And it will only show rows whereentity_id andbarcode wouldnot be unique. That's an example, yours will be different.

After the cleanup, when the query above would return an empty result set we should be able to create following index without any issues:

add_index(:items,[:entity_id,:barcode])
Enter fullscreen modeExit fullscreen mode

Inspiration taken from the articleRails: migration: Adding a unique Index and deleting Duplicates


Image generated via Midjourney prompt:Heap of items where every object is represented twice; --ar 16:9

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
nullvoxpopuli profile image
NullVoxPopuli
I like code.
  • Joined

A comment, by request

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Cycle 🚴 , climb 🗻 , run 🏃 , travel 🌍 , enjoy life ♥.IT guy with the need to live fully.
  • Location
    Interlaken, Switzerland
  • Education
    University of West Bohemia
  • Pronouns
    he/him
  • Work
    Sandcastle Architect
  • Joined

More fromMichal Bryxí

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp