Fixed bug in SQL queries