0
0
DynamodbHow-ToBeginner ยท 4 min read

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 ExpressionAttributeNames when attribute names are reserved words or contain special characters.
  • Forgetting to define all placeholders used in UpdateExpression inside ExpressionAttributeValues.
  • Using incorrect data types for values (e.g., string vs number).
  • Not specifying ReturnValues if 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

PartDescriptionExample
SETKeyword to assign new valuesSET attributeName = :value
attributeNameName of attribute to updatestatus
:valuePlaceholder for new value:newStatus
ExpressionAttributeValuesMap placeholders to actual values{ ':newStatus': {'S': 'completed'} }
ExpressionAttributeNamesMap 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.