0
0
DynamodbHow-ToBeginner ยท 3 min read

How to Use REMOVE in Update Expression in DynamoDB

In DynamoDB, use the REMOVE clause in an UpdateExpression to delete one or more attributes from an item. The syntax is REMOVE attributeName, and you can list multiple attributes separated by commas to remove them in a single update operation.
๐Ÿ“

Syntax

The REMOVE clause in a DynamoDB UpdateExpression specifies which attributes to delete from an item. You write it as REMOVE attribute1, attribute2, .... Each attribute listed will be removed from the item if it exists.

This clause is part of the UpdateExpression parameter in the UpdateItem API call.

sql
UpdateExpression = "REMOVE attributeName1, attributeName2"
๐Ÿ’ป

Example

This example shows how to remove the attributes PhoneNumber and Address from a DynamoDB item with a given UserId.

javascript
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();

const params = {
  TableName: 'Users',
  Key: { UserId: '123' },
  UpdateExpression: 'REMOVE PhoneNumber, Address'
};

dynamodb.update(params, (err, data) => {
  if (err) {
    console.error('Error updating item:', err);
  } else {
    console.log('Attributes removed successfully:', data);
  }
});
Output
Attributes removed successfully: { Attributes: undefined, ConsumedCapacity: undefined, ItemCollectionMetrics: undefined }
โš ๏ธ

Common Pitfalls

  • Trying to remove a non-existent attribute: This does not cause an error; DynamoDB simply ignores it.
  • Using REMOVE with incorrect attribute names: Attribute names must be valid and, if reserved words, must be replaced with expression attribute names (e.g., #attr).
  • Mixing REMOVE with other update actions incorrectly: Separate SET, REMOVE, ADD, and DELETE clauses with spaces in the same UpdateExpression.
sql
/* Wrong: Using reserved word without expression attribute name */
UpdateExpression = "REMOVE Size"

/* Right: Using expression attribute name for reserved word */
UpdateExpression = "REMOVE #sz"
ExpressionAttributeNames = { "#sz": "Size" }
๐Ÿ“Š

Quick Reference

ClausePurposeExample
REMOVEDeletes attributes from an itemREMOVE PhoneNumber, Address
SETAdds or updates attributesSET Age = 30
ADDAdds numbers or elements to setsADD Score 5
DELETERemoves elements from setsDELETE Tags :tagToRemove
โœ…

Key Takeaways

Use the REMOVE clause in UpdateExpression to delete attributes from a DynamoDB item.
List multiple attributes separated by commas to remove them in one update call.
If an attribute does not exist, REMOVE does not cause an error.
Use expression attribute names for reserved words in attribute names.
Combine REMOVE with other update actions by separating clauses with spaces.