What is Sort Key in DynamoDB: Explanation and Examples
sort key is the second part of a composite primary key that helps organize and sort data within a partition. It allows multiple items to share the same partition key but be uniquely identified and sorted by the sort key.How It Works
Think of a DynamoDB table like a filing cabinet. The partition key is like the drawer where files are stored, and the sort key is like the order of files inside that drawer. It helps keep related items together and sorted.
When you use a sort key, DynamoDB can store multiple items with the same partition key but different sort keys. This lets you quickly find and organize data, like all orders from one customer sorted by date.
Example
This example shows a DynamoDB table with a partition key called UserID and a sort key called OrderDate. It stores multiple orders per user, sorted by date.
CREATE TABLE Orders ( UserID STRING, OrderDate STRING, ProductName STRING, PRIMARY KEY (UserID, OrderDate) ); -- Insert sample data INSERT INTO Orders (UserID, OrderDate, ProductName) VALUES ('user123', '2024-01-01', 'Book'); INSERT INTO Orders (UserID, OrderDate, ProductName) VALUES ('user123', '2024-02-15', 'Pen'); INSERT INTO Orders (UserID, OrderDate, ProductName) VALUES ('user456', '2024-01-10', 'Notebook'); -- Query orders for user123 sorted by OrderDate SELECT * FROM Orders WHERE UserID = 'user123' ORDER BY OrderDate;
When to Use
Use a sort key when you want to store multiple related items under the same partition key but keep them uniquely identifiable and sorted. This is useful for scenarios like:
- Storing all orders of a customer sorted by date
- Keeping track of user activity logs sorted by timestamp
- Grouping messages in a chat sorted by time sent
The sort key helps you efficiently query and retrieve data in a meaningful order.
Key Points
- The sort key is part of the composite primary key in DynamoDB.
- It allows multiple items to share the same partition key.
- Items are stored and retrieved sorted by the sort key.
- It enables efficient queries on related data grouped by partition key.