refactor this sorting and query to do more heavy lifting in the database