Kangkan
Kangkan

Reputation: 127

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

Upvotes: 0

Views: 1240

Answers (2)

Abdullah Fadhel
Abdullah Fadhel

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

Ilya
Ilya

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

Related Questions