How to Use DeleteItem in DynamoDB: Syntax and Example
Use the
DeleteItem operation in DynamoDB to remove a single item by specifying its primary key. You provide the table name and key attributes in the request, and DynamoDB deletes the matching item if it exists.Syntax
The DeleteItem operation requires the TableName and the Key of the item to delete. Optionally, you can specify ConditionExpression to delete only if certain conditions are met, and ReturnValues to get the deleted item's attributes.
- TableName: The name of your DynamoDB table.
- Key: A map of the primary key attribute(s) identifying the item.
- ConditionExpression (optional): A condition that must be true for the delete to proceed.
- ReturnValues (optional): What attributes to return, e.g.,
ALL_OLDreturns the deleted item.
plaintext
DeleteItem {
TableName: string,
Key: { [attributeName: string]: AttributeValue },
ConditionExpression?: string,
ReturnValues?: string
}Example
This example shows how to delete an item from a DynamoDB table named Users where the primary key is UserId. It deletes the item with UserId equal to 123 and returns the deleted item's attributes.
python
import boto3 # Create DynamoDB client client = boto3.client('dynamodb') # Delete item from 'Users' table where UserId = '123' response = client.delete_item( TableName='Users', Key={ 'UserId': {'S': '123'} }, ReturnValues='ALL_OLD' ) print('Deleted item:', response.get('Attributes'))
Output
Deleted item: {'UserId': {'S': '123'}, 'Name': {'S': 'Alice'}, 'Age': {'N': '30'}}
Common Pitfalls
- Not specifying the full primary key in
Keycauses the delete to fail. - Using
ConditionExpressionincorrectly can prevent deletion if conditions are not met. - Expecting
ReturnValuesto return the deleted item without setting it toALL_OLDreturns nothing. - Trying to delete a non-existent item does not cause an error but returns no attributes.
python
## Wrong: Missing part of composite key client.delete_item( TableName='Orders', Key={ 'OrderId': {'S': '001'} # Missing SortKey attribute } ) ## Right: Provide full composite key client.delete_item( TableName='Orders', Key={ 'OrderId': {'S': '001'}, 'OrderDate': {'S': '2023-01-01'} } )
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| TableName | Name of the DynamoDB table | 'Users' |
| Key | Primary key of the item to delete | {'UserId': {'S': '123'}} |
| ConditionExpression | Condition to allow delete | attribute_exists(UserId) |
| ReturnValues | Attributes to return after delete | 'ALL_OLD' |
Key Takeaways
Always specify the full primary key in the Key parameter to delete an item.
Use ReturnValues='ALL_OLD' to get the deleted item's attributes in the response.
ConditionExpression can prevent deletion if conditions are not met; use carefully.
Deleting a non-existent item does not cause an error but returns no attributes.
DeleteItem removes only one item at a time identified by its primary key.