The whole query construction is rather ugly and needs to be refactored.