All checks were successful
learn org at code.softwareshinobi.com/databases.softwareshinobi.com/pipeline/head This commit looks good
51 lines
1.7 KiB
Markdown
51 lines
1.7 KiB
Markdown
# 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.
|
|
|
|
```sql
|
|
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.
|
|
|
|
```sql
|
|
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:
|
|
|
|
```sql
|
|
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.
|