Loading image…
🔥 SQL-задача с опасным подвохом

Какой баланс получит аккаунт после выполнения запроса в PostgreSQL?

CREATE TABLE accounts (
id int PRIMARY KEY,
balance int
);

CREATE TABLE operations (
account_id int,
amount int
);

INSERT INTO accounts VALUES (1, 100);
INSERT INTO operations VALUES
(1, 10),
(1, 20);

UPDATE accounts a
SET balance = a.balance + o.amount
FROM operations o
WHERE o.account_id = a.id;


Многие ответят 130, но PostgreSQL обновит строку только один раз.

Результатом может стать 110 или 120. Если целевая строка соединяется с несколькими строками из FROM, PostgreSQL использует одну из них, но какую именно, не гарантируется.

➡️ Правильный вариант:

UPDATE accounts a
SET balance = a.balance + x.total
FROM (
SELECT account_id, SUM(amount) AS total
FROM operations
GROUP BY account_id
) x
WHERE x.account_id = a.id;


Теперь каждой строке accounts соответствует ровно одна строка источника, а баланс станет 130.
Views: 221
Open in MAX Report an inaccuracy

Report an inaccuracy

Describe what needs fixing. If you have a source, add a link.

You are leaving datool.ru

The link leads to an external website. datool.ru is not responsible for its content — check the address before entering passwords or payment details.

Redirecting in 10 s

Go