Split queryEntities list and count queries to fix CTE materialization bottleneck
