fix inefficient query