Main query handling code