Bird
Raised Fist0
Ruby on Railsframework~20 mins

Database query optimization in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rails Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Understanding N+1 Query Problem in Rails

What is the main cause of the N+1 query problem in Rails ActiveRecord?

AUsing eager loading with <code>includes</code> to preload associations
BLoading associated records inside a loop without eager loading
CQuerying the database only once for all records
DUsing raw SQL queries instead of ActiveRecord methods
Attempts:
2 left
💡 Hint

Think about what happens when you access related data inside a loop.

❓ component_behavior
intermediate
2:00remaining
Effect of Using includes vs joins

Given a Rails model Post with many comments, what is the difference in database queries when using Post.includes(:comments) versus Post.joins(:comments)?

A<code>includes</code> loads only posts; <code>joins</code> loads only comments
B<code>includes</code> performs an INNER JOIN; <code>joins</code> loads posts and comments separately
C<code>includes</code> loads posts and comments in separate queries; <code>joins</code> performs an INNER JOIN returning combined rows
D<code>includes</code> and <code>joins</code> both perform the same single query with LEFT JOIN
Attempts:
2 left
💡 Hint

Consider how eager loading and joining affect the number and type of queries.

📝 Syntax
advanced
2:00remaining
Correct Use of select to Optimize Query

Which option correctly uses select in Rails ActiveRecord to fetch only the id and name columns from the User model?

AUser.select(:id, :name)
BUser.select('id name')
CUser.select('id, name')
DUser.select(:id name)
Attempts:
2 left
💡 Hint

Remember how to pass multiple columns as symbols or strings in select.

🔧 Debug
advanced
2:00remaining
Identifying Cause of Slow Query in Rails

Given this code snippet, why is the query slow?

users = User.all
users.each do |user|
  puts user.profile.bio
end
ABecause <code>profile.bio</code> is a method, not a database column
BBecause <code>User.all</code> loads too many users at once
CBecause <code>puts</code> slows down the loop
DBecause <code>profile</code> association is not eager loaded, causing N+1 queries
Attempts:
2 left
💡 Hint

Think about how accessing associations inside loops affects queries.

❓ state_output
expert
2:00remaining
Output of Query with pluck and distinct

What is the output of this Rails code?

Product.where(category: 'books').pluck(:author).uniq

Assuming the database has authors: ['Alice', 'Bob', 'Alice', 'Carol'] in that category.

A['Alice', 'Bob', 'Carol']
B['Alice', 'Bob', 'Alice', 'Carol']
C['Alice', 'Bob', 'Carol', 'Alice']
D['Alice', 'Bob']
Attempts:
2 left
💡 Hint

Remember that pluck returns an array and uniq is a Ruby method applied after fetching.

Practice

(1/5)
1. What is the main benefit of using includes in Rails queries?
easy
A. It loads associated records in fewer database queries to improve performance.
B. It deletes unused records from the database automatically.
C. It encrypts data before saving to the database.
D. It creates new database tables for associations.

Solution

  1. Step 1: Understand what includes does

    includes loads related records in one or fewer queries to avoid repeated database hits.
  2. Step 2: Identify the benefit

    This reduces the number of queries, speeding up the app and saving server resources.
  3. Final Answer:

    It loads associated records in fewer database queries to improve performance. -> Option A
  4. Quick Check:

    Using includes reduces queries = B [OK]
Hint: Think: fewer queries means faster loading [OK]
Common Mistakes:
  • Confusing includes with deleting records
  • Thinking includes encrypts data
  • Assuming includes creates tables
2. Which of the following is the correct syntax to select only the name and email columns from a User model in Rails?
easy
A. User.find(:name, :email)
B. User.where(:name, :email)
C. User.includes(:name, :email)
D. User.select(:name, :email)

Solution

  1. Step 1: Recall the method to choose specific columns

    The select method specifies which columns to retrieve from the database.
  2. Step 2: Check the syntax

    User.select(:name, :email) correctly selects only the name and email columns.
  3. Final Answer:

    User.select(:name, :email) -> Option D
  4. Quick Check:

    Select columns = select method = D [OK]
Hint: Use select to pick columns, not where or includes [OK]
Common Mistakes:
  • Using where instead of select for columns
  • Using includes to select columns
  • Using find with multiple columns
3. Given the following Rails code:
posts = Post.includes(:comments).where(published: true)

What is the main effect of this query?
medium
A. It loads all posts and their comments, regardless of published status.
B. It loads only comments for published posts but not the posts themselves.
C. It loads only published posts and their comments efficiently in fewer queries.
D. It deletes unpublished posts and their comments.

Solution

  1. Step 1: Analyze the query filters and includes

    The where(published: true) filters posts to only those published. includes(:comments) loads comments with posts efficiently.
  2. Step 2: Understand the combined effect

    The query fetches published posts and their comments in fewer database queries, improving performance.
  3. Final Answer:

    It loads only published posts and their comments efficiently in fewer queries. -> Option C
  4. Quick Check:

    Filter + includes = efficient published posts with comments = C [OK]
Hint: Filter first, then includes loads related data efficiently [OK]
Common Mistakes:
  • Thinking includes ignores the where filter
  • Assuming comments load without posts
  • Confusing includes with deletion
4. Identify the problem in this Rails query and how to fix it:
users = User.where(active: true).includes(:posts).select(:name)
medium
A. The select excludes the primary key (:id), causing posts not to load; fix by including :id in select.
B. The includes method is used incorrectly; replace it with joins.
C. The where clause should come after select to filter correctly.
D. The query will delete inactive users; remove where clause.

Solution

  1. Step 1: Understand select limits columns

    The select(:name) limits columns returned, but the primary key id is missing.
  2. Step 2: Effect on includes

    Without the primary key, Rails cannot load associated posts properly with includes.
  3. Step 3: Fix the query

    Add the primary key column (e.g., :id) to the select list to allow loading posts.
  4. Final Answer:

    The select excludes the primary key (:id), causing posts not to load; fix by including :id in select. -> Option A
  5. Quick Check:

    Select must include primary key for includes to work = A [OK]
Hint: Always select primary keys when using includes [OK]
Common Mistakes:
  • Removing primary key from select breaks associations
  • Replacing includes with joins unnecessarily
  • Changing where order incorrectly
5. You want to optimize a query to fetch Order records with their Customer and only the total_price and created_at fields from orders. Which Rails query is best for this optimization?
hard
A. Order.joins(:customer).select('orders.total_price, orders.created_at, customers.*')
B. Order.includes(:customer).select(:total_price, :created_at, :customer_id)
C. Order.includes(:customer).select(:total_price, :created_at)
D. Order.all.select(:total_price, :created_at)

Solution

  1. Step 1: Identify needed fields and associations

    You want orders with only total_price and created_at, plus associated customers.
  2. Step 2: Ensure foreign key is selected for includes

    Using includes(:customer) requires selecting the foreign key customer_id to load customers efficiently.
  3. Step 3: Choose the query that selects needed fields and includes association correctly

    Order.includes(:customer).select(:total_price, :created_at, :customer_id) meets all requirements.
  4. Final Answer:

    Order.includes(:customer).select(:total_price, :created_at, :customer_id) -> Option B
  5. Quick Check:

    Select needed fields + foreign key + includes = A [OK]
Hint: Include foreign keys in select when using includes [OK]
Common Mistakes:
  • Omitting foreign key breaks includes
  • Using joins loads all customer fields unnecessarily
  • Selecting all orders without includes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard