Bit more refactoring for the queryDB so that it works faster.