Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Trending in AI
Hot
Agentic AI EngineerForward-Deployed EngineerGenAI EngineerAI Architect
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Start free
Detect Row-by-Row Balance Changes
00:00
5 left

Detect Row-by-Row Balance Changes

MediumSQL · PostgreSQL

Problem

You are given account transactions and need to produce a row-by-row balance audit for each account. Write a PostgreSQL query that shows each transaction with the prior balance, the balance change from the previous row, and the running balance after the transaction. The logic must work across records in timestamp order, so this is a good test of how you handle row-dependent calculations.

Output details

  • Return columns in this order: account_id, transaction_id, transaction_ts, amount, prior_balance, balance_change, running_balance.
  • Sort ascending by account_id, then transaction_ts, then transaction_id, using transaction_id to break timestamp ties.
  • Treat NULL amount as zero when calculating running_balance and balance_change.
  • Set the first row's prior_balance and balance_change to NULL; otherwise calculate balance_change as prior_balance minus twice the non-NULL amount.

Schema

account_transactions
ColumnTypeDescription
transaction_idPKINTPrimary key for the transaction
account_idINTAccount identifier
transaction_tsTIMESTAMPTransaction timestamp used for sequencing
transaction_typeVARCHAR(20)Transaction category such as deposit or withdrawal
amountNUMERIC(12,2)Signed amount applied to the account
noteTEXTOptional note or reason for the transaction
Tablesaccount_transactions
Interviewer

Whenever you're ready, walk me through your approach or go straight to the code. The requirements and the one table are in the Question tab.

Sign up free to run or submit. Log in
CodePostgreSQL
Sign up free to run your code. Your draft is saved.Run with a free accountLog inLn 1
Run your query to see results here.