in reply to while (my @row = $sth->fetchrow_array)
You can use order by in the select query so that the Implicit sorting is done in the select query itself.