DEV Community

Abhishek Gupta for AWS

Posted on • Originally published at community.aws

1 1

[20 Days of DynamoDB] Day 8 - Conditional Delete operation

Posted - 17/Jan/2024

All the DynamoDB write APIs, including DeleteItem support criteria-based (conditional) execution. You can use DeleteItem operation with a condition expression - it must evaluate to true in order for the operation to succeed.

Here is an example that verifies the value of inactive_days attribute:

    resp, err := client.DeleteItem(context.Background(), &dynamodb.DeleteItemInput{
        TableName: aws.String(tableName),
        Key: map[string]types.AttributeValue{
            "email": &types.AttributeValueMemberS{Value: email},
        },
        ConditionExpression: aws.String("inactive_days >= :val"),
        ExpressionAttributeValues: map[string]types.AttributeValue{
            ":val": &types.AttributeValueMemberN{Value: "20"},
        },
    })

    if err != nil {
        if strings.Contains(err.Error(), "ConditionalCheckFailedException") {
            return
        } else {
            log.Fatal(err)
        }
    }
Enter fullscreen mode Exit fullscreen mode

Recommended reading - Conditional deletes documentation

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay