Fix bug in query builder for caching. Fixes #1640.