Fixing a bug with where the ORDER BY clause is put in the SQL statement