Bird
Raised Fist0
DynamoDBquery~20 mins

Composite primary key 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
🎖️
Composite Key Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
Querying with Composite Primary Key in DynamoDB

Given a DynamoDB table with a composite primary key consisting of PartitionKey and SortKey, what will be the output of the following query?

Query: Get all items where PartitionKey = 'User#123' and SortKey begins with 'Order#'
DynamoDB
Table: Orders
PartitionKey: User#123
SortKey: Order#001, Order#002, Profile#001

Query: PartitionKey = 'User#123' AND begins_with(SortKey, 'Order#')
AReturns all items with PartitionKey 'User#123' including 'Profile#001'
BReturns items with SortKey 'Order#001' and 'Order#002' only
CReturns no items because begins_with is not valid in DynamoDB
DReturns items with SortKey 'Profile#001' only
Attempts:
2 left
💡 Hint

Think about how the sort key condition works with begins_with in DynamoDB queries.

🧠 Conceptual
intermediate
1:30remaining
Understanding Composite Primary Key Components

Which two components make up a composite primary key in DynamoDB?

APartition Key and Sort Key
BPartition Key and Global Secondary Index
CHash Key and Range Key
DPrimary Key and Secondary Key
Attempts:
2 left
💡 Hint

One key decides the partition, the other orders items within that partition.

📝 Syntax
advanced
2:00remaining
Correct Syntax for Querying Composite Primary Key

Which of the following DynamoDB query expressions correctly uses the composite primary key to get all items with PartitionKey 'User#456' and SortKey between 'Order#100' and 'Order#200'?

AKeyConditionExpression: 'PartitionKey = :pk AND SortKey IN (:start, :end)'
BKeyConditionExpression: 'PartitionKey = :pk OR SortKey BETWEEN :start AND :end'
CKeyConditionExpression: 'PartitionKey = :pk AND SortKey BETWEEN :start AND :end'
DKeyConditionExpression: 'PartitionKey = :pk AND SortKey > :start AND SortKey < :end'
Attempts:
2 left
💡 Hint

Remember the correct operator to specify a range in DynamoDB queries.

🔧 Debug
advanced
1:30remaining
Identify the Error in Composite Key Query

Consider this DynamoDB query snippet:

KeyConditionExpression: 'PartitionKey = :pk AND SortKey = :sk'
ExpressionAttributeValues: { ':pk': 'User#789' }

What error will this cause?

ANo error, query runs successfully
BSyntax error: Invalid KeyConditionExpression format
CQuery returns no results because ':sk' is undefined
DRuntime error: Missing ExpressionAttributeValue for ':sk'
Attempts:
2 left
💡 Hint

Check if all placeholders in the expression have matching values.

optimization
expert
2:30remaining
Optimizing Access Patterns with Composite Primary Keys

You have a DynamoDB table with composite primary key (UserID, Timestamp). You want to efficiently retrieve the latest 5 records for a user. Which approach is best?

AQuery with PartitionKey = UserID and SortKey in descending order, limit 5
BScan the entire table and filter by UserID, then sort by Timestamp
CUse a Global Secondary Index on Timestamp only and filter by UserID
DQuery with PartitionKey = UserID and SortKey in ascending order, limit 5
Attempts:
2 left
💡 Hint

Think about how DynamoDB stores items sorted by sort key within a partition.

Practice

(1/5)
1.

What is a composite primary key in DynamoDB?

easy
A. A key that allows duplicate items
B. A key made of only one attribute
C. A key made of two attributes: PartitionKey and SortKey
D. A key used only for indexing

Solution

  1. Step 1: Understand primary key types in DynamoDB

    DynamoDB supports simple primary keys (one attribute) and composite primary keys (two attributes).
  2. Step 2: Identify composite primary key components

    A composite primary key consists of a PartitionKey and a SortKey to uniquely identify items.
  3. Final Answer:

    A key made of two attributes: PartitionKey and SortKey -> Option C
  4. Quick Check:

    Composite primary key = PartitionKey + SortKey [OK]
Hint: Composite key always has PartitionKey and SortKey [OK]
Common Mistakes:
  • Thinking composite key has only one attribute
  • Confusing composite key with secondary indexes
  • Believing composite key allows duplicates
2.

Which of the following is the correct way to define a composite primary key in DynamoDB table creation?

{
  "TableName": "Orders",
  "KeySchema": [
    {"AttributeName": "CustomerId", "KeyType": "HASH"},
    {"AttributeName": "OrderDate", "KeyType": "RANGE"}
  ]
}
easy
A. Use KeyType RANGE for both attributes
B. Use KeyType RANGE for PartitionKey and HASH for SortKey
C. Use KeyType HASH for both attributes
D. Use KeyType HASH for PartitionKey and RANGE for SortKey

Solution

  1. Step 1: Recall KeyType meanings

    In DynamoDB, HASH means PartitionKey and RANGE means SortKey.
  2. Step 2: Match KeyType to attributes

    PartitionKey must be HASH and SortKey must be RANGE for composite keys.
  3. Final Answer:

    Use KeyType HASH for PartitionKey and RANGE for SortKey -> Option D
  4. Quick Check:

    PartitionKey=HASH, SortKey=RANGE [OK]
Hint: HASH = PartitionKey, RANGE = SortKey in KeySchema [OK]
Common Mistakes:
  • Swapping HASH and RANGE roles
  • Using same KeyType for both keys
  • Confusing attribute names with KeyType
3.

Given a DynamoDB table with composite primary key (UserId as PartitionKey, Timestamp as SortKey), what will this query return?

{
  "TableName": "UserActivity",
  "KeyConditionExpression": "UserId = :uid and Timestamp > :time",
  "ExpressionAttributeValues": {
    ":uid": {"S": "user123"},
    ":time": {"N": "1609459200"}
  }
}
medium
A. All activities of user123 with Timestamp greater than 1609459200
B. All activities of all users with Timestamp greater than 1609459200
C. All activities of user123 regardless of Timestamp
D. Syntax error due to missing SortKey in query

Solution

  1. Step 1: Understand KeyConditionExpression

    It filters items by PartitionKey equality and SortKey condition.
  2. Step 2: Analyze the query conditions

    UserId = :uid restricts to user123; Timestamp > :time filters timestamps after 1609459200.
  3. Final Answer:

    All activities of user123 with Timestamp greater than 1609459200 -> Option A
  4. Quick Check:

    PartitionKey + SortKey condition filters items [OK]
Hint: PartitionKey = value AND SortKey condition filters items [OK]
Common Mistakes:
  • Thinking query returns all users' data
  • Ignoring SortKey condition
  • Assuming syntax error without SortKey equality
4.

What is wrong with this DynamoDB query using composite primary key (UserId as PartitionKey, OrderId as SortKey)?

{
  "TableName": "Orders",
  "KeyConditionExpression": "OrderId = :oid",
  "ExpressionAttributeValues": {
    ":oid": {"S": "order789"}
  }
}
medium
A. PartitionKey UserId is missing in KeyConditionExpression
B. SortKey OrderId cannot be used in KeyConditionExpression
C. ExpressionAttributeValues syntax is incorrect
D. TableName is invalid

Solution

  1. Step 1: Recall query requirements for composite keys

    Queries must specify PartitionKey equality in KeyConditionExpression.
  2. Step 2: Check the given query

    Only SortKey OrderId is used; PartitionKey UserId is missing, causing error.
  3. Final Answer:

    PartitionKey UserId is missing in KeyConditionExpression -> Option A
  4. Quick Check:

    PartitionKey must be in query condition [OK]
Hint: Always include PartitionKey equality in query [OK]
Common Mistakes:
  • Using only SortKey in query condition
  • Assuming SortKey alone can identify items
  • Ignoring required PartitionKey in queries
5.

You want to store blog posts in DynamoDB. Each post has a AuthorId and a PostDate. You want to quickly find all posts by an author sorted by date. Which composite primary key design is best?

hard
A. PartitionKey: PostDate, SortKey: AuthorId
B. PartitionKey: AuthorId, SortKey: PostDate
C. PartitionKey: AuthorId only, no SortKey
D. PartitionKey: PostDate only, no SortKey

Solution

  1. Step 1: Identify query pattern

    You want to find all posts by an author, sorted by date.
  2. Step 2: Choose PartitionKey and SortKey accordingly

    PartitionKey should be AuthorId to group posts by author; SortKey should be PostDate to sort posts by date.
  3. Final Answer:

    PartitionKey: AuthorId, SortKey: PostDate -> Option B
  4. Quick Check:

    Group by author, sort by date = AuthorId + PostDate [OK]
Hint: PartitionKey groups, SortKey sorts related items [OK]
Common Mistakes:
  • Swapping PartitionKey and SortKey roles
  • Using only one key losing sorting ability
  • Choosing SortKey that doesn't support query pattern