NoSQL? No, SQL! – How to Calculate Running Totals
Join the DZone community and get the full member experience.Join For Free
if anything at all, our jooq talks at various jugs and conferences have revealed mostly one thing:
java developers don’t know sql.
and it isn’t even necessarily our fault. we’re just not exposed to sql nowadays.
but consider this: we developers (or our customers) are paying millions of dollars every year to oracle, microsoft, ibm, sap for their excellent rdbms, only to ignore 90% of their database features and to perform a little bit of crud and a little bit of acid with orms like hibernate. we have forgotten about why those rdbms were so expensive in the first place. we haven’t paid attention to the various improvements to the sql standards, including sql:1999 , sql:2003 , sql:2008 , and the recent sql:2011 , which are all mostly left unsupported by jpa .
if only we java developers knew how easy and how much fun it can be to replace thousands of lines of erroneous java code with five lines of sql. don’t believe it? check this out:
promoting sql, the language
instead of simply promoting jooq, we started to help java developers appreciate actual sql, regardless of the access pattern that they’re using. because true sql can be appreciated through any of these apis:
and believe us, most developers were astonished by what was possible in sql, when they saw our nosql? no, sql! talk:
calculating a running total
so let’s delve into the essence of the talk and calculate a running total with sql. what’s a running total? it’s easy. imagine you have these bank account transaction data in your database:
you’ll notice immediately, that the balance per account transaction is missing. yes, we want to calculate that balance as such:
if we’re assuming that we know the
balance on the bank account, we can use each account transaction’s
value and subtract it from that current balance. alternatively, we could assume an initial balance of zero and add up all the
value till today. this is illustrated here:
each transaction’s balance can be calculated through either one of these formulas:
so, that’s a running total. easy, right?
but how can we do it in sql?
most of us would probably pull out a little java programme out of their sleeves, keeping all the amounts in memory, writing unit tests, fixing all sorts of bugs (we’re not mathematicians, after all), wrestling with
, etc. few of us would probably go through the hassle of doing the same in pl/sql or t-sql, or whatever other procedural language you have at disposition, and possibly update each balance directly into the table when inserting / updating new transactions.
but as you might have guessed so far, the solution we’re looking for here is a solution in sql. please bear with us as we’re going through the examples. they’re getting better and better. and if you want to play around with the examples, download oracle xe and the running-totals.sql script and get up and running!
what we’ve learned from college / sql-92 would probably involve a…
using nested select
let’s assume that we have a view like
, which already joins the accounts table to the account transactions table in order to access the
. here’s how we would write this query, then:
notice how the nested select uses row value expression predicates to express the filtering criteria. if your database doesn’t support the sql standard row value expression predicates ( and you’re not using jooq to emulate them ), you can factor them out yourself to form this equivalent query, instead:
so in essence, for any given account transaction, your nested select simply fetches the sum of all
values for account transactions that are more recent than the currently projected account transaction.
does it perform?
nope. as you can see, for the relatively simple sample data set (only 1101 records filtered from
account_id = 1
in line 9), there is an index range scan materialising a whopping total of
rows in memory. this looks like we have
complexity. i.e. a very naïve algorithm is being applied.
while you could probably tune this query slightly, we should still feel that oracle should be able to devise an
algorithm for this simple task.
using recursive sql
no one enjoys writing recursive sql. no one. let me convince you.
for simplicity, we’re assuming that we also have a
column enumerating transactions in their sort order, which can be used to simplify recursion:
ready? check out this gorgeous piece of sql!
ach… how to read this beauty?
essentially, we’re self-joining the view (common table expression) that we’re about to declare:
subselect of the
expression, we’re projecting the
of the account, only for the first
subselect of the
expression, we’re projecting the difference of the balance of the
account transaction and the
of the current account transaction.
and because we’re recursing into the
common table expression, this will continue until we reach the “last” transaction.
now let’s make an educated guess, whether this performs well…
well. it doesn’t. we get even more rows in memory, namely
rows for what should be at most
. parts of this plan are due to the fact that the
utility column is another calculated column that couldn’t be optimised by oracle. but the essence here is the fact that it is already very hard to get it
, it’s even harder to get it
using window functions
so, we’ve suffered enough. let’s hear some good news.
the best solution for this problem is this one:
essentially, we’re doing exactly the same thing as with the nested select. we’re subtracting the
values “over” the subset of rows that is:
in the same
partitionas the current row (i.e. has the same
- ordered by the same ordering criteria as the account transactions (from the outer query)
- positioned strictly before the current row in the sense of the above ordering
or, again, visually:
and now, does this perform?
it couldn’t be much faster! window functions are probably the most underestimated sql feature .
using the oracle model clause
now, this is more of a special treat for those sql nerds among you who want to piss off your fellow developers with eerie, weird-looking sql. the model clause (only available in oracle).
now, how to read this beast? we’re taking the sample data and transforming it to:
partition‘ed by the usual criteria
dimension‘ed along the sort order, i.e. the transaction row number
measure‘ed, i.e. to provide calculated values for date, amount, balance (where date and amount remain untouched, original data)
be calculated according to
rules, which define the balance of each transaction (except for the first one) to be the balance of the previous transaction minus the amount of the previous transaction
still too abstract? i know. but think about it this way:
ms excel! every time you have a problem that your project manager thinks is peanuts to solve with his fancy ms excel spreadsheets, then the model clause is your friend!
and does it perform?
… pretty much so (although the above shouldn’t be confused with an actual benchmark).
if you haven’t seen enough, see another great use-case for the model clause here . and for all the details, consider reading oracle’s official model clause whitepaper
do it yourself
did you like the above examples? don’t worry. when you’ve seen these things for the first time, they can be pretty confusing. but in essence, they’re really not that complicated. and once you have those features in your tool-chain, you will be indefinitely more productive than if you had to write out all those algorithms in an imperative programming language.
at data geekery , we always say:
sql is a device whose mystery is only exceeded by its power
and sometimes, we also quote winston churchill for having said something along the lines of:
indeed, as the model clause has shown us, sql can become very extreme. but once you know the tricks and expressions (and most importantly, window functions ), you’ll be incredibly more productive with sql than with many other technologies, if the task at hand is a bulk calculation operation on a simple or complex data set. and your query is often faster than if you had hand-written it, at least when you’re using a decent database.
so let’s put sql to action in our software!
Published at DZone with permission of Lukas Eder, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.