Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Reading and Writing Items

DeleteItem and ReturnValues

Delete items with DeleteItem, understand why deletes are idempotent, get the old item back with ReturnValues, delete a whole collection safely, and use soft deletes.

Deleting looks like the simplest operation, and in DynamoDB it nearly is: DeleteItem removes one item by its full primary key. The interesting parts are the questions around it. What happens when the item is not there? How do you get the deleted data back for an undo? How do you delete everything under a partition key, when there is no DELETE ... WHERE? This lesson answers those and shows when not to delete at all.

DeleteItem basics

Terminal
aws dynamodb delete-item \
  --table-name Orders \
  --key '{"PK": {"S": "CUSTOMER#amina"}, "SK": {"S": "ORDER#5001"}}' \
  --return-values ALL_OLD
  • The full primary key is required, including the sort key when the table has one.
  • If the item does not exist, the call succeeds and does nothing. Deletes are idempotent: repeating one is safe, which is convenient for retries.
  • ReturnValues accepts NONE (default) or ALL_OLD. With ALL_OLD the response contains the item as it was, or nothing if there was no such item. That is how you tell "deleted something" from "was already gone".
  • A delete consumes write capacity based on the size of the item that was removed (rounded up to 1 KB), not on the key.

The Python SDK form:

Python
response = table.delete_item(
    Key={"PK": "CUSTOMER#amina", "SK": "ORDER#5001"},
    ReturnValues="ALL_OLD",
)
deleted = response.get("Attributes")     # None when nothing was there

A model of delete semantics

Python Stand-in: idempotent delete with ALL_OLD

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second call prints an empty result and no exception. If your logic needs to know whether something was actually removed, ask for ALL_OLD and check whether Attributes is present, or use a condition expression.

Conditional deletes

Because a plain delete always succeeds, protect important data with a condition. The delete then fails with ConditionalCheckFailedException when the condition is false. The condition expressions lesson covers the full syntax, but the typical examples are:

Terminal
# Only delete orders that were never paid
aws dynamodb delete-item --table-name Orders \
  --key '{"PK": {"S": "CUSTOMER#amina"}, "SK": {"S": "ORDER#5002"}}' \
  --condition-expression "#s = :open" \
  --expression-attribute-names '{"#s": "Status"}' \
  --expression-attribute-values '{":open": {"S": "open"}}'

Conditions also solve the "is it still the version I saw?" question: delete only if Version = :seen, so you do not remove an item someone else just updated (optimistic locking).

Deleting many items

There is no bulk delete by condition. To delete everything under a partition key you must:

  1. Query the keys of the items (project only the key attributes to save transfer),
  2. send the keys to BatchWriteItem in groups of 25, or run them inside transactions if they must succeed together,
  3. repeat while the query has more pages.
flowchart LR
    Q["Query partition key<br/>project keys only"] --> B["Chunk into 25"]
    B --> W["BatchWriteItem<br/>DeleteRequest x 25"]
    W --> U{"Unprocessed items?"}
    U -->|"yes"| W
    U -->|"no"| N{"More pages?"}
    N -->|"yes"| Q
    N -->|"no"| D["Done"]

The next stand-in models that loop on an in-memory table, with a chunk size of 25 as in the real batch limit.

Python Stand-in: delete a whole partition in chunks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Deleting 60 items took three batch calls. This is also why you should not use a large collection under one key if you often need to wipe it: for a table whose entire contents can be replaced, deleting the table and re-creating it is far cheaper than deleting item by item.

For data that expires on a schedule (sessions, one-time codes, caches), do not run your own delete job. Set a TTL attribute and DynamoDB removes the items for free in the background. See the Streams, TTL and Integrations chapter.

Soft delete

Often the right answer to "delete" is "mark as deleted". A soft delete keeps the item, sets a flag or timestamp and lets you restore it, audit it, or purge it later.

  • Set DeletedAt (or Status = "deleted") with UpdateItem.
  • Keep deleted items out of normal queries, either with a filter, a sparse index that only contains active items, or by moving them to a different sort key prefix.
  • Add a TTL to the soft-deleted item so it disappears after the retention period.
Python Stand-in: soft delete with a retention timestamp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Cascading cleanup

DynamoDB has no foreign keys, so deleting a parent does not touch its children. When a customer closes an account, you must also delete (or archive) their orders, sessions and so on. Common approaches: do it in the same request with a transaction (for small sets), run a background worker, or react to the delete through DynamoDB Streams and a Lambda function. Plan this early because orphans accumulate silently.

Common mistakes

  • Expecting an error for a missing item. Deletes succeed either way, so check ALL_OLD or add a condition.
  • Omitting the sort key. The request fails because the key is incomplete.
  • Looping delete-by-delete for big collections. Use BatchWriteItem or TTL, and project keys only.
  • Deleting without a safety condition on data that matters. Add a condition, or use a soft delete.
  • Forgetting dependent items such as lookup items and index entries that your design duplicated.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does DeleteItem do when the item does not exist?

    Deleting a missing item is not an error, which makes DeleteItem idempotent and safe to retry.
  2. 2. How can you tell that a delete actually removed something?

    ALL_OLD returns the removed item. If no Attributes come back, nothing was deleted.
  3. 3. How do you delete all items that share a partition key?

    There is no delete-by-condition. You find the keys with Query and delete them, in batches of up to 25.
  4. 4. What is the cheapest way to expire sessions after a day?

    With TTL enabled, DynamoDB deletes expired items in the background at no extra write cost.

Summary

  • DeleteItem needs the full key and succeeds even if the item is missing.
  • ReturnValues=ALL_OLD returns what was removed; conditions guard against deleting the wrong thing.
  • Bulk deletes mean Query for keys, then BatchWriteItem in groups of 25.
  • Soft deletes and TTL are often better than hard deletes.
  • Cascading cleanup is your responsibility; there are no foreign keys.

Next: Condition Expressions