Bird
Raised Fist0
DynamoDBquery~20 mins

Query result ordering (ascending, descending) in DynamoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
DynamoDB Query Ordering Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the order of results returned by this DynamoDB query?

Consider a DynamoDB table with a partition key UserID and a sort key Timestamp. You run this query to get all items for UserID = 'user123':

QueryRequest request = new QueryRequest()
    .withTableName("UserActivity")
    .withKeyConditionExpression("UserID = :uid")
    .withExpressionAttributeValues(Map.of(":uid", new AttributeValue().withS("user123")))
    .withScanIndexForward(true);

What order will the items be returned in?

AItems are returned in ascending order by the sort key (Timestamp).
BItems are returned in descending order by the sort key (Timestamp).
CItems are returned in random order.
DItems are returned in ascending order by the partition key (UserID).
Attempts:
2 left
💡 Hint

Look at the withScanIndexForward(true) parameter.

query_result
intermediate
2:00remaining
How to get descending order results from a DynamoDB query?

You want to get the latest activity first for a user in a DynamoDB table with UserID as partition key and Timestamp as sort key. Which parameter should you set in the query?

ASet <code>ScanIndexForward</code> to <code>true</code>.
BSet <code>ReturnConsumedCapacity</code> to <code>INDEXES</code>.
CSet <code>ConsistentRead</code> to <code>true</code>.
DSet <code>ScanIndexForward</code> to <code>false</code>.
Attempts:
2 left
💡 Hint

Think about reversing the order of the sort key.

🧠 Conceptual
advanced
2:00remaining
Why can't you order DynamoDB query results by attributes other than the sort key?

DynamoDB queries allow ordering results by the sort key only. Why is it not possible to order by other attributes?

ABecause DynamoDB stores data sorted only by partition key and sort key, so ordering by other attributes would require scanning all data.
BBecause DynamoDB automatically orders by all attributes internally, so specifying others is redundant.
CBecause DynamoDB does not support any ordering of query results.
DBecause ordering by other attributes is only possible with a Scan operation.
Attempts:
2 left
💡 Hint

Think about how DynamoDB stores and indexes data physically.

📝 Syntax
advanced
2:00remaining
Identify the syntax error in this DynamoDB query for descending order

Which option contains a syntax error in setting the query to return results in descending order?

QueryRequest request = new QueryRequest()
    .withTableName("UserActivity")
    .withKeyConditionExpression("UserID = :uid")
    .withExpressionAttributeValues(Map.of(":uid", new AttributeValue().withS("user123")))
    .withScanIndexForward(???);
AwithScanIndexForward(Boolean.FALSE)
BwithScanIndexForward(false)
CwithScanIndexForward("false")
DwithScanIndexForward(0)
Attempts:
2 left
💡 Hint

Check the expected data type for withScanIndexForward.

optimization
expert
3:00remaining
How to efficiently get the last 5 items in descending order from a DynamoDB table?

You want to get the 5 most recent activities for a user from a DynamoDB table with UserID as partition key and Timestamp as sort key. Which approach is best?

AQuery with <code>ScanIndexForward(true)</code> and <code>Limit(5)</code> to get first 5 items in ascending order.
BQuery with <code>ScanIndexForward(false)</code> and <code>Limit(5)</code> to get last 5 items in descending order.
CUse a Global Secondary Index on Timestamp and scan it to get last 5 items.
DScan the whole table and sort results in application code to get last 5 items.
Attempts:
2 left
💡 Hint

Think about how to limit data read and get results in desired order.

Practice

(1/5)
1. In DynamoDB, which parameter controls whether query results are returned in ascending or descending order based on the sort key?
easy
A. ProjectionExpression
B. ReturnConsumedCapacity
C. ScanIndexForward
D. ConsistentRead

Solution

  1. Step 1: Understand query ordering in DynamoDB

    DynamoDB orders query results based on the sort key, and the order can be controlled.
  2. Step 2: Identify the controlling parameter

    The parameter ScanIndexForward controls ascending (true) or descending (false) order.
  3. Final Answer:

    ScanIndexForward -> Option C
  4. Quick Check:

    Ordering parameter = ScanIndexForward [OK]
Hint: Remember: ScanIndexForward controls ascending/descending order [OK]
Common Mistakes:
  • Confusing ScanIndexForward with ReturnConsumedCapacity
  • Thinking ordering applies to partition key
  • Assuming default order is descending
2. Which of the following is the correct syntax to query a DynamoDB table named Orders with results in descending order on the sort key OrderDate?
easy
A. client.query({ TableName: 'Orders', KeyConditionExpression: 'CustomerId = :id', ExpressionAttributeValues: { ':id': '123' }, ScanIndexForward: true })
B. client.query({ TableName: 'Orders', KeyConditionExpression: 'CustomerId = :id', ExpressionAttributeValues: { ':id': '123' }, ScanIndexForward: false })
C. client.query({ TableName: 'Orders', KeyConditionExpression: 'CustomerId = :id', ExpressionAttributeValues: { ':id': '123' }, Descending: true })
D. client.query({ TableName: 'Orders', KeyConditionExpression: 'CustomerId = :id', ExpressionAttributeValues: { ':id': '123' }, OrderBy: 'DESC' })

Solution

  1. Step 1: Identify the parameter for descending order

    To get descending order, ScanIndexForward must be set to false.
  2. Step 2: Check the syntax correctness

    client.query({ TableName: 'Orders', KeyConditionExpression: 'CustomerId = :id', ExpressionAttributeValues: { ':id': '123' }, ScanIndexForward: false }) uses ScanIndexForward: false correctly; other options use invalid or wrong parameters.
  3. Final Answer:

    Option B syntax with ScanIndexForward false -> Option B
  4. Quick Check:

    Descending order = ScanIndexForward false [OK]
Hint: Use ScanIndexForward false for descending order [OK]
Common Mistakes:
  • Using ScanIndexForward true for descending order
  • Using non-existent parameters like Descending or OrderBy
  • Confusing partition key with sort key ordering
3. Given a DynamoDB table with partition key 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
})
medium
A. Results unordered
B. Results ordered by Timestamp ascending (oldest first)
C. Results ordered by UserId ascending
D. Results ordered by Timestamp descending (newest first)

Solution

  1. Step 1: Understand ScanIndexForward effect

    Setting ScanIndexForward: false returns results in descending order of the sort key.
  2. Step 2: Identify the sort key

    The sort key is Timestamp, so results are ordered newest to oldest.
  3. Final Answer:

    Results ordered by Timestamp descending (newest first) -> Option D
  4. Quick Check:

    ScanIndexForward false = descending order [OK]
Hint: ScanIndexForward false means newest items first [OK]
Common Mistakes:
  • Assuming ScanIndexForward false orders by partition key
  • Thinking default order is descending
  • Confusing ascending and descending meanings
4. You wrote this DynamoDB query but the results are always in ascending order, even though you want descending order:
client.query({
  TableName: 'Sales',
  KeyConditionExpression: 'StoreId = :sid',
  ExpressionAttributeValues: { ':sid': 'store1' },
  ScanIndexForward: 'false'
})

What is the error?
medium
A. ScanIndexForward must be a boolean, not a string
B. KeyConditionExpression is incorrect
C. ExpressionAttributeValues is missing a value
D. TableName is invalid

Solution

  1. Step 1: Check ScanIndexForward data type

    ScanIndexForward expects a boolean true or false, not a string.
  2. Step 2: Identify impact of wrong type

    Passing 'false' as a string is truthy, so DynamoDB treats it as true (ascending order).
  3. Final Answer:

    ScanIndexForward must be boolean false, not string 'false' -> Option A
  4. Quick Check:

    Boolean type needed for ScanIndexForward [OK]
Hint: Use boolean false, not string 'false' for ScanIndexForward [OK]
Common Mistakes:
  • Passing 'false' as a string instead of boolean
  • Misunderstanding KeyConditionExpression syntax
  • Ignoring data types in parameters
5. You want to retrieve the 5 most recent orders for customer 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?
hard
A. client.query({ TableName: 'Orders', KeyConditionExpression: 'CustomerId = :cid', ExpressionAttributeValues: { ':cid': 'cust123' }, ScanIndexForward: false, Limit: 5 })
B. client.query({ TableName: 'Orders', KeyConditionExpression: 'CustomerId = :cid', ExpressionAttributeValues: { ':cid': 'cust123' }, ScanIndexForward: false })
C. client.query({ TableName: 'Orders', KeyConditionExpression: 'CustomerId = :cid', ExpressionAttributeValues: { ':cid': 'cust123' }, Limit: 5 })
D. client.query({ TableName: 'Orders', KeyConditionExpression: 'CustomerId = :cid', ExpressionAttributeValues: { ':cid': 'cust123' }, ScanIndexForward: true, Limit: 5 })

Solution

  1. Step 1: Set descending order for most recent first

    Use ScanIndexForward: false to get descending order by OrderDate.
  2. Step 2: Limit results to 5

    Use Limit: 5 to get only the top 5 recent orders.
  3. Final Answer:

    Query with ScanIndexForward false and Limit 5 -> Option A
  4. Quick Check:

    Descending + Limit 5 = ScanIndexForward false + Limit 5 [OK]
Hint: Use ScanIndexForward false with Limit 5 for recent 5 items [OK]
Common Mistakes:
  • Using ScanIndexForward true returns oldest first
  • Omitting Limit returns all items
  • Not combining descending order with limit