fixed sql query optimisation  and performance issue