Last active
December 17, 2017 11:24
-
-
Save StevenJL/853d4622fb09e3c45b93abeb91720c10 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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