0
0
DynamodbHow-ToBeginner ยท 3 min read

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_exists can overwrite existing values unintentionally.
  • Using if_not_exists outside of UpdateExpression is invalid.
  • For numeric increments, forgetting to add the increment value after if_not_exists causes 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

FunctionPurposeExample Usage
if_not_exists(path, default)Returns attribute value if exists, else defaultSET attr = if_not_exists(attr, :default)
Use in UpdateExpressionConditionally set or increment attributesSET count = if_not_exists(count, :zero) + :one
Common use caseInitialize counters or timestamps only if missingSET 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.