Search code examples
sqlruby-on-railsarel

Correct sql (arel) for this query?


I have two tables, one with users, the other with profiles. Each table has a created_at column, where I want to update profiles.created_at so that it is the same as the corresponding row (determined by user_id) in users.created_at.

In Rails, I might do something like:

Profile.update_all(created_at: {???})

Trying to create an efficient query as this is being performed on over a million rows.


Solution

  • update  profiles p 
    set     p.created_at = (select  u.created_at 
                            from    users u 
                            where   u.user_id = p.user_id 
                            and     u.created_at <> p.created_at
                            )