# Sort by size of column

**URL:** <https://www.ruby-forum.com/t/sort-by-size-of-column/92142>\
**Category:** Rails\
**Created:** [April 16, 2007, 4:42pm UTC](https://www.ruby-forum.com/t/sort-by-size-of-column/92142 "2007-04-16T16:42:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![plewizard](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ce7236/32.png) [@plewizard](https://www.ruby-forum.com/u/plewizard)\
**Post date:** [April 16, 2007, 4:42pm UTC](https://www.ruby-forum.com/t/sort-by-size-of-column/92142/1 "2007-04-16T16:42:55Z")

</div>

this is a SQL question that has always stumped me. how to order by  
the size of a column. for instance suppose many Presidents have many  
Votes and you want to list them in a ranking table.

1. Bob 345 Votes
2. Jim 215 Votes  
3 Karen 121 Votes

etc. what’s the SQL for that? is it possible in SQL to count columns  
within a query of Presidents and then order by the count?

---

<div class="post-metadata">

**Author:** ![plewizard](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ce7236/32.png) [@plewizard](https://www.ruby-forum.com/u/plewizard)\
**Post date:** [April 16, 2007, 4:45pm UTC](https://www.ruby-forum.com/t/sort-by-size-of-column/92142/2 "2007-04-16T16:45:56Z")

</div>

SELECT name, votes FROM presidents ORDER BY votes DESC

On 4/16/07, plewizard [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> etc. what’s the SQL for that? is it possible in SQL to count columns  
> within a query of Presidents and then order by the count?
> 
> >

–  
[http://www.web-buddha.co.uk](http://www.web-buddha.co.uk)

---

<div class="post-metadata">

**Author:** ![plewizard](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ce7236/32.png) [@plewizard](https://www.ruby-forum.com/u/plewizard)\
**Post date:** [April 16, 2007, 5:38pm UTC](https://www.ruby-forum.com/t/sort-by-size-of-column/92142/3 "2007-04-16T17:38:04Z")

</div>

Are you saying here that you have two tables for Presidents and  
Votes. And you are wanting to sort by counting the related vote  
objects? If so you could do something like:

SELECT presidents.name, count(votes._) from presidents INNER JOIN  
votes ON president.id=votes.president\_id ORDER BY count(votes._) DESC;

But, that’s terribly inefficient and will likely cause major  
performance problems. Your best bet is to use the facility in Rails  
to cache the vote counts inside your presidents table so that you can  
use a much more efficient SQL statement like:

SELECT name, votes FROM presidents ORDER BY votes DESC;

Look up information on the :counter\_cache option of :belongs\_to in the  
ActiveRecord documentation. That should point you in the right  
direction.

On Apr 16, 10:41 am, “plewizard”
