add ordering logic to the SQL query