refactor sql in queries