optimize SQL by removing unecessary query