Extract query code to function