fixed bug in sql query construction