Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Reading and Writing Items

UpdateItem and Update Expressions

Change items in place with UpdateItem: SET, REMOVE, ADD and DELETE actions, if_not_exists and list_append, atomic counters, nested paths and upsert behavior.

PutItem replaces an item. Most of the time you want something smaller: change one attribute, add one to a counter, append an element to a list, remove a flag. UpdateItem does that in a single request, on the server, without reading the item first. It is also atomic for the item, which makes it the right tool for counters and other values that many clients change at once.

The shape of an UpdateItem call

Terminal
aws dynamodb update-item \
  --table-name Books \
  --key '{"Isbn": {"S": "978-1-0000-0001-1"}}' \
  --update-expression "SET Pages = :p, #s = :s REMOVE OldField" \
  --expression-attribute-names '{"#s": "Status"}' \
  --expression-attribute-values '{":p": {"N": "320"}, ":s": {"S": "in print"}}' \
  --return-values UPDATED_NEW

Three pieces:

  • Key: the full primary key of the item to change.
  • UpdateExpression: what to do, built from the four actions below.
  • ExpressionAttributeNames / ExpressionAttributeValues: placeholders. Names start with #, values with :. Values are always supplied through placeholders, never inlined in the expression.

ReturnValues can be NONE, ALL_OLD, UPDATED_OLD, ALL_NEW or UPDATED_NEW, which choose which attributes come back.

The four actions

An expression can contain each action at most once, in any order.

SET

Sets an attribute to a value, creating it if missing.

TEXT
SET Pages = :p
SET Price = Price + :delta            -- arithmetic on the current value
SET Views = if_not_exists(Views, :zero) + :one
SET Tags = list_append(Tags, :newTags)
SET Address.City = :city              -- nested map attribute
SET Lines[0].Qty = :q                 -- list element
  • if_not_exists(path, value) returns the attribute if it exists, otherwise the value. Use it to initialize counters safely.
  • list_append(a, b) joins two lists. Put the list that should come first first.
  • Arithmetic works only with + and -, on number operands.

REMOVE

Deletes attributes, or elements from a list.

TEXT
REMOVE OldField, Tags[1]

ADD

Adds to a number, or adds members to a set. It creates the attribute when absent (starting from zero or an empty set).

TEXT
ADD Views :one
ADD Tags :moreTags         -- :moreTags must be a set (SS)

ADD is considered legacy. AWS recommends SET with if_not_exists for numbers, but ADD is still the only way to add to a set, and many codebases use it.

DELETE

Removes members from a set (not from a list).

TEXT
DELETE Tags :removeTags

Upsert behavior

UpdateItem on a key that does not exist creates the item with the key attributes and the attributes you set. This makes it an "update or insert" operation, which is helpful for counters and surprising if you expected a failure. Add a condition expression (attribute_exists(Isbn)) when the item must already exist.

An engine that applies update expressions

The stand-in below implements enough of the update expression language to try the actions above: SET (with arithmetic, if_not_exists, list_append, nested map paths), REMOVE, ADD and DELETE. It is a simplified teaching model, not the real parser.

Python Stand-in: apply SET, REMOVE, ADD and DELETE

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.

Read the first output carefully: the item did not exist, yet it ended up with Isbn, Title and Views = 1. That is the upsert behavior. Run it a few times in your head or edit the numbers: each SET Views = Views + :one changes the value in place.

Atomic counters and lost updates

The big reason to use an update expression instead of read-modify-write is concurrency. Two clients that each read Views = 10, add one in their own code and write 11 produce 11, not 12: one increment is lost. SET Views = Views + :one is applied by DynamoDB to the latest stored value, so both increments count.

Python Stand-in: lost update vs atomic increment

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.

An atomic counter is not idempotent. If a request times out and you retry it, you might count twice. When exact counts matter, make the update conditional (for example on a request id stored in the item) or use a transaction, both covered in later lessons.

Returning values

ReturnValues Returns
NONE Nothing (default)
ALL_OLD The whole item before the update
UPDATED_OLD Only the changed attributes, before
ALL_NEW The whole item after the update
UPDATED_NEW Only the changed attributes, after

ALL_NEW after an increment is the standard way to read the new counter value without a second request.

Limits to remember

  • You cannot update a key attribute. To change a key, delete the item and write a new one (a transaction keeps them together).
  • Two actions cannot touch the same path in one expression.
  • A single expression is capped at 4 KB.
  • Lists can only be appended or edited by index; there is no "remove element by value".
  • Sets cannot be empty: deleting the last member removes the attribute.

Common mistakes

  • Putting values inline: SET Pages = 320 is invalid, use :p.
  • Updating a nested attribute whose parent does not exist. SET Address.City = :c fails if Address is not there, so create the map first or set the whole map.
  • Forgetting upsert: an update on a mistyped key quietly creates a new item.
  • Using ADD with a list: it supports only numbers and sets.
  • Retrying counters blindly, which double counts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does UpdateItem do when the key does not exist?

    UpdateItem is an upsert unless you add a condition such as attribute_exists on the key.
  2. 2. Which expression safely increments a counter that may not exist yet?

    if_not_exists supplies a starting value, so the arithmetic works even when Views is missing.
  3. 3. Which action removes members from a set?

    DELETE removes members from a set. REMOVE deletes an entire attribute or a list element.
  4. 4. Why is SET Views = Views + :one better than reading and writing in your code?

    The server applies the change to the current value, so concurrent increments are not lost. It is not idempotent, though.
  5. 5. Which attribute can UpdateItem not change?

    Primary key attributes are immutable. To change a key you delete and re-create the item.

Summary

  • UpdateItem modifies attributes in place and atomically, without reading the item first.
  • The four actions are SET, REMOVE, ADD and DELETE, with if_not_exists and list_append as helper functions.
  • Values and reserved names always go through :value and #name placeholders.
  • UpdateItem is an upsert; add a condition if the item must exist.
  • Atomic counters avoid lost updates but are not idempotent on retry.

Next: DeleteItem and ReturnValues