Chain an additional order on a Rails activerecord query? <p>Activerecord seems to ignore my second <code>order</code> in a chained AR query.</p> <p>What I'm trying to do is retrieve the top 5 most-read articles <em>within</em> the top 25 highest-scored (eg. rated by users) articles.</p> <p><code>Article</code> has both <code>read_count</code> (integer) and <code>score</code> (float) columns that I order by.</p> <p>My (naive?) attempt was this query:</p> <pre><code>Article.order("score DESC").limit(25).order("read_count DESC").limit(5) </code></pre> <p>What this returns is simply the first 5 highest-scored articles, rather than the 5 most-read articles within the first 25 highest-scored.</p> <p>Can I do this in a single query? Thanks for any help!</p> <p><em>(I'm on Rails 3.2 and Postgres 9.2)</em></p> <p><strong>Addendum</strong></p> <p>Thank you to brad and Philip Hallstrom for two solutions to this. Either would have been acceptable, although I went with brad's database-only solution as explained in my comment on his answer.</p> <p>Profiling each query on my local development machine (MBA) showed the subquery solution to be 33% faster than the Ruby-loop solution. Profiling the queries on my production machine (Heroku + Crane production database) showed the subquery solution to be <strong>95% faster</strong>! (this is across a database of 40,000 articles).</p> <p>While the actual time taken is pretty insignificant, 95% faster and 50% fewer lines of code is a pretty good decider.</p> <pre><code>Ruby-loop solution: (Philip) dev: 24 msec prod: 16 msec Sub-query solution: (brad) dev: 22 msec prod: 0.9 msec </code></pre> <p>Thanks to both Philip and brad for their answers!</p>