DEV Community

Abhishek Gupta for AWS

Posted on • Updated on • Originally published at

[20 Days of DynamoDB] Day 1 - Conditional PutItem

For the next 20 days (don't ask me why I chose that number 😉), I will be publishing a DynamoDB quick tip per day with code snippets. The examples use the DynamoDB packages from AWS SDK for Go V2, but should be applicable to other languages as well.

Posted: 8/Jan/2024

The DynamoDB PutItem API overwrites the item in case an item with the same primary key already exists. To avoid (or work around) this behaviour, use PutItem with an additional condition.

Here is an example that uses the attribute_not_exists function:

    _, err := client.PutItem(context.Background(), &dynamodb.PutItemInput{
        TableName: aws.String(tableName),
        Item: map[string]types.AttributeValue{
            "email": &types.AttributeValueMemberS{Value: email},
        ConditionExpression: aws.String("attribute_not_exists(email)"),
        ReturnConsumedCapacity:      types.ReturnConsumedCapacityTotal,
        ReturnValues:                types.ReturnValueAllOld,
        ReturnItemCollectionMetrics: types.ReturnItemCollectionMetricsSize,

    if err != nil {
        if strings.Contains(err.Error(), "ConditionalCheckFailedException") {
            log.Println("failed pre-condition check")
        } else {
Enter fullscreen mode Exit fullscreen mode

With the PutItem operation, you can also:

  • Return the consumed Write Capacity Units (WCU)
  • Get the item attributes as they appeared before (in case they were updated during the operation)
  • Retrieve statistics about item collections, if any, that were modified during the operation

Recommended reading:

Top comments (0)