Optimized query function.