PIM-1627 Dividing the query in 3 steps to help improve performance and maintenability