When to Use Single Table Design in DynamoDB: Key Guidance
single table design in DynamoDB when you want to store multiple entity types in one table to optimize query performance and reduce costs. It works best when your access patterns are well-defined and you want to minimize the number of queries by leveraging composite keys and indexes.How It Works
Single table design means putting different types of data into one DynamoDB table instead of many tables. Imagine a big filing cabinet where you keep all your documents sorted by labels instead of having many small cabinets. This helps you find related data quickly without opening multiple cabinets.
In DynamoDB, you use a combination of partition keys and sort keys to organize and retrieve different data types efficiently. By designing your keys carefully, you can fetch all needed information with fewer queries, which saves time and money.
Example
This example shows a DynamoDB table storing both User and Order items in one table using a composite key.
CREATE TABLE SingleTable ( PK STRING, SK STRING, Data JSON, PRIMARY KEY (PK, SK) ); -- Insert a User item INSERT INTO SingleTable (PK, SK, Data) VALUES ('USER#123', 'PROFILE#123', '{"name": "Alice", "email": "alice@example.com"}'); -- Insert an Order item for the same user INSERT INTO SingleTable (PK, SK, Data) VALUES ('USER#123', 'ORDER#456', '{"orderDate": "2024-06-01", "amount": 99.99}'); -- Query all items for user 123 SELECT * FROM SingleTable WHERE PK = 'USER#123';
When to Use
Use single table design when your application has multiple related data types that you often query together. It is ideal if you know your access patterns upfront and want to reduce the number of queries and improve performance.
Real-world examples include e-commerce apps where users, orders, and products are stored in one table, or social media apps where posts, comments, and user profiles share a table. This design reduces complexity and cost by avoiding multiple tables and joins.
Key Points
- Single table design stores multiple entity types in one DynamoDB table.
- It uses composite keys to organize and query data efficiently.
- Best when access patterns are well known and related data is queried together.
- Reduces query count, improves performance, and lowers cost.
- Requires careful planning of keys and indexes.