Lesson 5 of 10 Amazon DynamoDB

Reading and Writing Items with Queries, Batches, Conditions and Transactions

This lesson explains the DynamoDB operations for reading and writing data: single-item operations, batch operations, queries and scans, and the conditional and transactional writes that protect data integrity.

Learning outcomes

After completing this lesson, you will be able to:

  • Distinguish Query from Scan and explain why a Scan is less efficient.
  • Describe how update expressions and atomic counters change attributes without rewriting an item.
  • Explain why batch operations can return unprocessed items that the application must retry.
  • Explain how conditional writes implement optimistic locking and when to use transactions.

Query vs Scan

Query and Scan both return multiple items, but they read data in fundamentally different ways.

A Query requires an exact value for the partition key and can add a condition on the sort key, such as begins_with, between or a comparison. DynamoDB goes directly to the item collection for that key and reads only the matching range, so the cost depends on the size of the result, not of the table. Queries can run against the table or any secondary index.

A Scan reads every item in the table or index and is charged for all of them, however few it returns. On a large table it is slow, consumes a large share of capacity and can throttle other requests. A parallel scan divides the table into segments that several workers read at once, which finishes sooner but consumes capacity even faster. Scans suit small tables, one-off exports and maintenance jobs; a frequent need to scan usually means the access pattern needs a key or an index.

The following table summarises the differences.

Query
ReadsOnly items with one partition key, optionally narrowed by the sort key
CostEfficient
Speed-upBetter keys or an index
Scan
ReadsEvery item in the table
CostExpensive on large tables
Speed-upParallel scan splits the work into segments, but consumes capacity faster

The following list describes further parameters that affect the results and cost of a read.

  • ProjectionExpression returns fewer attributes.
  • FilterExpression removes items after they are read, so it does not reduce the capacity consumed.
  • Each response holds at most 1 MB. Continue by passing LastEvaluatedKey back as ExclusiveStartKey.

Example. Paginating a query until no LastEvaluatedKey remains:

from boto3.dynamodb.conditions import Key

kwargs = {"KeyConditionExpression": Key("PK").eq("CUSTOMER#42") & Key("SK").begins_with("ORDER#")}
while True:
    page = table.query(**kwargs)
    handle(page["Items"])
    if "LastEvaluatedKey" not in page:
        break
    kwargs["ExclusiveStartKey"] = page["LastEvaluatedKey"]

The following diagram shows which items each operation reads from the same table.

Query compared with Scan. A Query goes directly to one partition key's item collection and reads only the matching sort-key range, so its cost follows the size of the result. A Scan reads and charges every item in the table; a FilterExpression removes items only after they have been read.
Shaded cells are the items read; teal cells are the items returned. A Scan pays for every amber cell, even though its filter returns only two items.
True or false

Query and Scan

Exam skills 1.3.4 · 4.3.2

Check three facts about how Query and Scan read and charge.

Log in to try this activity Interactive activities are free with an account.

Updating items

UpdateItem changes specific attributes without rewriting the whole item, using update expressions with SET, REMOVE, ADD and DELETE.

  • Atomic counters: SET views = views + :inc increments safely without reading first.
  • ReturnValues: returns the item as it was before or after the update.
  • Placeholders: expression attribute names such as #s are required for reserved words like status or name; expression attribute values such as :val pass values safely.

Batch operations

BatchGetItem reads up to 100 items and BatchWriteItem writes or deletes up to 25. Under throttling, either can return UnprocessedKeys or UnprocessedItems, which your code must retry with backoff. The resource API's batch_writer() does this for you:

with table.batch_writer() as batch:
    for order in orders:
        batch.put_item(Item=order)

Conditional writes and transactions

A conditional write succeeds only if its ConditionExpression holds. This is how optimistic locking works: each item carries a version number, and an update succeeds only if the version is unchanged.

try:
    table.update_item(
        Key={"PK": "ORDER#9017"},
        UpdateExpression="SET #s = :new, version = version + :one",
        ConditionExpression="version = :expected",
        ExpressionAttributeNames={"#s": "status"},
        ExpressionAttributeValues={":new": "SHIPPED", ":one": 1, ":expected": 4},
    )
except table.meta.client.exceptions.ConditionalCheckFailedException:
    reload_and_retry()   # someone else changed the item first

For changes that must succeed or fail together, TransactWriteItems and TransactGetItems provide ACID transactions across up to 100 items.

The following diagram shows two writers updating the same item with the optimistic locking code above.

Optimistic locking with a version attribute. Two writers read version 4 of ORDER#9017. Writer A updates on condition that the version is 4, which succeeds and sets version 5. Writer B's update with the same condition fails with ConditionalCheckFailedException, so it reloads the item and retries.
The condition makes the second update fail instead of silently overwriting the first, so no change is lost.
Scenario questions

Read and write correctly

Exam skills 1.1.5 · 1.3.4

Practise the details of queries, batches and conditional writes.

Log in to try this activity Interactive activities are free with an account.
Worked example

Preventing a lost update

Two support agents open the same ticket. Both change its status and save; the second save silently overwrites the first. Optimistic locking with a condition expression prevents this:

StepAgent AAgent B
ReadItem version 3Item version 3
WriteUpdate with condition version = 3, set version 4: succeeds
WriteUpdate with condition version = 3: fails with ConditionalCheckFailedException
RecoverRe-read version 4, re-apply the change, write version 5

Separately, a nightly report that used Scan on a 50 GB table consumed most of the table's capacity. Replacing it with a Query on a GSI keyed by date reads only the items needed, and an export to S3 would remove the load entirely.

Check yourself

When is a Scan acceptable instead of a Query?

Show answer

When the job really needs every item, such as an occasional export or a small table. A Scan reads the whole table and consumes capacity for every item read, so it should not serve routine requests that a key or index can answer.

Exam Tips

Remember for the exam

  • "Prevent concurrent updates from overwriting each other" means conditional writes (optimistic locking).
  • Filter expressions do not reduce read capacity consumed; better keys or an index do.
  • Results that stop at 1 MB must be paginated with LastEvaluatedKey.
  • To increment a counter safely, use UpdateItem with SET counter = counter + :inc.
  • When an attribute name is a reserved word, use an expression attribute name such as #s.