DynamoDB tables, keys and queries

Intermediate · 12 min

Items, partition and sort keys, Query versus Scan, conditional writes, consistency, item limits and designing from access patterns.

Before thisIAM users, groups, roles and policiesThe AWS CLI, SDKs and credential profiles

Be A Better Dev · 12 min

DynamoDB tables, keys and queries

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Be A Better DevReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • The partition key decides where an item lives. The sort key orders items that share a partition key and allows range queries.
  • Query reads one partition key's items efficiently. Scan reads the whole table and should be rare in a request path.
  • A filter expression runs after items are read, so it reduces what you receive, not what you pay.
  • Design keys from the list of access patterns, not from an entity diagram.
  • Choose a partition key with many values and even traffic. One partition serves about 3,000 read units and 1,000 write units per second.
  • Condition expressions make writes safe under concurrency: create only if absent, update only if unchanged.

A database that refuses to guess

A relational database lets you ask nearly anything and works out a plan. That flexibility is why its speed depends on data size, indexes and the planner’s mood. DynamoDB makes the opposite deal. You may only ask questions it can answer by going straight to the data, and in return a lookup stays fast whether the table holds a thousand items or a billion. It’s fully managed: no instances, no connections to pool, just HTTPS calls.

SQL versus NoSQL covers when that trade makes sense.

Tables, items, keys

A table holds items, each a set of attributes up to 400 KB in total. Items needn’t share attributes. Only the key is fixed.

The primary key is a partition key, optionally with a sort key. DynamoDB hashes the partition key to decide which physical partition stores the item. Items with the same partition key are kept together, ordered by sort key. Picture a filing cabinet: the partition key chooses the drawer, the sort key is the order of folders inside it. You can jump to a drawer and read a run of folders. You can’t ask “which drawer has a red folder” without opening all of them.

Query and Scan

GetItem fetches one item by its full key. Query reads items with one partition key, optionally narrowed by a sort key condition: equals, greater than, between, begins_with. Scan reads everything.

I put a customer profile and ten orders under the partition key CUST#42, with sort keys like ORDER#2026-03-01#3, and queried a local emulator:

all items for customer             Count=11 ScannedCount=11
newest 3 orders                    Count=3  ScannedCount=3
orders Q3                          Count=3  ScannedCount=3
query + filter total>80            Count=2  ScannedCount=10
scan + filter total>80             Count=2  ScannedCount=11

ScannedCount is what was read, Count is what came back. “Newest 3” is begins_with(SK, "ORDER#"), descending, limit 3. The date in the sort key does the work. A filter expression applies after reading, so the filtered rows were paid for anyway. A response holds at most 1 MB; follow LastEvaluatedKey for the rest.

Designing from questions

Write down every read and write first: get a customer, list their recent orders, fetch open orders. Then choose keys so each is a GetItem or Query. Putting different entity types under one partition key, as above, lets one request return a customer with their orders. That’s single-table design. It’s powerful when access patterns are stable and harder to read and change, so several simple tables are a fair choice too. New patterns are served by secondary indexes or by rewriting data.

Pick a partition key with many distinct values and spread-out traffic, such as a customer or order ID. Each partition is designed for up to 3,000 read units and 1,000 write units per second. DynamoDB can split busy partitions, but one very hot key still throttles. A date as partition key sends all of today’s writes to one place.

Reading your own writes

Reads are eventually consistent by default and may miss a write made a moment ago. Asking for ConsistentRead returns the latest committed value and costs twice as much. It works on tables and local indexes, not global ones.

Writing safely

There’s no lock to take. Attach a condition to the write instead:

t.put_item(Item={"PK": "CUST#42", "SK": "PROFILE", "name": "x"},
           ConditionExpression="attribute_not_exists(PK)")

Against the existing profile this raised ConditionalCheckFailedException. A version number with a condition on the old value gives optimistic locking. UpdateItem can increment counters atomically, and transactions group up to 100 actions all-or-nothing at twice the capacity cost.

Use expression placeholders for values, grant IAM access per table and index, turn on point-in-time recovery (up to 35 days) and deletion protection for anything you care about.

Model the data on paper first, then load realistic volumes and watch which keys get the traffic. Changing a key later means writing every item again into a new table.

About the video

The embed is Be A Better Dev’s 12-minute “AWS DynamoDB Schema Design: How to choose the right key” from 2019. Its chapters cover why the key matters, primary, partition and sort keys, and when to use which. It’s dated: it predates on-demand being the default and other later features, though how keys behave hasn’t changed. I judged it from chapters and description; its audio is flagged as original US English.

What was run: the items, queries and conditional write ran with boto3 against moto 5.1.22, so the counts show query semantics, not performance or billing. Limits come from the DynamoDB developer guide, checked in November 2026.

Check yourself

  1. 01A table is keyed on status with values open and closed. Why is that a poor partition key?

    There are only two values, so traffic and data pile onto very few partitions and hit per-partition limits while the rest of the capacity sits idle.

  2. 02A Query with a filter returns 2 items but consumed capacity for 10,000. Why?

    The key condition matched 10,000 items, which were all read before the filter removed most of them. The attribute you filter on belongs in a key or an index.

  3. 03You get a page of results with a LastEvaluatedKey. What must your code do?

    Query again, passing it as ExclusiveStartKey, until no LastEvaluatedKey is returned. A single response holds at most 1 MB.

  4. 04How do you keep two requests from creating the same username?

    Make the username the key and put it with a condition such as attribute_not_exists on the partition key. The second write fails.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark