Sort key purpose and usage in DynamoDB - Time & Space Complexity
When using a sort key in DynamoDB, it helps organize data within a partition. Understanding how time grows when querying with a sort key is important.
We want to know how the number of operations changes as more items share the same partition key but have different sort keys.
Analyze the time complexity of querying items using a partition key and a sort key condition.
const params = {
TableName: "Orders",
KeyConditionExpression: "CustomerId = :cid AND OrderDate > :date",
ExpressionAttributeValues: {
":cid": "12345",
":date": "2023-01-01"
}
};
const result = await dynamodb.query(params).promise();
This code fetches orders for one customer where the order date is after a certain date, using the sort key to filter.
Look at what repeats when the query runs.
- Primary operation: Checking items with the same partition key and evaluating the sort key condition.
- How many times: Once for each item with that partition key until the condition is met or all are checked.
As more orders exist for the same customer, the query checks more items to find those matching the date condition.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows roughly in direct proportion to how many items share the partition key.
Time Complexity: O(n)
This means the time to get results grows linearly with the number of items that have the same partition key.
[X] Wrong: "Using a sort key means queries always run in constant time regardless of data size."
[OK] Correct: The sort key helps organize data, but if many items share the partition key, the query still checks each relevant item, so time grows with that number.
Knowing how sort keys affect query time shows you understand how DynamoDB organizes data and how to write efficient queries. This skill helps you design tables that scale well.
"What if we added a filter on a non-key attribute after the query? How would that affect the time complexity?"