Improved flatten and usage of memory in SELECT by using iterators rather than collections