Fixed bugs with sql query