Fixed bug in SQL query