SQLite Delete
Delete Rows
Use the DELETE FROM statement to delete rows from a table. WHERE tells which rows to delete.
The examples on this page use this players table:
| name | score |
|---|---|
| Emil | 120 |
| Tobias | 95 |
| Linus | 150 |
| Lene | 80 |
To keep the examples short, they show only the code for the DELETE statement. Click "Try it Yourself" to see the complete code, which also creates the table and adds the rows.
Example
Delete the row for Tobias:
cur.execute("""
DELETE FROM players
WHERE name = 'Tobias'
""")
con.commit()
Try it Yourself »
Warning: Remember the WHERE part. Without WHERE, all the rows are deleted!
Delete With a Variable
Use a ? placeholder for a value from a variable. Remember the comma in (name,):
Example
Delete the player with the name in the variable name:
name = "Tobias"
cur.execute(
"DELETE FROM players WHERE name = ?",
(name,)
)
con.commit()
Try it Yourself »
Delete Many Rows
All the rows that match the condition are deleted. cur.rowcount tells how many:
Example
Delete all players with less than 100 points:
cur.execute("""
DELETE FROM players
WHERE score < 100
""")
con.commit()
print(cur.rowcount, "rows deleted")
Try it Yourself »
Delete All Rows
To delete all the rows, but keep the table, leave out WHERE:
The table is still there, but it is empty.
Delete a Table
Use DROP TABLE to delete the whole table, with all its rows:
The table and all its rows are gone. In "Try it Yourself", the list of tables from sqlite_master is empty.
Note: If the table does not exist, DROP TABLE gives an error. Write DROP TABLE IF EXISTS players to delete the table only if it exists.