More fixes to the SQL queries