More fixes in SQL query