Whenever you perform a [`query`](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html) operation against a [[DynamoDB]] table or GSI, you can specify a [`Limit`](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html#API_Query_RequestSyntax) telling the maximum number of results to be returned that match the included criteria. If you don't specify a limit, then DynamoDB will automatically cap the number of results returned whenever the processed dataset reaches 1MB. Whenever a resultset is returned that has reached the limit, a [`LastEvaluatedKey` field](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html#DDB-Query-response-LastEvaluatedKey) is provided in the response indicating that there are further results to fetch. This field contains the primary key of the last item returned in the result set. This field is an object, not a scalar type, (technically an `AttributeMap`) containing the attribute names and values of the partition and sort keys of the table/index being queried. Subsequent `query` requests need to supply the value of the `LastEvaluatedKey` as the [`ExclusiveStartKey`](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html#DDB-Query-request-ExclusiveStartKey) argument in order to fetch the next page of results. ## Edge cases to consider - *"A `Query` operation can return an empty result set and a `LastEvaluatedKey` if all the items read for the page of results are filtered out."* (see [here](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html)) ## Limitations of paging with DynamoDB Many web apps use a "Page X of Y" notation to show the user what page they are on, where Y is the total number of pages available. However, since the DynamoDB `Query` operation only returns a pointer to the first record of the next page of results, and has no knowledge of how many total results match the query criteria, it is not possible to compute a total number of pages purely by querying the table. If this functionality is really needed, there are a few (pretty ugly) options: 1. Maintain a total count field in DDB that gets updated whenever matching records are added/removed. But this is very inflexible in terms of the filter criteria. 2. Perform 2 concurrent queries using the same filter criteria, one that only projects the ID field with no limit specified, and one projecting all the fields and with the limit included. Then return the count of the first result set. This is far from ideal too though as it would require more DDB read units, and still mightn't work with very large numbers of matching records. --- ## References - [Discussion on dynamodbplace.com: How do you get the total count when using pagination in DynamoDB?](https://dynamodbplace.com/c/questions/how-do-you-get-the-total-count-when-using-pagination-in-dynamodb)