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
ADDon 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.,
SSfor 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 Case | Attribute Type | Value Type | Effect |
|---|---|---|---|
| Increment number | Number | Number | Adds the number to the attribute value |
| Add to set | Set (String, Number, Binary) | Set | Adds elements to the set attribute |
| Non-existing attribute | Number or Set | Number or Set | Creates 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.