optimized query() method