Query result ordering (ascending, descending) in DynamoDB - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we ask DynamoDB to return items in order, we want to know how the time it takes changes as we get more data.
We are trying to see how sorting results affects the work DynamoDB does.
Analyze the time complexity of the following code snippet.
// Query items from a DynamoDB table
const params = {
TableName: "Orders",
KeyConditionExpression: "CustomerId = :cid",
ExpressionAttributeValues: {
":cid": { S: "12345" }
},
ScanIndexForward: false // false means descending order
};
const result = await dynamodb.query(params).promise();
This code fetches all orders for a customer and returns them in descending order by sort key.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: DynamoDB reads each matching item once to return it.
- How many times: Once per matching item in the query result.
As the number of matching items grows, DynamoDB reads more items to return them in order.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 reads |
| 100 | About 100 reads |
| 1000 | About 1000 reads |
Pattern observation: The work grows directly with the number of items returned, whether ascending or descending.
Time Complexity: O(n)
This means the time to get results grows linearly with how many items match the query, regardless of order direction.
[X] Wrong: "Ordering results descending makes the query slower than ascending."
[OK] Correct: DynamoDB stores data sorted by the sort key, so reading in ascending or descending order just changes the direction of reading, not the amount of work.
Understanding how DynamoDB handles ordering helps you explain how queries scale and shows you know how databases manage data efficiently.
"What if we added a filter expression after the query? How would that affect the time complexity?"
Practice
Solution
Step 1: Understand query ordering in DynamoDB
DynamoDB orders query results based on the sort key, and the order can be controlled.Step 2: Identify the controlling parameter
The parameterScanIndexForwardcontrols ascending (true) or descending (false) order.Final Answer:
ScanIndexForward-> Option CQuick Check:
Ordering parameter = ScanIndexForward [OK]
- Confusing ScanIndexForward with ReturnConsumedCapacity
- Thinking ordering applies to partition key
- Assuming default order is descending
Orders with results in descending order on the sort key OrderDate?Solution
Step 1: Identify the parameter for descending order
To get descending order,ScanIndexForwardmust be set tofalse.Step 2: Check the syntax correctness
client.query({ TableName: 'Orders', KeyConditionExpression: 'CustomerId = :id', ExpressionAttributeValues: { ':id': '123' }, ScanIndexForward: false }) usesScanIndexForward: falsecorrectly; other options use invalid or wrong parameters.Final Answer:
Option B syntax with ScanIndexForward false -> Option BQuick Check:
Descending order = ScanIndexForward false [OK]
- Using ScanIndexForward true for descending order
- Using non-existent parameters like Descending or OrderBy
- Confusing partition key with sort key ordering
UserId and sort key Timestamp, what will be the order of results returned by this query?client.query({
TableName: 'UserActivity',
KeyConditionExpression: 'UserId = :uid',
ExpressionAttributeValues: { ':uid': 'user123' },
ScanIndexForward: false
})Solution
Step 1: Understand ScanIndexForward effect
SettingScanIndexForward: falsereturns results in descending order of the sort key.Step 2: Identify the sort key
The sort key isTimestamp, so results are ordered newest to oldest.Final Answer:
Results ordered by Timestamp descending (newest first) -> Option DQuick Check:
ScanIndexForward false = descending order [OK]
- Assuming ScanIndexForward false orders by partition key
- Thinking default order is descending
- Confusing ascending and descending meanings
client.query({
TableName: 'Sales',
KeyConditionExpression: 'StoreId = :sid',
ExpressionAttributeValues: { ':sid': 'store1' },
ScanIndexForward: 'false'
})What is the error?
Solution
Step 1: Check ScanIndexForward data type
ScanIndexForward expects a boolean true or false, not a string.Step 2: Identify impact of wrong type
Passing 'false' as a string is truthy, so DynamoDB treats it as true (ascending order).Final Answer:
ScanIndexForward must be boolean false, not string 'false' -> Option AQuick Check:
Boolean type needed for ScanIndexForward [OK]
- Passing 'false' as a string instead of boolean
- Misunderstanding KeyConditionExpression syntax
- Ignoring data types in parameters
cust123 from a DynamoDB table Orders with partition key CustomerId and sort key OrderDate. Which query will correctly return these orders in descending order by OrderDate?Solution
Step 1: Set descending order for most recent first
UseScanIndexForward: falseto get descending order byOrderDate.Step 2: Limit results to 5
UseLimit: 5to get only the top 5 recent orders.Final Answer:
Query with ScanIndexForward false and Limit 5 -> Option AQuick Check:
Descending + Limit 5 = ScanIndexForward false + Limit 5 [OK]
- Using ScanIndexForward true returns oldest first
- Omitting Limit returns all items
- Not combining descending order with limit
