Files
databases.softwareshinobi.com/landing/docs/SQL-101/009-update.md

93 lines
3.0 KiB
Markdown
Raw Normal View History

2025-06-19 13:04:08 -04:00
# UPDATE
The `UPDATE` statement modifies existing data within a database table. Utilize this for atomic data changes based on specified criteria, ensuring data accuracy in application workflows.
Update syntax:
```sql
UPDATE users SET username='software shinobi' WHERE id=1;
```
## Syntax breakdown:
* `UPDATE users`: Identifies the target table (`users`) for the modification.
* `SET username='software shinobi'`: Specifies the column (`username`) to update and its new value.
* `WHERE id=1`: Filters which rows are affected. Only the row where `id` equals `1` will be updated.
**Critical Impact:** Omitting the `WHERE` clause updates *every* row in the table. This operation is destructive; confirm intent before executing an `UPDATE` without a filter.
## Update Multiple Rows
Consider a `users` table state prior to updates:
| id | username | about |
| :-- | :------------ | :---- |
| 2 | shinobi | NULL |
| 3 | java team six | NULL |
| 4 | tony | NULL |
| 5 | shinobi | NULL |
| 6 | java team six | NULL |
| 7 | tony | NULL |
Update all rows in the `about` column:
```sql
UPDATE users SET about='404 bio not found';
```
This query affects all six rows:
```
Query OK, 6 rows affected (0 .02 sec)
Rows matched: 6 Changed: 6 Warnings: 0
```
`users` table state after updating all rows:
| id | username | about |
| :-- | :------------ | :---------------- |
| 2 | shinobi | 404 bio not found |
| 3 | java team six | 404 bio not found |
| 4 | tony | 404 bio not found |
| 5 | shinobi | 404 bio not found |
| 6 | java team six | 404 bio not found |
| 7 | tony | 404 bio not found |
## Update Specific Row
To update only a specific row, use the `WHERE` clause. Update the `about` column for the user with `id` 2:
```sql
UPDATE users SET about ='Hello World :)' WHERE id=2;
```
This targets a single row:
```
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
```
`users` table state after updating a single row:
| id | username | about |
| :-- | :------------ | :---------------- |
| 2 | shinobi | Hello World :) |
| 3 | java team six | 404 bio not found |
| 4 | tony | 404 bio not found |
| 5 | shinobi | 404 bio not found |
| 6 | java team six | 404 bio not found |
| 7 | tony | 404 bio not found |
## Updating Records Using Another Table
Modify records in one table based on data from another table. This is achieved by joining or listing the tables involved in the `UPDATE` statement and specifying the join condition in the `WHERE` clause.
Update the `about ` field in the `users` table using corresponding data from the `prospect_users` table where usernames match:
```sql
update users, prospect_users
set users.about = prospect_users.about
where prospect_users.username = users.username;
```