Move query handling into a function