optimized runQuery function