Properly handle pagination in query