How to Delete Item in DynamoDB: Syntax and Example
To delete an item in DynamoDB, use the
DeleteItem operation specifying the table name and the key of the item to remove. This operation permanently removes the item identified by its primary key from the table.Syntax
The DeleteItem operation requires the TableName and the Key of the item you want to delete. The Key is a map of attribute names to their values that uniquely identify the item.
Optionally, you can use ConditionExpression to delete the item only if certain conditions are met.
plaintext
DeleteItem {
TableName: string,
Key: { <PrimaryKeyAttributeName>: {S|N|B: value}, ... },
ConditionExpression?: string
}Example
This example shows how to delete an item from a DynamoDB table named Users where the primary key is UserId with value 123. It uses AWS SDK for JavaScript (v3).
javascript
import { DynamoDBClient, DeleteItemCommand } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({ region: "us-east-1" }); async function deleteUser() { const params = { TableName: "Users", Key: { "UserId": { S: "123" } } }; try { const data = await client.send(new DeleteItemCommand(params)); console.log("Item deleted successfully", data); } catch (err) { console.error("Error deleting item", err); } } deleteUser();
Output
Item deleted successfully {}
Common Pitfalls
- Not specifying the full primary key (partition key and sort key if applicable) will cause the delete to fail or delete the wrong item.
- Forgetting to handle errors can hide issues like trying to delete a non-existent item.
- Using
ConditionExpressionincorrectly can prevent deletion if conditions are not met.
javascript
/* Wrong: Missing sort key if table has composite key */ const paramsWrong = { TableName: "Orders", Key: { "OrderId": { S: "001" } // Missing SortKey attribute } }; /* Right: Include both partition and sort key */ const paramsRight = { TableName: "Orders", Key: { "OrderId": { S: "001" }, "SortKey": { S: "C123" } } };
Quick Reference
Remember these key points when deleting an item in DynamoDB:
- Always specify the full primary key in
Key. - Use
ConditionExpressionto avoid accidental deletes. - Handle errors to catch issues like missing items.
- DeleteItem is permanent; no undo.
Key Takeaways
Use DeleteItem with the full primary key to remove an item from DynamoDB.
ConditionExpression helps prevent unwanted deletions by adding conditions.
Always handle errors to know if the delete succeeded or failed.
Deleting an item is permanent; ensure you want to remove it before running.
Include both partition and sort keys if your table uses a composite key.