Skip to content

Instantly share code, notes, and snippets.

@StevenJL
Last active December 17, 2017 11:24
Show Gist options
  • Save StevenJL/853d4622fb09e3c45b93abeb91720c10 to your computer and use it in GitHub Desktop.
Save StevenJL/853d4622fb09e3c45b93abeb91720c10 to your computer and use it in GitHub Desktop.
# Suppose we want to select from these n emails those that
# are not already in the `users` table.
emails = [
"[email protected]",
"[email protected]",
"[email protected]",
...
"[email protected]"
]
new_emails = []
emails.each do |email|
unless User.where(email: email).exists?
new_emails << email
end
end
# The above will run n queries, one for each email
# SELECT 1 FROM users WHERE email` = '[email protected]' LIMIT 1;
# SELECT 1 FROM users WHERE email` = '[email protected]' LIMIT 1;
# SELECT 1 FROM users WHERE email` = '[email protected]' LIMIT 1;
# ...
# SELECT 1 FROM users WHERE email` = '[email protected]' LIMIT 1;
# Instead, let's grab all the emails from the database first in one query,
# then filter in memory and store in a Set (since we want to only
# check for inclusion).
existing_emails = Set.new(User.pluck(:email))
# SELECT users.email from users;
new_emails = []
emails.each do |email|
unless existing_emails.include?(email)
new_emails << email
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment