Reduce sql queries