Introduction
The SET expression lets you add new attributes or change existing ones in a DynamoDB item.
Jump into concepts and practice - no test required
The SET expression lets you add new attributes or change existing ones in a DynamoDB item.
UpdateExpression: "SET attributeName = :value, anotherAttribute = :anotherValue"UpdateExpression: "SET age = :newAge"UpdateExpression: "SET lastLogin = :time, status = :newStatus"UpdateExpression: "SET score = score + :increment"This updates the user's email and increases their login count by 1. If 'loginCount' does not exist, it starts at 0.
const params = {
TableName: "Users",
Key: { userId: "123" },
UpdateExpression: "SET email = :newEmail, loginCount = if_not_exists(loginCount, :start) + :inc",
ExpressionAttributeValues: {
":newEmail": "new.email@example.com",
":start": 0,
":inc": 1
},
ReturnValues: "UPDATED_NEW"
};
// Assume docClient is an instance of AWS.DynamoDB.DocumentClient
const result = await docClient.update(params).promise();
console.log(result.Attributes);Use if_not_exists to safely add numbers when the attribute might not exist yet.
Always use placeholders (like :newEmail) to avoid injection and errors.
SET expression updates or adds attributes in DynamoDB items.
Use placeholders for values to keep queries safe and clear.
You can update multiple attributes in one SET expression.
SET expression do in a DynamoDB UpdateItem operation?age to 30?UpdateExpression: "SET #n = :newName, age = age + :inc",
ExpressionAttributeNames: {"#n": "name"},
ExpressionAttributeValues: {":newName": "Alice", ":inc": 1}SET age = age + :inc newName = :bobstatus to "active" only if it does not exist, and also increment loginCount by 1. Which UpdateExpression correctly does this?