Query improvements and bugfixes