Query with sort key conditions in DynamoDB - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we query a DynamoDB table using a sort key condition, we want to know how the time it takes changes as the data grows.
We ask: How does the number of items affect the work DynamoDB does to find matching results?
Analyze the time complexity of the following code snippet.
const params = {
TableName: "Orders",
KeyConditionExpression: "CustomerId = :cid AND OrderDate > :date",
ExpressionAttributeValues: {
":cid": { S: "12345" },
":date": { S: "2023-01-01" }
}
};
const result = await dynamodb.query(params).promise();
This code queries the "Orders" table for all orders by a customer with ID "12345" where the order date is after January 1, 2023.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning through the items with the matching CustomerId and checking the OrderDate condition.
- How many times: Once for each item with that CustomerId until all matching dates are found or the query limit is reached.
As the number of orders for the customer grows, DynamoDB checks more items to find those after the given date.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the number of items with the same CustomerId.
Time Complexity: O(n)
This means the time to complete the query grows linearly with the number of items that share the same partition key.
[X] Wrong: "The query will always be fast no matter how many items match the partition key because DynamoDB is fast."
[OK] Correct: While DynamoDB is optimized, the query still needs to check each item with the matching partition key to apply the sort key condition, so more items mean more work.
Understanding how queries scale with data size helps you design efficient DynamoDB tables and write queries that perform well in real projects.
"What if we added a filter expression after the query? How would that affect the time complexity?"
Practice
Query operation with a sort key condition, which of the following is always required?Solution
Step 1: Understand Query requirements
A DynamoDB Query must always specify the partition key with '=' to identify the partition.Step 2: Add sort key condition
You can add conditions on the sort key to filter items within that partition.Final Answer:
Specify the partition key with '=' and a condition on the sort key -> Option CQuick Check:
Partition key '=' + sort key condition = required [OK]
- Trying to query without specifying partition key
- Using scan instead of query for sort key filtering
- Specifying only sort key condition without partition key
Timestamp is greater than 1000?Solution
Step 1: Use '=' for partition key
The partition key must be compared with '=' in the KeyConditionExpression.Step 2: Use '>' for sort key condition
The sort key condition can use operators like '>' to filter items.Final Answer:
KeyConditionExpression: 'PartitionKey = :pk AND Timestamp > :ts' -> Option DQuick Check:
PartitionKey '=' and sort key '>' correct syntax [OK]
- Using OR instead of AND in KeyConditionExpression
- Using '>' for partition key instead of '='
- Using '==' instead of '=' for partition key
UserID and sort key OrderDate, what will the following query return?KeyConditionExpression: 'UserID = :uid AND OrderDate BETWEEN :start AND :end'
ExpressionAttributeValues: { ':uid': 'user123', ':start': '2023-01-01', ':end': '2023-01-31' }Solution
Step 1: Partition key '=' filters user
The query filters items where UserID equals 'user123'.Step 2: Sort key BETWEEN filters date range
The BETWEEN operator selects OrderDate values from '2023-01-01' to '2023-01-31' inclusive.Final Answer:
All orders for 'user123' placed between January 1 and January 31, 2023 inclusive -> Option AQuick Check:
Partition key '=' + sort key BETWEEN returns filtered range [OK]
- Assuming query returns all users' orders
- Thinking BETWEEN excludes boundary dates
- Believing BETWEEN is invalid in KeyConditionExpression
KeyConditionExpression: 'UserID = :uid AND OrderDate > :date'
ExpressionAttributeValues: { ':uid': 'user123', ':date': '2023-12-31' }What is the most likely reason?
Solution
Step 1: Check operator validity
The '>' operator is valid for sort key conditions in DynamoDB queries.Step 2: Consider data existence
If no items have OrderDate after '2023-12-31' for 'user123', query returns empty.Final Answer:
No items exist with OrderDate after 2023-12-31 for user123 -> Option AQuick Check:
Valid syntax but no matching data = empty result [OK]
- Thinking '>' is invalid in KeyConditionExpression
- Using '>' for partition key instead of '='
- Misunderstanding ExpressionAttributeValues syntax
CustomerID and sort key InvoiceDate. You need to find all invoices for CustomerID = 'C123' where InvoiceDate is either before '2023-01-01' or after '2023-12-31'. Which approach correctly achieves this?Solution
Step 1: Understand KeyConditionExpression limits
DynamoDB KeyConditionExpression supports only AND between partition key and sort key conditions, no OR.Step 2: Query with OR on sort key requires multiple queries
To get items before '2023-01-01' OR after '2023-12-31', run two queries and merge results.Final Answer:
Run two separate queries: one with InvoiceDate < '2023-01-01' and another with InvoiceDate > '2023-12-31', then combine results -> Option BQuick Check:
OR on sort key = multiple queries combined [OK]
- Trying to use OR in KeyConditionExpression
- Using BETWEEN for non-continuous ranges
- Using scan instead of efficient queries
