Deleting Data
Use delete() to remove rows from a table. The condition can be a dictionary or a
raw SQL string. The statement is committed for you.
db.delete(table, condition) condition is required
Both arguments are positional and required. db.delete('session_tokens')
raises TypeError: delete() missing 1 required positional argument: 'condition'
— it does not clear the table. To delete every row, pass a condition that is always true,
such as "1=1".
Parameters
| Parameter | Type | Description |
|---|---|---|
table | str | Name of the table |
condition | dict or str |
Required. Dict keys are joined with AND; a string is injected verbatim.
|
Delete by ID
# DELETE FROM products WHERE id='42' ;
db.delete('products', {'id': 42})
Delete with multiple conditions
# DELETE FROM products WHERE category='discontinued' AND stock='0' ;
db.delete('products', {'category': 'discontinued', 'stock': 0})
The dict branch is guarded by collections.Iterable, removed in Python 3.10, so
passing a dict raises AttributeError there. String conditions are unaffected —
the check short-circuits before it is reached.
See Limitations.
Delete with a SQL string
# Delete orders older than 1 year
db.delete('orders', "created_at < DATE_SUB(NOW(), INTERVAL 1 YEAR)")
Delete every row
Pass a tautology as the condition:
db.delete('session_tokens', "1=1") # clears the entire table
TRUNCATE is faster for emptying a table and resets the AUTO_INCREMENT
counter, but the library's truncate() helper is broken in this release — run it
through execute() instead:
db.execute("TRUNCATE session_tokens;") Return value
delete() returns None. Read
count() afterwards for the number of rows removed:
db.delete('orders', "status = 'cancelled'")
print(db.count(), "rows deleted")