Refactor sql queries