Calculating Percentage Complete via a SQL Query
Posted by Corey Ehmke on December 22nd, 2008 in Ruby on Rails | Permanent Link | Share/SaveTags: MySQL, Ruby on Rails, SQL
I needed to update an attribute on a bunch of records today. In the model, there’s a before save condition that generates a permalink based on the record’s name. So in script/console, I populated an array with Location.all, iterated over the array, and called save(false) on each. The operation was taking a while, so I hopped over to CocoaMySQL to monitor the progress of the operation.
While I waited, I wrote a little SQL query to calculate the progress of the operation:
select (select count(*) from locations where url is null) as unprocessed, (select count(*) from locations where url is not null) as processed, (((select processed / (unprocessed + processed)) * 100)) as "% complete";
Sample output:

Nothing terribly complex, but cool and generally useful.