Challenge - 5 Problems
Raw SQL Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this raw SQL query in Rails?
Given the following Rails code using raw SQL, what will be the output when fetching the user's name?
Ruby on Rails
user = User.find_by_sql(["SELECT name FROM users WHERE id = ?", 1]).first user.name
Attempts:
2 left
💡 Hint
The query selects the name column for user with id 1.
✗ Incorrect
The raw SQL query returns an array of User objects with only the name attribute loaded. Accessing user.name returns the name string.
📝 Syntax
intermediate2:00remaining
Which option correctly uses raw SQL with parameter binding in Rails?
Select the option that safely executes a raw SQL query to find users older than a given age.
Attempts:
2 left
💡 Hint
Look for the correct way to pass parameters safely to avoid SQL injection.
✗ Incorrect
Option B uses the array form with ? placeholder and parameter binding, which is the correct and safe way.
🔧 Debug
advanced2:00remaining
Why does this raw SQL query raise an error in Rails?
Examine the code below and select the reason for the error raised.
Ruby on Rails
User.find_by_sql("SELECT * FROM users WHERE name = 'O'Reilly'")Attempts:
2 left
💡 Hint
Look at how the single quote in the name is handled inside the SQL string.
✗ Incorrect
The single quote in O'Reilly breaks the SQL string syntax causing a syntax error.
❓ state_output
advanced2:00remaining
What is the value of 'count' after running this raw SQL in Rails?
Consider this code snippet. What will be the value of 'count'?
Ruby on Rails
result = ActiveRecord::Base.connection.select_all("SELECT COUNT(*) FROM users WHERE active = true") count = result.first['count']
Attempts:
2 left
💡 Hint
Check the data type returned by raw SQL execution for count queries.
✗ Incorrect
The raw SQL returns a hash with string keys and string values, so count is a string representing the number.
🧠 Conceptual
expert2:00remaining
Why might you choose raw SQL over ActiveRecord query methods in Rails?
Select the best reason to use raw SQL instead of ActiveRecord query methods.
Attempts:
2 left
💡 Hint
Think about limitations of ActiveRecord and when raw SQL is necessary.
✗ Incorrect
Raw SQL is used when queries are too complex or specific for ActiveRecord's methods. It is not always faster and requires care for security.