Posted almost 8 years ago. Visible to the public.

MySQL: Do not use "WHERE id IN (SELECT ....)"

Note: This applies specifically to MySQL. In PostgreSQL for example, this is not an issue.

If you care about performance, never use a query like

Copy
UPDATE users SET has_message = 1 WHERE users.id IN (SELECT user_id FROM messages)

MySQL does not optimize this and seems to scan the temporary table, which isn't indexed, for every row in the update statement. This applies to other statements than UPDATE as well.

Instead, either use a JOIN like

Copy
UPDATE users INNER JOIN messages ON messages.user_id = users.id SET has_message = 1

or pipe it through ruby with something like

Copy
user_ids = ActiveRecord::Base.connection.select_values(Message.select(:user_id).to_sql) # Rails 2 user_ids = Message.all.pluck(:user_id) # Rails 3+ User.where(:id => user_ids).update_all(:has_message => 1)

Be aware that MySQL can take many but not too many arguments. Passing a list of 100'000 arguments to an IN statement won't work.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Tobias Kraze
Last edit:
10 months ago
by Henning Koch
Keywords:
sub, queries, sub, select, sub, query
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Tobias Kraze to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more