Lesson 9 of 13 · 26 min

Account balances and activity

By the end of this lesson you can calculate the balance of bank accounts at a date, aggregate balances by product or region, compute running and lowest balances with window functions, and identify inactive accounts from their last transaction.

The bank dataset belongs to Rawabi Bank, a fictional Saudi retail bank. accounts holds each account with its opening_balance on 2024-01-01; transactions holds every posting from then to the end of 2025.

Two conventions matter more than anything else here:

  • amount is always positive. direction says which way money moved from the customer's point of view: credit = into the account, debit = out of it. The signed amount is CASE WHEN direction = 'credit' THEN amount ELSE -amount END.
  • Balance at time t = opening_balance + signed transactions with posted_at <= t. Nothing is stored: the balance is derived.

Credit cards and personal finance accounts carry negative balances: they show what the customer owes. A card purchase is a debit (the balance goes further negative), a repayment a credit.

Notice that this is the bank's customer view. In the general ledger of the previous lessons, a debit to cash increased it; here a debit to a customer's account decreases it, because for the bank a customer deposit is a liability. Always check which perspective a dataset uses before you sign anything.

Included with a Formula Quest membership

This lesson, its 4 graded exercises and every other Members lesson in SQL Quest come with a Formula Quest membership that includes SQL (Single Quest with SQL selected, Quest Trio including SQL, or Quest Unlimited), or with SQL access from your organization.

Free to everyone: all of SQL Foundations and Retrieving and Filtering Data, the first lesson of every track, the playground, the dataset library and the SQL reference. See free lessons