Chuyển đến nội dung chính
eLearner.app
Mô-đun 8 · Bài học 2 trong tổng số 430/57 trong khóa học~10 min
Bài học theo mô-đun (2/4)

Cập nhật và xóa: UPDATE và DELETE

UPDATE modifies existing rows; DELETE removes them. Both share the same, fundamental, golden rule: the WHERE clause decides which rows to touch. Forgetting it means modifying/deleting the whole table.

UPDATE

SQL
UPDATE tabella
SET    colonna1 = nuovo_valore,
       colonna2 = altra_espressione
WHERE  condizione;

Examples:

SQL
-- Aumenta del 10% i prezzi di tutti i prodotti della categoria 5 (Computer):
UPDATE products
SET    price = price * 1.10
WHERE  category_id = 5;

-- Aggiorna due colonne contemporaneamente:
UPDATE orders
SET    status     = 'shipped',
       shipped_at = NOW()
WHERE  id = 12;

SET col = espressione: the expression can reference the row's current values (price * 1.10), and can also use NOW(), NULL, or sub-queries.

DELETE

SQL
DELETE FROM tabella
WHERE  condizione;

Examples:

SQL
-- Cancella tutte le recensioni con rating < 3:
DELETE FROM reviews
WHERE  rating < 3;

-- Cancella un ordine specifico:
DELETE FROM orders WHERE id = 999;

RETURNING here too

Like INSERT, UPDATE and DELETE also accept RETURNING so you know what they acted on:

SQL
DELETE FROM reviews
WHERE  rating < 3
RETURNING id, customer_id, rating;

Useful for logging in one shot what was deleted/modified.

Foreign keys and deletion

Trying to delete a row referenced by another table through a foreign key produces an error:

SQL
DELETE FROM customers WHERE id = 1;
-- ERROR: update or delete on table "customers" violates foreign key constraint
-- on table "orders"

Solutions: delete the child rows first, or define the FK with ON DELETE CASCADE when you create the table (we'll cover this in the next DDL lesson).

Your turn

tập thể dục#sql.m8.l2.e1
Nỗ lực: 0Đang tải…

Increase by 10% the price of every product in category 5 (Computer). A single UPDATE statement.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

The expression to the right of SET can reference the column itself: price * 1.10.

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#sql.m8.l2.e2
Nỗ lực: 0Đang tải…

Delete every review with a rating lower than 3 (very negative reviews).

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

WHERE rating < 3.

Giải pháp khả dụng sau 3 lần thử