Bug fix in SQL query