CREATE TABLE account (
account_id VARCHAR(36) NOT NULL PRIMARY KEY, -- uuid
account_name VARCHAR(255) NOT NULL
);
CREATE TABLE `transaction` (
transaction_id VARCHAR(36) NOT NULL PRIMARY KEY, -- uuid
transaction_timestamp BIGINT NOT NULL,
account_debit_id VARCHAR(36) NOT NULL,
account_credit_id VARCHAR(36) NOT NULL,
transaction_amount DECIMAL(10,2) NOT NULL,
FOREIGN KEY (account_debit_id) REFERENCES account(account_id),
FOREIGN KEY (account_credit_id) REFERENCES account(account_id)
);
CREATE TABLE balance_event (
balance_event_id VARCHAR(36) NOT NULL PRIMARY KEY, -- uuid
transaction_id VARCHAR(36) NOT NULL,
account_id VARCHAR(36) NOT NULL,
account_balance DECIMAL(10,2) NOT NULL,
FOREIGN KEY (transaction_id) REFERENCES `transaction`(transaction_id),
FOREIGN KEY (account_id) REFERENCES account(account_id)
);
balance_event
is used to keep track of the balance of every account; the table records the events when the balance of an account is changed as a result of some transaction. This way, getting the account balance doesn't require traversing and summing all the thousands of transactions, and also the history of the account balance is kept.
I want to describe a query that gives me all rows from the account
table, together with their corresponding account_balance
taken from balance_event
. I'm testing the code in an online SQL editor that happens to use MySQL, but I seek a query supported by PostgreSQL.
I've tried many different approaches, none of which work for different reasons. Some of the queries don't work because ONLY_FULL_GROUP_BY
is on; if possible, I'd like to keep it that way.