Quest · quest 5
Put Mew into Your Party
You've encountered the mythical Pokémon Mew! You want to add it to your party (the Pokemon table), but you must be careful. If you just use PutItem, you might overwrite an existing Pokémon if they have the same name (unlikely for Mew, but critical for data integrity!). Use a ConditionExpression to ensure the item doesn't already exist.
Key takeaways
- 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.
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.
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."
Name is a DynamoDB reserved word. We use it directly here to keep things simple — in the Expression Attributes quest you'll learn to alias reserved words with a # placeholder so the expression never breaks.Interactive Challenge
Add the ConditionExpression to the code below to safely add Mew to your party. Ensure you use the function attribute_not_exists(Name) to prevent overwriting.
ConditionExpression to ensure "Name" does not already exist.Quick Quiz
What happens if you use PutItem on an existing key without a condition?
Make your choice to test your understanding. Submit to check, and if it's not quite right you can adjust and try again.