Fixing bug in sql query