pull out query code to simplify