Skip to main content

On Par with Window Functions

Use golf analogy when explaining to executives.                                Use a car analogy for all others.  — Confucius.



The purpose of window functions is to translate the business reporting requirements declaratively and effectively to SQL so query performance and developer/business-analyst efficiency improve dramatically. I’ve seen real-world reports and dashboards go from hours to minutes, minutes to seconds after using window functions.  Query size decreases from 40-pages to a few pages. Back in the ‘90s, Redbrick database really understood the business use case and created a new layer of functionality to do business reporting that included ranking, running totals, calculating commissions & inventory based on subgroups, positions, etc. These have been in SQL standard in 2003.  Every BI layer (like Tableau, Looker, Cognos) exploits this functionality.
Introduction to Window Functions
Imagine you have scores of six golfers through two rounds. Now, you need to create the leaderboard and rank them. Rank them using SQL.
PlayerRound1Round2
Marco7573
Johan7268
Chang6776
Isha7471
Sitaram6872
Bingjie7167
Insert the data into Couchbase.
INSERT INTO golf 
VALUES("KP1", {"player": "Marco", "round1":75, "round2":73}),
VALUES("KP2", {"player": "Johan", "round1":72, "round2":68}),
VALUES("KP3", {"player": "Chang", "round1":67, "round2":76}),
VALUES("KP4", {"player": "Isha", "round1":74, "round2":71}),
VALUES("KP5", {"player": "Sitaram", "round1":68, "round2":72}),
VALUES("KP6", {"player": "Bingjie", "round1":71, "round2":67});

WITHOUT window functions (current state – Couchbase 6.0)
To write the query without the use of window functions, you need a subquery to calculate the rank for each player.  This subquery has to scan through all of the data resulting in the worst algorithmic complexity of O(N^2), which dramatically increases the execution time and throughput.
WITH g1 as (select player, round1, round2 from golf)
SELECT    g3.player                                AS player,
          (g3.round1+g3.round2)                    AS T,
          ((g3.round1+g3.round2) - 144)            AS ToPar, 
          (select raw 1+COUNT(*) 
             from g1 as g2 
               where (g2.round1 + g2.round2) < 
                     (g3.round1 + g3.round2))[0]   AS sqlrankR2
FROM g1 as g3
ORDER BY sqlrankR2
Results: 
T ToPar player sqlrankR2
138 -6 "Bingjie"    1
140 -4 "Johan"      2
140 -4 "Sitaram"    2
143 -1 "Chang"      4
145 1 "Isha"        5
148 4 "Marco"       6

With window functions in Mad-Hatter (upcoming release)
This query returns player, total after two rounds (T), how of the score is over/under par (ToPar) and then ranks them based on the scores of first two rounds.  This is the NEW functionality in Mad-Hatter. The time complexity of this is O(N), meaning execution time will only increase linearly.  
SELECT    player                                AS player,
          (round1+round2)                       AS T,
          ((round1+round2) - 144)               AS ToPar,
          RANK() OVER(ORDER BY (round1+round2)) AS rankR2
FROM golf;
T ToPar player    rankR2
138 -6 "Bingjie"    1
140 -4 "Johan"      2
140 -4 "Sitaram"    2
143 -1 "Chang"      4
145 1  "Isha"       5
148 4  "Marco"      6
Observations:
  1. The query expresses the requirements simply and clearly.
  2. Performance of this query in a real-world scenario is much better.  We plan to measure.
  3. When the ranking requirements depend on multiple documents,  the query becomes quite complex — to write, optimize and run.
  4. All this affects the TCO overall.
Now, let’s create an expanded dashboard.
Show add dense rank, row number, who’s ahead, and the number of strokes behind the leader.  All very common things in a reporting resituation. You’re seeing the new window function whenever you see the OVER() clause.  The query below has six window functions.
SELECT    player                                AS player,
          (round1+round2)                       AS T,
          ((round1+round2) - 144)               AS ToPar,
          RANK() OVER(ORDER BY (round1+round2)) AS rankR2,
          DENSE_RANK() OVER (ORDER BY (round1+round2)) AS rankR2Dense,
          ROW_NUMBER() OVER() rownum,
          ((round1+round2) - 
              FIRST_VALUE(round1+round2) 
                OVER(ORDER BY (round1+round2))) AS strokesbehind,
          RANK() OVER(ORDER BY (round1))        AS rankR1,
          LAG(player, 1, "None") OVER(ORDER BY round1+round2) 
                                                AS inFront
FROM golf
ORDER BY rankR2
T ToPar inFront   player    rankR1  rankR2 rankR2Dense rownum strokesbehind
138 -6 "None"    "Bingjie"    3     1        1          3      0
140 -4 "Johan"   "Sitaram"    2     2        2          2      2
140 -4 "Bingjie" "Johan"      4     2        2          4      2
143 -1 "Sitaram" "Chang"      1     4        3          1      5
145 1 "Chang"  "Isha"         5     5        4          5      7
148 4 "Isha"   "Marco"        6     6        5          6     10
As you saw earlier, doing this query with six window functions using subquery method will be a larger effort, expensive, error-prone query.
In addition to making the built-in aggregates (COUNT, SUM, AVG, etc) as window functions, the upcoming release will have the following window functions.  The syntax and semantics of each of them are well defined in the standard and well described in the articles of the reference section below.
RANK()
DENSE_RANK()
PERCENT_RANK()
CUME_DIST()
NTILE()
RATIO_TO_REPORT()
ROW_NUMBER()
LAG()
FIRST_VALUE()
LAST_VALUE()
NTH_VALUE()
LEAD()
References:
  1. Probably the Coolest SQL Feature: Window Functions. https://blog.jooq.org/2013/11/03/probably-the-coolest-sql-feature-window-functions/
  2. A Window into the World of Analytic Functions. https://blogs.oracle.com/oraclemagazine/a-window-into-the-world-of-analytic-functions
  3. Oracle Reference: https://docs.oracle.com/cd/E11882_01/server.112/e41084/functions004.htm#SQLRF06174

Comments

Popular posts from this blog

Swami Vivekananda: The Monk That Nobody Sent to Chicago

  There’s a saying in Chicago: “We don’t want nobody that nobody sent.” This was the cold reception Swami Vivekananda faced when he arrived in the windy city in July 1893, determined to attend the World Parliament of Religions that September. He belonged to no organization, carried no letter of recommendation, his countrymen were nobody, and represented an alien religion to the Western world. As the days passed, his hope of attending the parliament dwindled. With money running out and the odds stacked against him, he left the Windy City and went to Boston, praying for a glimmer of opportunity.  Swamiji came to America to share India’s most profound gift: the wisdom of the Hindu sages, preserved through centuries of oral tradition and embodied by its monks. This was 1893, not 1993—India was under the British grip, its resources drained, and its spirit subdued. Swamiji’s mission was not just a cultural exchange; it was a bold step toward envisioning a future where India could re...

Why Should Databases Go Natural?

From search to CRM, applications are adopting natural language and intuitive interactions. Should databases follow? This article provides a strategic perspective. Amid the many technological evolutions in software and hardware (CISC/RISC, Internet, Cloud, and AI), one technology has endured:  Relational Database Systems   (RDBMS), aka SQL databases. For over 50 years, RDBMS has survived and thrived, overcoming many challenges. It has evolved and adopted beneficial features from emerging technologies like object-relational databases and now competes robustly with   NoSQL databases .  Today, RDBMS dominates the market, with four of the top five databases and seven of the top ten being relational. RDBMS has smartly borrowed ideas, like JSON support, from NoSQL, while NoSQL has also borrowed from RDBMS. NoSQL no longer rejects SQL. From a user perspective, all modern databases have SQL-inspired query language and a set of APIs. All applications manage the respective data...

iQ Interactive: Cool Things for Developers on Couchbase Capella iQ

  The landscape of software development is ever-evolving with the advent of new technologies. As we venture into 2023, natural language processing ( NLP ) is rapidly emerging as a pivotal aspect of programming. Unlike previous generations of tools that primarily aimed at enhancing coding productivity and code quality, the new generation of Artificial Intelligence ( GenAI ) tools, like iQ, is set to revolutionize every facet of a developer's workflow. This encompasses a wide range of activities: Reading, writing, and rewriting specifications Designing, prototyping, and coding Reviewing, refactoring, and verifying software Going through the iterative cycle of deploying, debugging, and improving the software Create a draft schema and sample data for any use case Natural language queries. Generate sample queries on a given dataset Fix the syntax error for a query Don't stop here. Let your imagination fly. Although the insights garnered from iQ are preliminary and should be treated ...