Clearing a DynamoDB table means removing its items while keeping the table itself. Unlike some relational databases, Amazon DynamoDB does not offer a simple TRUNCATE TABLE command. To clear a table, you can scan for its items and delete them, or delete the table and create it again. The right approach depends on the table’s size, whether you need to preserve its configuration, and how much downtime you can accept.
This guide explains how to clear a DynamoDB table safely using the AWS Console, Python, or table deletion and recreation. It also covers costs, permissions, backups, and common mistakes to avoid.
What Does “Clear a DynamoDB Table” Mean?
Usually, clearing a DynamoDB table means deleting every item but retaining the table’s primary key schema and other settings. DynamoDB does not have a built-in operation that instantly empties a table while preserving it. Each item must be deleted individually, or the whole table must be deleted and rebuilt.
That distinction matters. Deleting items preserves the table, but it takes time and consumes write capacity. Deleting the table can be simpler for a disposable dataset, but it also removes the table’s indexes and configuration. Before choosing a method, confirm whether you need to retain the table name, indexes, streams, capacity settings, tags, or other resources connected to it.
Choose the Right Method
- Delete items individually: Best when you need to keep the table and its configuration. Use a scan followed by batch deletes, or write an application-specific process.
- Delete and recreate the table: Often convenient for a small development or test table that can be rebuilt from a known definition. This removes the table and its data, so plan for downtime and configuration setup.
- Use an application-specific cleanup: Best when your items have a known key pattern, such as a tenant ID or date range. Querying a targeted set of keys can avoid scanning the entire table.
There is no universal “clear table” button or single DynamoDB command that safely deletes every item while preserving all table settings. The method you select should reflect the table’s size and the consequences of losing its data.
Clear a DynamoDB Table with Python and Boto3
For many use cases, a Python script using Boto3 is a practical way to delete every item while keeping the table. The general process is to scan the table for primary keys and submit a delete request for each item. DynamoDB batch write operations support up to 25 requests per batch; Boto3’s batch_writer handles batching and retries for unprocessed items.
The example below reads the table’s key schema, scans only the key attributes, and deletes the matching items. Set the AWS credentials and region using your usual AWS configuration, and replace the table name with the one you intend to clear.
import boto3
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
table = dynamodb.Table("YOUR_TABLE_NAME")
# Find the partition key and, if present, the sort key.
key_names = [element["AttributeName"] for element in table.key_schema]
# Alias attribute names in case a key name is a reserved word.
expression_names = {
f"#key{i}": name for i, name in enumerate(key_names)
}
projection = ", ".join(expression_names.keys())
scan_args = {
"ProjectionExpression": projection,
"ExpressionAttributeNames": expression_names,
}
with table.batch_writer() as batch:
while True:
response = table.scan(**scan_args)
for item in response.get("Items", []):
key = {name: item[name] for name in key_names}
batch.delete_item(Key=key)
last_key = response.get("LastEvaluatedKey")
if not last_key:
break
scan_args["ExclusiveStartKey"] = last_key
print("Table items have been processed for deletion.")
DynamoDB may return a page of results rather than the entire table in one response. The loop uses LastEvaluatedKey to continue scanning until there are no more pages. Omitting that pagination logic can leave items behind in larger tables.
The script discovers both partition and sort keys, if the table has them. Each delete request must include the complete primary key for the item. Do not assume that every table has only a partition key, and do not try to delete an item using a non-key attribute alone.
Important Safety Checks Before Running the Script
- Confirm the account, region, and table name. Check the AWS account and region in your environment before running a destructive script. A similarly named production table can be easy to mistake for a test table.
- Back up important data. Create an on-demand backup or verify that point-in-time recovery is enabled and suitable for your recovery needs. A backup provides a recovery option; it does not make a deletion harmless.
- Pause writes where possible. A scan is not a snapshot of the table. If applications continue creating or changing items during the cleanup, some items may remain or new items may appear after the scan has passed their keys.
- Test on a small table first. Validate the script and key handling in a non-production environment before running it against valuable data.
- Check permissions. The identity running the script needs permission to describe and scan the table and to delete items. Exact permissions depend on your setup and any encryption or access controls in use.
For a stable cleanup, stop or redirect application writes until the process finishes, then verify the result. A strongly consistent scan can provide more current reads for supported tables, but it still does not create a transactionally consistent snapshot of the entire table. Coordinate with writers if you need a reliably empty result.
Clear a Table from the AWS Console
You can delete items through the AWS Management Console, but manually selecting records is usually suitable only for small tables or one-off cleanup. Open DynamoDB, choose Tables, select the table, and use the item explorer to find and delete items. Console labels and layouts can change, so check the current AWS interface for the available item actions.
For a large table, avoid treating the item explorer as a bulk truncate tool. A manual workflow may require repeated searches and deletions, and it is easier to miss records. A scripted, reviewed process is generally more repeatable and easier to monitor.
Delete and Recreate the DynamoDB Table
If the table contains disposable data and you can tolerate downtime, deleting and recreating it may be simpler than deleting every item. You can delete a table from the AWS Console or with the AWS CLI:
aws dynamodb delete-table --table-name YOUR_TABLE_NAME
Table deletion is asynchronous. Wait for the table to finish deleting before attempting to create another table with the same name. You can check its status with the AWS Console or a command such as:
aws dynamodb describe-table --table-name YOUR_TABLE_NAME
After deletion, create a replacement table with the required partition key, sort key, billing mode or capacity settings, and secondary indexes. Also review any connected features and dependencies, such as streams, alarms, application configuration, resource policies, tags, and infrastructure-as-code definitions. Do not assume that recreating a table automatically restores its previous setup.
This approach removes the table itself, not just its items. It is therefore a poor fit when applications depend on the table being available continuously or when its configuration is difficult to reproduce. Keep the table definition in infrastructure-as-code or another reliable source if you expect to rebuild it.
Understand the Cost and Time
A scan reads table data, and deleting each item consumes write capacity. The exact time and cost depend on table size, item size, capacity settings, throttling, and competing workload. On a large table, a full scan and delete can take a long time and affect other applications sharing the table’s capacity.
Monitor the table during cleanup for throttling, consumed capacity, and application impact. Consider running the job at a quieter time and using controlled pacing if it competes with normal traffic. For a very large table, evaluate the workload and AWS’s current DynamoDB guidance before selecting a deletion strategy; a simple script may not be appropriate for every scale or service-level requirement.
Common Mistakes to Avoid
-
Expecting a SQL-style truncate command: DynamoDB does not provide a standard
TRUNCATE TABLEoperation. -
Scanning only the first page: Always continue through every page using
LastEvaluatedKey. - Deleting with an incomplete key: Include every primary key attribute, including the sort key when the table has one.
- Allowing writes during cleanup: Concurrent application activity can cause the table to contain items when the job ends.
- Deleting a production table without a recovery plan: Verify backups, dependencies, and the exact target before taking action.
- Assuming a table rebuild restores everything: Recreate indexes and settings deliberately, and confirm that dependent applications point to the correct table.
How to Verify the Table Is Empty
After the cleanup completes, verify the result rather than relying only on a success message. You can check the table in the Console or run a scan that requests a count. DynamoDB’s reported item count in table metadata may not update immediately, so it is not always an instant confirmation. For stronger verification, use a scan that processes all pages and check that it returns no items, while keeping application writes paused.
Also review the script’s output and CloudWatch metrics for errors or throttling. If the table is still receiving writes, an empty result at one moment does not guarantee that it will remain empty.
Conclusion
To clear a DynamoDB table while preserving it, scan its items and delete them using their complete primary keys. A paginated Boto3 script with batch_writer is a reliable starting point for many small and medium cleanup jobs, provided you test it, protect important data, and account for concurrent writes and capacity use. If the data is disposable and downtime is acceptable, deleting and recreating the table may be simpler—but you must rebuild its schema, indexes, and related configuration. Choose the approach that matches your table’s size, recovery requirements, and application needs, then verify the result before resuming writes.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.