class AddUniquenessToSomeTable < ActiveRecord::Migration[5.2]
def up
execute <<-SQL
-- deleting conflicting entries
DELETE FROM
TABLE a USING TABLE b
WHERE
a.id < b.id
AND a.some_column = b.some_column
AND DATE(a.some_column2) = DATE(b.some_column2);
-- create unique index
CREATE UNIQUE INDEX unique_index_on_some_column_per_day ON table (some_column, date(some_column2));
SQL
end
def down
execute <<-SQL
DROP INDEX unique_index_on_some_column_per_day;
SQL
end
end
Deleting duplicate records during unique index creation
Subscribe to A Developer's Diary
Get the latest posts delivered right to your inbox