Which of the following Rails ActiveRecord queries correctly groups users by their city and selects only those cities having more than 5 users?
Remember that having expects a SQL condition as a string, and where cannot be used with aggregate functions directly.
Option C correctly uses having('count(*) > 5') to filter groups by count. Option C incorrectly uses where with an aggregate function, which is invalid. Option C uses an undefined variable count without quotes, causing an error. Option C uses count without parentheses in the SQL string, which is invalid SQL syntax.
Given the query Order.group(:status).having('sum(total) > 1000').sum(:total), what is the output?
Order.group(:status).having('sum(total) > 1000').sum(:total)
Think about what group, having, and sum do together in ActiveRecord.
The query groups orders by status, filters groups where the sum of total is greater than 1000, then returns a hash mapping each status to its sum total. Option A ignores the having clause. Option A misunderstands the grouping and aggregation. Option A is incorrect because sum can be used with having.
Consider this Rails query:
User.group(:role).having('count(id) > ?', 3).countIt raises an error. What is the cause?
User.group(:role).having('count(id) > ?', 3).count
Think about how ActiveRecord handles SQL fragments with parameters in having.
ActiveRecord does not support parameter binding (the question mark placeholder) inside having clauses. This causes an error. Option A is false because chaining count is valid. Option A is incorrect because aliasing is not required here. Option A is wrong because group must come before having.
Which statement best explains the difference between where and having clauses in ActiveRecord queries?
Think about when filtering happens in SQL query execution order.
where filters individual rows before grouping happens. having filters the grouped results after aggregation. They serve different purposes and are not interchangeable.
Given the following ActiveRecord query:
Product.group(:category).having('avg(price) < 50').count.keys.sizeWhat does this expression return?
Product.group(:category).having('avg(price) < 50').count.keys.sizeConsider what count returns when used after group and having.
The count method returns a hash with keys as categories and values as counts. Using keys.size counts how many categories meet the having condition (average price < 50). Option B confuses product count with group count. Option B ignores the having filter. Option B is incorrect because keys.size is valid on the hash.
