How to Use if_not_exists in DynamoDB for Conditional Updates
In DynamoDB, use the
if_not_exists function in an UpdateExpression to set an attribute only if it does not already exist. This helps avoid overwriting existing values by providing a default when the attribute is missing.Syntax
The if_not_exists(path, default) function checks if the attribute at path exists. If it does, it returns the current value; if not, it returns the default value.
It is commonly used in UpdateExpression to conditionally set or increment attributes.
sql
SET attribute = if_not_exists(attribute, :default_value)Example
This example shows how to increment a counter attribute only if it exists, or initialize it to 1 if it does not.
javascript
const AWS = require('aws-sdk'); const dynamodb = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'MyTable', Key: { id: '123' }, UpdateExpression: 'SET visitCount = if_not_exists(visitCount, :start) + :inc', ExpressionAttributeValues: { ':start': 0, ':inc': 1 }, ReturnValues: 'UPDATED_NEW' }; dynamodb.update(params, (err, data) => { if (err) { console.error('Update failed:', err); } else { console.log('Update succeeded:', data.Attributes); } });
Output
{"visitCount": 1}
Common Pitfalls
- Not using
if_not_existscan overwrite existing values unintentionally. - Using
if_not_existsoutside ofUpdateExpressionis invalid. - For numeric increments, forgetting to add the increment value after
if_not_existscauses no change.
sql
/* Wrong: Overwrites visitCount always */ UpdateExpression: 'SET visitCount = :val', ExpressionAttributeValues: { ':val': 1 } /* Right: Uses if_not_exists to initialize or increment */ UpdateExpression: 'SET visitCount = if_not_exists(visitCount, :start) + :inc', ExpressionAttributeValues: { ':start': 0, ':inc': 1 }
Quick Reference
| Function | Purpose | Example Usage |
|---|---|---|
| if_not_exists(path, default) | Returns attribute value if exists, else default | SET attr = if_not_exists(attr, :default) |
| Use in UpdateExpression | Conditionally set or increment attributes | SET count = if_not_exists(count, :zero) + :one |
| Common use case | Initialize counters or timestamps only if missing | SET lastSeen = if_not_exists(lastSeen, :now) |
Key Takeaways
Use
if_not_exists in UpdateExpression to avoid overwriting existing attributes.It returns the current attribute value if present, otherwise returns the default you provide.
Commonly used to initialize counters or timestamps only when they don't exist.
Always add increments after
if_not_exists for numeric updates.Do not use
if_not_exists outside update expressions; it will cause errors.