Asosiy matnga o'tish
ITIT Interview
SQL

Ma'lumotni o'zgartirish

INSERT, UPDATE, DELETE, RETURNING, upsert (ON CONFLICT), JOIN bilan yangilash, DELETE, TRUNCATE va DROP farqi, soft delete.

O'rganildi: 0 / 4
Progress

Bu nima?

DML buyruqlari jadvaldagi ma'lumotni o'zgartiradi: INSERT qo'shadi, UPDATE yangilaydi, DELETE o'chiradi.

INSERT

INSERT INTO users (name, email, city)
VALUES ('Ali', 'ali@example.com', 'Toshkent');

-- Bir nechta qator bitta so'rovda (alohida so'rovlardan ancha tez)
INSERT INTO products (name, category, price) VALUES
  ('Telefon', 'phone', 3500000),
  ('Noutbuk', 'laptop', 9000000);

-- Boshqa so'rov natijasidan
INSERT INTO archived_orders SELECT * FROM orders WHERE created_at < '2025-01-01';

-- Yaratilgan qatorni qaytarish (PostgreSQL)
INSERT INTO users (name, email) VALUES ('Vali', 'vali@example.com')
RETURNING id, created_at;

UPDATE

UPDATE products SET price = price * 0.9 WHERE category = 'phone';

UPDATE orders SET status = 'paid', paid_at = now()
WHERE id = 42
RETURNING *;

-- Boshqa jadval ma'lumoti bilan (PostgreSQL)
UPDATE orders o
SET status = 'blocked'
FROM users u
WHERE u.id = o.user_id AND u.is_blocked = true;

WHERE siz UPDATE yoki DELETE jadvaldagi barcha qatorlarni o'zgartiradi. Avval xuddi shu WHERE bilan SELECT qilib tekshiring yoki amalni tranzaksiya ichida bajaring.

DELETE

DELETE FROM orders WHERE status = 'cancelled' AND created_at < now() - interval '1 year';

Soft delete

Ko'p ilovalarda ma'lumot haqiqatda o'chirilmaydi, faqat belgilanadi:

ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP;
UPDATE users SET deleted_at = now() WHERE id = 7;
SELECT * FROM users WHERE deleted_at IS NULL;

Afzalligi: tiklash mumkin, tarix saqlanadi. Kamchiligi: har bir so'rovga shart qo'shish kerak va UNIQUE cheklovlar murakkablashadi.

Upsert

Qator bo'lsa yangilash, bo'lmasa qo'shish:

INSERT INTO cart_items (user_id, product_id, quantity)
VALUES (1, 10, 2)
ON CONFLICT (user_id, product_id)
DO UPDATE SET quantity = cart_items.quantity + EXCLUDED.quantity;

INSERT INTO tags (name) VALUES ('sql') ON CONFLICT (name) DO NOTHING;

MySQL'da: INSERT ... ON DUPLICATE KEY UPDATE. Standart SQL'da: MERGE.

DELETE, TRUNCATE va DROP

DELETETRUNCATEDROP
Nima o'chadiTanlangan qatorlarBarcha qatorlarJadvalning o'zi
WHEREBorYo'qYo'q
TezlikQatorma-qator, sekinJuda tezJuda tez
Trigger'larIshlaydiIshlamaydi—
TuzilmaQoladiQoladiO'chadi

PostgreSQL'da TRUNCATE ham tranzaksiya ichida qaytarilishi mumkin, ba'zi bazalarda esa yo'q.

Intervyu savollari

Ushbu sahifada