Query improvements

Various improvements to query correctness and speed.