refactor handle logic  for less sql queries