Back to Course

Practice · Scaling · Card 8

How many SQL writes does this loop fire?

A cleanup task. 100,000 draft posts to mark published. The code reads like a one-liner. The database sees it differently.

The code

A rake task to publish all draft posts older than a week.

Post.where(status: "draft")
    .where("created_at < ?", 1.week.ago)
    .each do |post|
  post.update(status: "published")
end

# Suppose this matches 100,000 posts.

The question

For 100,000 matching posts, how many SQL UPDATE statements does this fire?

Take a moment. Pick the best answer. Wrong picks reveal why they're wrong, which is half the point.