Bird
Raised Fist0
DynamoDBquery~20 mins

Sort key purpose and usage 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
🎖️
Sort Key Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Purpose of a Sort Key in DynamoDB
What is the main purpose of a sort key in a DynamoDB table?
ATo allow multiple items with the same partition key and sort them within that partition
BTo uniquely identify each item in the table by itself
CTo encrypt the data stored in the table
DTo define the read capacity units for the table
Attempts:
2 left
💡 Hint
Think about how DynamoDB organizes items when they share the same partition key.
query_result
intermediate
2:00remaining
Query Result Using Sort Key Condition
Given a DynamoDB table with partition key 'UserID' and sort key 'Timestamp', which query will return all items for UserID '123' with Timestamp greater than 1000?
DynamoDB
Query(
  TableName='UserActivity',
  KeyConditionExpression='UserID = :uid AND Timestamp > :ts',
  ExpressionAttributeValues={':uid': '123', ':ts': 1000}
)
AReturns all items with UserID '123' and Timestamp greater than 1000
BReturns all items with UserID '123' regardless of Timestamp
CReturns all items with Timestamp greater than 1000 regardless of UserID
DReturns no items because the query syntax is invalid
Attempts:
2 left
💡 Hint
Check how the KeyConditionExpression uses both partition and sort keys.
📝 Syntax
advanced
2:30remaining
Correct Syntax for Defining Sort Key in Table Creation
Which option shows the correct syntax to define a sort key named 'OrderDate' when creating a DynamoDB table?
DynamoDB
CreateTable(
  TableName='Orders',
  KeySchema=[
    {'AttributeName': 'CustomerID', 'KeyType': 'HASH'},
    {'AttributeName': 'OrderDate', 'KeyType': 'RANGE'}
  ],
  AttributeDefinitions=[
    {'AttributeName': 'CustomerID', 'AttributeType': 'S'},
    {'AttributeName': 'OrderDate', 'AttributeType': 'S'}
  ],
  ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
)
AKeySchema includes CustomerID as RANGE and OrderDate as HASH; AttributeDefinitions define both as type String
BKeySchema includes OrderDate as HASH and CustomerID as RANGE; AttributeDefinitions define both as type Number
CKeySchema includes only CustomerID as HASH; AttributeDefinitions define OrderDate as type String
DKeySchema includes CustomerID as HASH and OrderDate as RANGE; AttributeDefinitions define both as type String
Attempts:
2 left
💡 Hint
Remember HASH is partition key and RANGE is sort key.
optimization
advanced
2:30remaining
Optimizing Queries Using Sort Key
You want to efficiently retrieve all orders for a customer placed within a specific date range. Which approach best uses the sort key to optimize this query?
AUse a Query operation with only the partition key CustomerID and filter dates after fetching
BUse a Scan operation filtering by CustomerID and date range
CUse a Query operation with partition key as CustomerID and a sort key condition between the start and end dates
DUse a GetItem operation with CustomerID and date range as keys
Attempts:
2 left
💡 Hint
Consider how Query and Scan differ and how sort key conditions help.
🔧 Debug
expert
3:00remaining
Debugging a Query with Sort Key Condition Error
A developer runs this query on a DynamoDB table with partition key 'UserID' and sort key 'CreatedAt': Query( TableName='Users', KeyConditionExpression='UserID = :uid AND CreatedAt = :date', ExpressionAttributeValues={':uid': 'u123', ':date': '2023-01-01'} ) What error will this query produce?
AResourceNotFoundException because table 'Users' does not exist
BValidationException due to missing ExpressionAttributeValue for ':date'
CNo error; query returns items with UserID 'u123' and any CreatedAt
DSyntaxError due to incorrect KeyConditionExpression format
Attempts:
2 left
💡 Hint
Check if all placeholders in the expression have matching values.

Practice

(1/5)
1. What is the main purpose of a sort key in a DynamoDB table?
easy
A. To store large binary data efficiently
B. To uniquely identify each item across all partitions
C. To organize and order items within the same partition key
D. To encrypt data at rest automatically

Solution

  1. Step 1: Understand partition and sort keys roles

    The partition key groups items, and the sort key orders items within that group.
  2. Step 2: Identify the sort key's purpose

    The sort key organizes related items so they can be retrieved in order and filtered efficiently.
  3. Final Answer:

    To organize and order items within the same partition key -> Option C
  4. Quick Check:

    Sort key = Organize items in partition [OK]
Hint: Sort key orders items inside a partition [OK]
Common Mistakes:
  • Confusing sort key with partition key uniqueness
  • Thinking sort key encrypts data
  • Assuming sort key stores large binary data
2. Which of the following is the correct way to define a DynamoDB table with a partition key named UserID and a sort key named Timestamp using AWS CLI?
easy
A. aws dynamodb create-table --table-name MyTable --attribute-definitions AttributeName=Timestamp,AttributeType=N --key-schema AttributeName=Timestamp,KeyType=HASH --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5
B. aws dynamodb create-table --table-name MyTable --attribute-definitions AttributeName=UserID,AttributeType=S AttributeName=Timestamp,AttributeType=N --key-schema AttributeName=UserID,KeyType=HASH AttributeName=Timestamp,KeyType=HASH --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5
C. aws dynamodb create-table --table-name MyTable --attribute-definitions AttributeName=UserID,AttributeType=S --key-schema AttributeName=UserID,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5
D. aws dynamodb create-table --table-name MyTable --attribute-definitions AttributeName=UserID,AttributeType=S AttributeName=Timestamp,AttributeType=N --key-schema AttributeName=UserID,KeyType=HASH AttributeName=Timestamp,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5

Solution

  1. Step 1: Check attribute definitions and key schema

    Partition key must have KeyType=HASH and sort key must have KeyType=RANGE.
  2. Step 2: Verify aws dynamodb create-table --table-name MyTable --attribute-definitions AttributeName=UserID,AttributeType=S AttributeName=Timestamp,AttributeType=N --key-schema AttributeName=UserID,KeyType=HASH AttributeName=Timestamp,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 matches correct key types

    aws dynamodb create-table --table-name MyTable --attribute-definitions AttributeName=UserID,AttributeType=S AttributeName=Timestamp,AttributeType=N --key-schema AttributeName=UserID,KeyType=HASH AttributeName=Timestamp,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 uses UserID as HASH and Timestamp as RANGE, which is correct.
  3. Final Answer:

    aws dynamodb create-table --table-name MyTable --attribute-definitions AttributeName=UserID,AttributeType=S AttributeName=Timestamp,AttributeType=N --key-schema AttributeName=UserID,KeyType=HASH AttributeName=Timestamp,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 -> Option D
  4. Quick Check:

    Partition=HASH, Sort=RANGE in CLI [OK]
Hint: Sort key uses KeyType=RANGE in key schema [OK]
Common Mistakes:
  • Using KeyType=HASH for both keys
  • Missing sort key in key schema
  • Defining only partition key without sort key
3. Given a DynamoDB table with partition key UserID and sort key OrderDate, what will the following query return?
aws dynamodb query --table-name Orders --key-condition-expression "UserID = :uid AND OrderDate > :date" --expression-attribute-values '{":uid":{"S":"user123"}, ":date":{"S":"2023-01-01"}}'
medium
A. All orders for user123 with OrderDate after 2023-01-01, sorted by OrderDate
B. All orders for user123 regardless of OrderDate
C. All orders with OrderDate after 2023-01-01 for all users
D. Syntax error due to missing partition key in condition

Solution

  1. Step 1: Analyze the key condition expression

    The query filters items where UserID equals 'user123' and OrderDate is greater than '2023-01-01'.
  2. Step 2: Understand query behavior with partition and sort keys

    Query returns items for one partition key, ordered by sort key, filtered by the condition on sort key.
  3. Final Answer:

    All orders for user123 with OrderDate after 2023-01-01, sorted by OrderDate -> Option A
  4. Quick Check:

    Query filters by partition and sort key conditions [OK]
Hint: Query needs partition key equality and sort key condition [OK]
Common Mistakes:
  • Expecting query to filter across all partitions
  • Ignoring sort key condition in query
  • Confusing query with scan operation
4. You wrote this DynamoDB query but it returns an error:
aws dynamodb query --table-name Sales --key-condition-expression "OrderID > :oid" --expression-attribute-values '{":oid":{"S":"1000"}}'

What is the likely cause?
medium
A. Using > operator on partition key is allowed
B. Missing partition key equality condition in key-condition-expression
C. Incorrect data type for expression attribute value
D. Missing sort key in attribute definitions

Solution

  1. Step 1: Recall query key condition requirements

    DynamoDB query requires partition key equality condition in key-condition-expression.
  2. Step 2: Identify error cause

    Query uses only 'OrderID > :oid' without partition key equality, causing error.
  3. Final Answer:

    Missing partition key equality condition in key-condition-expression -> Option B
  4. Quick Check:

    Partition key equality is mandatory in query [OK]
Hint: Query must have partition key equality condition [OK]
Common Mistakes:
  • Using range operators on partition key
  • Omitting partition key in query condition
  • Confusing query with scan operation
5. You want to model a one-to-many relationship where each CustomerID can have multiple Invoices sorted by InvoiceDate. Which DynamoDB table design best uses the sort key to achieve this?
hard
A. Partition key: CustomerID, Sort key: InvoiceDate
B. Partition key: InvoiceDate, Sort key: CustomerID
C. Partition key: CustomerID only, no sort key
D. Partition key: InvoiceID, Sort key: InvoiceDate

Solution

  1. Step 1: Understand one-to-many modeling in DynamoDB

    Use partition key for the 'one' side and sort key to order the 'many' items.
  2. Step 2: Apply to CustomerID and Invoices

    CustomerID as partition key groups invoices; InvoiceDate as sort key orders them.
  3. Final Answer:

    Partition key: CustomerID, Sort key: InvoiceDate -> Option A
  4. Quick Check:

    Sort key models one-to-many order [OK]
Hint: Partition key = one side, sort key = many side order [OK]
Common Mistakes:
  • Swapping partition and sort keys
  • Not using sort key for ordering
  • Using only partition key losing order info