মূল কন্টেন্টে যান
eLearner.app
মডিউল 8 · 2-এর পাঠ 4কোর্সে 30/57~10 min
মডিউল পাঠ (2/4)

আপডেট করা এবং মুছে ফেলা: আপডেট এবং মুছে ফেলুন

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

ব্যায়াম#sql.m8.l2.e1
প্রচেষ্টা: 0লোড হচ্ছে...

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

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

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

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

Review exercise

ব্যায়াম#sql.m8.l2.e2
প্রচেষ্টা: 0লোড হচ্ছে...

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

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

WHERE rating < 3.

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ