Deleting items from a DynamoDB table is a common operation for managing data lifecycle, cleanup, or user-driven deletions. In this guide, you’ll learn how to delete data from DynamoDB tables using Python and Boto3, the AWS SDK for Python.
Table of Contents
-
Understanding Delete in DynamoDB
-
Prerequisites
-
Basic Delete Syntax in Python (Boto3)
-
Conditional Deletes
-
Batch Deletes
-
Deleting with
scan()
+ Delete (when key is unknown) -
Complete Example
-
Tips and Best Practices
-
Common Pitfalls
-
Conclusion
1. Understanding Delete in DynamoDB
DynamoDB’s delete_item()
operation removes a single item identified by its primary key (partition key + optional sort key). You can also use conditional expressions to ensure only specific items are deleted.
-
Efficient: Directly removes the item using its key
-
Supports conditions: Only delete if a certain condition is met
-
Can be batched: Use
batch_writer()
for bulk deletions
⚙️ 2. Prerequisites
-
Python 3.7+
-
AWS account
-
DynamoDB table (e.g.,
Users
) with partition key (user_id
) and optional sort key -
AWS credentials configured via
aws configure
Install Boto3 if not already:
pip install boto3
3. Basic Delete Syntax in Python (Boto3)
Assume you have a Users
table with:
-
Partition key:
user_id
-
Sort key:
email
(optional)
Example: Delete by Partition Key
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
response = table.delete_item(
Key={
'user_id': '001'
}
)
print("Delete response:", response)
Example: With Partition and Sort Key
response = table.delete_item(
Key={
'user_id': '001',
'email': '[email protected]'
}
)
✅ 4. Conditional Deletes
You can enforce conditions to ensure an item is only deleted if it matches specific criteria.
Example: Delete only if status = 'inactive'
from boto3.dynamodb.conditions import Attr
response = table.delete_item(
Key={
'user_id': '001'
},
ConditionExpression=Attr('status').eq('inactive')
)
If the condition fails, an exception is raised, which you should catch:
from botocore.exceptions import ClientError
try:
table.delete_item(
Key={'user_id': '001'},
ConditionExpression=Attr('status').eq('inactive')
)
except ClientError as e:
if e.response['Error']['Code'] == "ConditionalCheckFailedException":
print("Delete condition failed.")
else:
raise
5. Batch Deletes (Efficient Bulk Deletion)
Use batch_writer()
to delete multiple items in a loop.
with table.batch_writer() as batch:
batch.delete_item(Key={'user_id': '001'})
batch.delete_item(Key={'user_id': '002'})
This is useful when deleting many items at once and handles retries automatically.
6. Deleting Items Found via scan()
If you don’t know the keys beforehand, you can scan the table and delete items one by one.
⚠️ Use with caution (inefficient for large tables)
response = table.scan()
items = response['Items']
with table.batch_writer() as batch:
for item in items:
batch.delete_item(Key={'user_id': item['user_id']})
If your table uses both partition and sort key, include both in Key
.
7. Complete Example
import boto3
from boto3.dynamodb.conditions import Attr
from botocore.exceptions import ClientError
def delete_user(user_id):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
try:
response = table.delete_item(
Key={'user_id': user_id},
ConditionExpression=Attr('status').eq('inactive')
)
print("Deleted:", response)
except ClientError as e:
if e.response['Error']['Code'] == "ConditionalCheckFailedException":
print(f"User {user_id} not deleted due to condition failure.")
else:
raise
# Example usage
delete_user('001')
8. Tips and Best Practices
Tip | Reason |
---|---|
✅ Use ConditionExpression |
Prevents accidental deletes |
✅ Use batch_writer() |
Efficient bulk deletion |
✅ Always use primary keys | Required for delete_item() |
❌ Avoid scan() on large tables |
Expensive and slow |
Use IAM policies to control delete access | Prevents misuse and accidental data loss |
⚠️ 9. Common Pitfalls
Pitfall | Solution |
---|---|
❌ Forgetting sort key | Both keys required if your table uses them |
❌ Not handling conditional failures | Always catch ClientError |
❌ Using scan() for large deletes |
Use key-based deletes instead |
❌ Assuming delete is reversible | It is permanent unless backed up |
❌ Misunderstanding ConditionExpression behavior |
Always test conditions before using them in production |
✅ 10. Conclusion
Deleting data from DynamoDB using Python is straightforward when you know the item’s key. For more complex use cases, conditional expressions and batch deletions make it efficient and safe. However, deletion is permanent, so use safeguards like condition checks and role-based permissions.
What’s Next?
Want to learn about:
-
Deleting entire tables?
-
Archiving data before deletion (soft delete)?
-
Restoring deleted data from backups?