1.7 KiB
DELETE
Overview
The DELETE statement is fundamental for data management, enabling the removal of rows from a database table. Proper use ensures data integrity and efficiency within your application's data layer.
Basic DELETE
Removes specific rows based on a condition. The WHERE clause is critical for precise targeting. Omitting it will affect all rows in the table.
DELETE FROM users WHERE id=5;
A successful operation indicates the number of rows removed.
Query OK, 1 row affected (0.01 sec)
Critical Warning
Executing DELETE without a WHERE clause removes all data from the specified table.
DELETE FROM users;
Output reflects the total count of rows deleted.
Query OK, x row(s) affected (0.047 sec)
Unlike operations within a transaction that can be rolled back, standard DELETE operations are permanent. Recovery typically requires restoring from a backup.
Deleting Based on Related Tables
Rows can be deleted from one table based on criteria evaluated against another table. This commonly involves using JOIN clauses within the DELETE statement to link related data. While the FROM clause may reference multiple tables, the DELETE clause specifies only the table from which rows are removed.
For instance, to remove users from the users table if their corresponding entry in prospect_users is marked inactive:
delete users
from users, prospect_users
where users.username = prospect_users.username
and NOT prospect_users.active;
This approach efficiently removes dependent data, maintaining data consistency across related tables.