0
0
DynamoDBquery~5 mins

Composite primary key in DynamoDB

Choose your learning style9 modes available
Introduction

A composite primary key helps you organize data by using two parts together to find each item uniquely.

When you want to store orders where each order has many items, and you want to find items by order and item ID.
When you have users and their posts, and you want to find posts by user and post date.
When you want to keep track of events by date and event type.
When you want to group related data and still find each piece easily.
When you want to avoid duplicate entries that share one key but differ in another.
Syntax
DynamoDB
TableName:
  PartitionKey: <PartitionKeyName> (Type: String or Number)
  SortKey: <SortKeyName> (Type: String or Number)

Example:
  PartitionKey: UserID (String)
  SortKey: OrderID (String)

The PartitionKey is like the main folder where data is stored.

The SortKey helps sort and find items inside that folder.

Examples
This setup lets you find invoices for each customer easily.
DynamoDB
PartitionKey: CustomerID (String)
SortKey: InvoiceID (String)
This helps group products by category and find each product by its ID.
DynamoDB
PartitionKey: ProductCategory (String)
SortKey: ProductID (Number)
This lets you find user actions sorted by time.
DynamoDB
PartitionKey: UserID (String)
SortKey: Timestamp (Number)
Sample Program

This example creates a table with a composite primary key using OrderID and ItemID. It adds two items to the same order and then queries all items for that order.

DynamoDB
CreateTable {
  TableName: "Orders",
  KeySchema: [
    { AttributeName: "OrderID", KeyType: "HASH" },  # Partition Key
    { AttributeName: "ItemID", KeyType: "RANGE" }   # Sort Key
  ],
  AttributeDefinitions: [
    { AttributeName: "OrderID", AttributeType: "S" },
    { AttributeName: "ItemID", AttributeType: "S" }
  ],
  ProvisionedThroughput: {
    ReadCapacityUnits: 5,
    WriteCapacityUnits: 5
  }
}

# Insert items
PutItem TableName="Orders" Item={"OrderID": "123", "ItemID": "A1", "Product": "Book", "Quantity": 2}
PutItem TableName="Orders" Item={"OrderID": "123", "ItemID": "B2", "Product": "Pen", "Quantity": 5}

# Query items for OrderID = "123"
Query TableName="Orders" KeyConditionExpression="OrderID = :orderId" ExpressionAttributeValues={":orderId": {"S": "123"}}
OutputSuccess
Important Notes

Composite primary keys let you store multiple related items under one main key.

PartitionKey decides the partition where data is stored; SortKey orders items inside that partition.

Using composite keys helps avoid duplicates and improves query speed for grouped data.

Summary

A composite primary key uses two attributes: PartitionKey and SortKey.

It helps organize and find related data easily.

Use it when you want to group items and still keep each item unique.