What you'll learn
- PutItem overwrites items with the same primary key by default.
- Use ConditionExpression to prevent accidental overwrites.
- attribute_not_exists(key) ensures the item is new.
Section 01
The Overwrite Problem
DynamoDB's PutItem operation is destructive by default. If you put an item with the same Partition Key (Name) as an existing item, DynamoDB will replace the old item completely.
To prevent this, you can ask DynamoDB to check a condition before writing. If the condition fails, the write is rejected with a ConditionalCheckFailedException.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({ region: "ap-south-1" });
const docClient = DynamoDBDocumentClient.from(client);
await docClient.send(new PutCommand({
TableName: "Pokemon",
Item: { Name: "Mew", Level: 5 }
}));Ready · 5 steps · Orbi
This animation plays when you scroll to it. Press Play to start it now.
All steps as text
- Your app sends PutItem to the Pokemon table with Name = "Mew". No ConditionExpression, and a Level 50 Mew is already stored.
- DynamoDB hashes "Mew" to 416a585c, which routes the request to partition P0.
- Your app's write to Mew lands on P0 and silently replaces the other change.
- This call consumed 1 WCU.
- DynamoDB responds with success: the Level 50 Mew was replaced by a fresh Level 5 copy, with no error.
Section 02
Safe Put with Conditions
Use ConditionExpression with the function attribute_not_exists(). This tells DynamoDB: "Only write this item if the attribute 'Name' does not exist yet."
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({ region: "ap-south-1" });
const docClient = DynamoDBDocumentClient.from(client);
await docClient.send(new PutCommand({
TableName: "Pokemon",
Item: { Name: "Mew", Level: 5 },
ExpressionAttributeNames: { "#name": "Name" },
ConditionExpression: "attribute_not_exists(#name)"
}));Practice
Your turn
Add a
ConditionExpression so Mew is only added if it isn't already in your party. Use attribute_not_exists(#name), with #name mapped to Name in ExpressionAttributeNames, so an existing item is never overwritten.Add a
ConditionExpression so the put fails if Name already exists.Tab inserts two spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the code.
Ctrl/⌘ Enter to run · simulated, no AWS callsSimulated — no AWS calls
Check
Check your understanding
Quick Quiz · one question, as many tries as you need.
What happens if you use PutItem on an existing key without a condition?
Choose one answer.