Reputation: 127
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
Upvotes: 0
Views: 1240
Reputation: 310
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
Upvotes: 4
Reputation: 13487
You can use offset
and last
:
Booking.order(:value).offset(1).last
Which will produce following SQL statement:
SELECT `bookings`.* FROM `bookings`
ORDER BY `bookings`.`value` DESC
LIMIT 1 OFFSET 1
Upvotes: 4