How to Use SET in Update Expression in DynamoDB
In DynamoDB, use the
SET clause in an update expression to assign new values to one or more attributes of an item. The syntax is SET attributeName = :value, where :value is a placeholder for the new value provided in ExpressionAttributeValues.Syntax
The SET clause in a DynamoDB update expression assigns new values to attributes. It can update one or multiple attributes separated by commas.
- SET: Keyword to start the update assignment.
attributeName: The attribute you want to update.= :value: Assigns the attribute to the value represented by a placeholder.ExpressionAttributeValues: A map of placeholders to actual values.
json
UpdateExpression = "SET attributeName = :value" ExpressionAttributeValues = { ":value": {"S": "newValue"} }
Example
This example updates the status attribute of an item with primary key id to "completed" using the SET clause.
python
import boto3 # Initialize DynamoDB client client = boto3.client('dynamodb') # Update item with SET expression response = client.update_item( TableName='Tasks', Key={ 'id': {'S': 'task123'} }, UpdateExpression='SET #st = :newStatus', ExpressionAttributeNames={ '#st': 'status' }, ExpressionAttributeValues={ ':newStatus': {'S': 'completed'} }, ReturnValues='UPDATED_NEW' ) print(response['Attributes'])
Output
{"status": {"S": "completed"}}
Common Pitfalls
Common mistakes when using SET in update expressions include:
- Not using
ExpressionAttributeNameswhen attribute names are reserved words or contain special characters. - Forgetting to define all placeholders used in
UpdateExpressioninsideExpressionAttributeValues. - Using incorrect data types for values (e.g., string vs number).
- Not specifying
ReturnValuesif you want to see updated attributes.
text
Wrong: UpdateExpression='SET status = :newStatus' # Missing ExpressionAttributeValues for :newStatus Right: UpdateExpression='SET status = :newStatus' ExpressionAttributeValues={':newStatus': {'S': 'completed'}}
Quick Reference
| Part | Description | Example |
|---|---|---|
| SET | Keyword to assign new values | SET attributeName = :value |
| attributeName | Name of attribute to update | status |
| :value | Placeholder for new value | :newStatus |
| ExpressionAttributeValues | Map placeholders to actual values | { ':newStatus': {'S': 'completed'} } |
| ExpressionAttributeNames | Map attribute name placeholders if needed | { '#st': 'status' } |
Key Takeaways
Use the SET clause in UpdateExpression to assign new values to attributes.
Always define placeholders in ExpressionAttributeValues for values used in SET.
Use ExpressionAttributeNames to avoid conflicts with reserved words.
Specify ReturnValues='UPDATED_NEW' to get updated attributes in response.
Separate multiple attribute updates with commas in the SET clause.