Moved sorting into the query to reduce lines of code