fixing bugs in speeding up query