Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4activerecord

Better method to find the second largest element in ruby on rails active record query


I am using this query to find the 2nd largest element. I am making query on value column.

Booking.where("value < ?", Booking.maximum(:value)).last

Is there any better query than this? Or any alternative to this.

PS - value is not unique. There could be two elements with same value


Solution

  • This should work.

    Booking.select("DISTINCT value").order('value DESC').offset(1).limit(1)
    

    Which will generate this query :

     SELECT  DISTINCT value FROM "bookings"  ORDER BY value DESC LIMIT 1 OFFSET 1