0
0
DynamoDBquery~5 mins

Conditional expressions in DynamoDB

Choose your learning style9 modes available
Introduction

Conditional expressions help you check if certain conditions are true before changing data in your database. This keeps your data safe and accurate.

You want to add a new item only if it does not already exist.
You want to update a value only if it matches a specific current value.
You want to delete an item only if it meets certain criteria.
You want to avoid overwriting data accidentally.
You want to make sure a number is within a range before updating it.
Syntax
DynamoDB
ConditionExpression = "attribute_exists(attributeName) AND attribute_not_exists(otherAttribute)"

# Use placeholders for attribute names and values:
ExpressionAttributeNames = {"#attr": "attributeName"}
ExpressionAttributeValues = {":val": value}

Use ConditionExpression to write your condition.

Use placeholders like #attr and :val to avoid conflicts with reserved words.

Examples
Only add a new item if the UserID does not exist yet.
DynamoDB
ConditionExpression = "attribute_not_exists(UserID)"
Update only if Age is 18 or older.
DynamoDB
ConditionExpression = "Age >= :minAge",
ExpressionAttributeValues = {":minAge": {"N": "18"}}
Update only if Status is currently 'Pending'.
DynamoDB
ConditionExpression = "#status = :currentStatus",
ExpressionAttributeNames = {"#status": "Status"},
ExpressionAttributeValues = {":currentStatus": {"S": "Pending"}}
Sample Program

This code adds a new user to the 'Users' table only if the UserID 'user123' is not already there. If the UserID exists, it will not add and will raise an error.

DynamoDB
import boto3

# Connect to DynamoDB
client = boto3.client('dynamodb')

table_name = 'Users'

# Try to add a new user only if UserID does not exist
response = client.put_item(
    TableName=table_name,
    Item={
        'UserID': {'S': 'user123'},
        'Name': {'S': 'Alice'},
        'Age': {'N': '30'}
    },
    ConditionExpression='attribute_not_exists(UserID)'
)

print('User added successfully')
OutputSuccess
Important Notes

If the condition is false, DynamoDB returns a ConditionalCheckFailedException.

Always use condition expressions to avoid accidental data loss.

Summary

Conditional expressions let you control when data changes happen.

They help keep your data safe and consistent.

Use placeholders to avoid conflicts with reserved words.