0
0
DynamodbHow-ToBeginner ยท 3 min read

How to Use ADD in Update Expression in DynamoDB

In DynamoDB, use the ADD keyword in an update expression to increment numeric attributes or add elements to set attributes. The syntax is ADD attributeName :value, where :value is the amount or set elements to add. This operation updates the item atomically without replacing the entire attribute.
๐Ÿ“

Syntax

The ADD keyword in DynamoDB update expressions lets you add a number to a numeric attribute or add elements to a set attribute. It does not replace the attribute but increments or extends it.

Syntax pattern:

ADD attributeName :value

Where:

  • attributeName: The name of the attribute to update.
  • :value: A placeholder for the value to add (number or set).
plaintext
UpdateExpression = "ADD attributeName :value"
ExpressionAttributeValues = {":value": valueToAdd}
๐Ÿ’ป

Example

This example shows how to increment a numeric attribute counter by 1 using the ADD keyword in an update expression.

python
import boto3

# Create DynamoDB client
client = boto3.client('dynamodb')

# Update item by adding 1 to 'counter' attribute
response = client.update_item(
    TableName='MyTable',
    Key={'id': {'S': '123'}},
    UpdateExpression='ADD counter :inc',
    ExpressionAttributeValues={':inc': {'N': '1'}},
    ReturnValues='UPDATED_NEW'
)

print(response['Attributes'])
Output
{"counter": {"N": "6"}}
โš ๏ธ

Common Pitfalls

  • Using ADD on a non-numeric or non-set attribute causes an error.
  • Trying to add a number to a string attribute will fail.
  • When adding to a set, the value must be a set type (e.g., SS for string set).
  • For incrementing, ensure the attribute exists or DynamoDB will create it with the added value.
plaintext
Wrong usage example:
UpdateExpression = "ADD name :val"
ExpressionAttributeValues = {":val": {"N": "1"}}  # 'name' is a string attribute

Correct usage example:
UpdateExpression = "ADD counter :val"
ExpressionAttributeValues = {":val": {"N": "1"}}  # 'counter' is numeric
๐Ÿ“Š

Quick Reference

Use CaseAttribute TypeValue TypeEffect
Increment numberNumberNumberAdds the number to the attribute value
Add to setSet (String, Number, Binary)SetAdds elements to the set attribute
Non-existing attributeNumber or SetNumber or SetCreates attribute with the added value
โœ…

Key Takeaways

Use ADD in update expressions to increment numbers or add elements to sets atomically.
The value added must match the attribute type: number for numeric attributes, set for set attributes.
ADD does not replace the attribute but updates it by adding the given value.
Using ADD on incompatible attribute types causes errors.
If the attribute does not exist, ADD creates it with the added value.