Search code examples
mysqlruby-on-railsrubyrake

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


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;

Solution

  • If you are on Rails and using ActiveRecord you can simply use:

    ActiveRecord::Base.execute(my_sql)
    
    ActiveRecord::Base.connection.execute(my_sql)
    

    Where my_sql is your SQL string.