Some refactoring in query in preparation for provider specific SQL gen