How do you run a MySQL query from a rake task?

Viewed 9908

I'm working on removing duplicates from a legacy database for a client of mine, and I've found a MySQL query to do just that. I want to create a Rake task to run the query for the production server. How would I do that?

MySQL query:

    select * from community_event_users;
    create table dups as
      select distinct username, count(*)
      from community_event_users group by username
      having count(*) > 1;
    delete community_event_users from community_event_users inner join dups
    on community_event_users.username = dups.username;

    insert into community_event_users select username from dups;
2 Answers

For Rails 5 and above you better use:

ApplicationRecord.connection.execute <<~END_OF_SQL
  YOUR QUERY HERE
END_OF_SQL
Related