⚡️ 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.
#SQL #PostgreSQL #Database
17 · 2.2K · Ветка⚡️ SQL-задача с опасным подвохом
5 сообщений · –К A Not, is one experiment. Your responded is intuition, but the true is that is only clean space. 😅 This is possible to be correct in other software, for example: > I use to SQLlibrary in Cpp, is possible add new command and possibly one return. Formally it is combinations of SQL library + program. > If one program was builder with 10 library, the 11° that you find, not is understand. So, sql is: 10 library. (Remember, one "Application or Program in your device not is eternal")