Photo by Yasmina H on Unsplash
Window functions are key to writing SQL code that is both efficient and easy to understand. Knowing how they work and when to use them will unlock new ways of solving your reporting problems.
The objective of this article is to explain window functions in SQL step by step in an understandable way so that you dont need to rely on only memorizing the syntax.
Here is what we will cover:
Our dataset is simple, six rows of revenue data for two regions in the year 2023.
If we took this dataset and ran a GROUP BY sum on the revenue of each region, it would be clear what happens, right? It would result in only two remaining rows, one for each region, and then the sum of the revenues:
The way I want you to view window functions is very similar to this but, instead of reducing the number of rows, the aggregation will run in the background and the values will be added to our existing rows.
First, an example:
Notice that we dont have any GROUP BY and our dataset is left intact. And yet we were able to get the sum of all revenues. Before we go more in depth in how this worked lets just quickly talk about the full syntax before we start building up our knowledge.
The syntax goes like this:
Picking apart each section, this is what we have:
Dont stress over what each of these means yet, as it will become clear when we go over the examples. For now just know that to define a window function we will use the OVER keyword. And as we saw in the first example, thats the only requirement.
Moving to something actually useful, we will now apply a group in our function. The initial calculation will be kept to show you that we can run more than one window function at once, which means we can do different aggregations at once in the same query, without requiring sub-queries.
As said, we use the PARTITION BY to define our groups (windows) that are used by our aggregation function! So, keeping our dataset intact weve got:
Were also not restrained to a single group. Similar to GROUP BY we can partition our data on Region and Quarter, for example:
In the image we see that the only two data points for the same region and quarter got grouped together!
At this point I hope its clear how we can view this as doing a GROUP BY but in-place, without reducing the number of rows in our dataset. Of course, we dont always want that, but its not that uncommon to see queries where someone groups data and then joins it back in the original dataset, complicating what could be a single window function.
Moving on to the ORDER BY keyword. This one defines a running window function. Youve probably heard of a Running Sum once in your life, but if not, we should start with an example to make everything clear.
What happens here is that weve went, row by row, summing the revenue with all previous values. This was done following the order of the id column, but it couldve been any other column.
This specific example is not particularly useful because were summing across random months and two regions, but using what weve learned we can now find the cumulative revenue per region. We do that by applying the running sum within each group.
Take the time to make sure you understand what happened here:
Its quite interesting to notice here that when were writing these running functions we have the context of other rows. What I mean is that to get the running sum at one point, we must know the previous values for the previous rows. This becomes more obvious when we learn that we can manually chose how many rows before/after we want to aggregate on.
For this query we specified that for each row we wanted to look at one row behind and two rows ahead, so that means we get the sum of that range! Depending on the problem youre solving this can be extremely powerful as it gives you complete control on how youre grouping your data.
Finally, one last function I want to mention before we move into a harder example is the RANK function. This gets asked a lot in interviews and the logic behind it is the same as everything weve learned so far.
Just as before, we used ORDER BY to specify the order which we will walk, row by row, and PARTITION BY to specify our sub-groups.
The first column ranks each row within each region, meaning that we will have multiple rank ones in the dataset. The second calculation is the rank across all rows in the dataset.
This is a problem that shows up every now and then and to solve it on SQL it takes heavy usage of window functions. To explain this concept we will use a different dataset containing timestamps and temperature measurements. Our goal is to fill in the rows missing temperature measurements with the last measured value.
Here is what we expect to have at the end:
Before we start I just want to mention that if youre using Pandas you can solve this problem simply by running df.ffill() but if youre on SQL the problem gets a bit more tricky.
The first step to solve this is to, somehow, group the NULLs with the previous non-null value. It might not be clear how we do this but I hope its clear that this will require a running function. Meaning that its a function that will walk row by row, knowing when we hit a null value and when we hit a non-null value.
The solution is to use COUNT and, more specifically, count the values of temperature measurements. In the following query I run both a normal running count and also a count over the temperature values.
The normal_count column is useless for us, I just wanted to show what a running COUNT looked like. Our second calculation though, the group_count moves us closer to solving our problem!
Notice that this way of counting makes sure that the first value, just before the NULLs start, is counted and then, every time the function sees a null, nothing happens. This makes sure that were tagging every subsequent null with the same count we had when we stopped having measurements.
Moving on, we now need to copy over the first value that got tagged into all the other rows within that same group. Meaning that for the group 2 needs to all be filled with the value 15.0.
Can you think of a function now that we can use here? There is more than one answer for this, but, again, I hope that at least its clear that now were looking at a simple window aggregation with PARTITION BY .
We can use both FIRST_VALUE or MAX to achieve what we want. The only goal is that we get the first non-null value. Since we know that each group contains one non-null value and a bunch of null values, both of these functions work!
This example is a great way to practice window functions. If you want a similar challenge try to add two sensors and then forward fill the values with the previous reading of that sensor. Something similar to this:
Could you do it? It doesnt use anything that we havent learned here so far.
By now we know everything that we need about how window functions work in SQL, so lets just do a quick recap!
This is what weve learned:
Originally posted here:
Understand SQL Window Functions Once and For All - Towards Data Science
- Global Data Science Platform Market Report 2020 Industry Trends, Share and Size, Complete Data Analysis across the Region and Globe, Opportunities and... [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Data Science and Machine-Learning Platforms Market Size, Drivers, Potential Growth Opportunities, Competitive Landscape, Trends And Forecast To 2027 -... [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Industrial Access Control Market 2020-28 use of data science in agriculture to maximize yields and efficiency with top key players - TechnoWeekly [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- IPG Unveils New-And-Improved Copy For Data: It's Not Your Father's 'Targeting' 11/11/2020 - MediaPost Communications [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Risks and benefits of an AI revolution in medicine - Harvard Gazette [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- UTSA to break ground on $90 million School of Data Science and National Security Collaboration Center - Construction Review [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Addressing the skills shortage in data science and analytics - IT-Online [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Data Science Platform Market Research Growth by Manufacturers, Regions, Type and Application, Forecast Analysis to 2026 - Eurowire [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- 2020 AI and Data Science in Retail Industry Ongoing Market Situation with Manufacturing Opportunities: Amazon Web Services, Baidu Inc., BloomReach... [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Endowed Chair of Data Science job with Baylor University | 299439 - The Chronicle of Higher Education [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Data scientists gather 'chaos into something organized' - University of Miami [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- AI Update: Provisions in the National Defense Authorization Act Signal the Importance of AI to American Competitiveness - Lexology [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Healthcare Innovations: Predictions for 2021 Based on the Viewpoints of Analytics Thought Leaders and Industry Experts | Quantzig - Business Wire [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Poor data flows hampered governments Covid-19 response, says the Science and Technology Committee - ComputerWeekly.com [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Ilia Dub and Jasper Yip join Oliver Wyman's Asia partnership - Consultancy.asia [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Save 98% off the Complete Excel, VBA, and Data Science Certification Training Bundle - Neowin [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Data Science for Social Good Programme helps Ofsted and World Bank - India Education Diary [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Associate Professor of Fisheries Oceanography named a Cooperative Institute for the North Atlantic Region (CINAR) Fellow - UMass Dartmouth [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Rapid Insight To Host Free Webinar, Building on Data: From Raw Piles to Data Science - PR Web [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- This Is the Best Place to Buy Groceries, New Data Finds | Eat This Not That - Eat This, Not That [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Which Technology Jobs Will Require AI and Machine Learning Skills? - Dice Insights [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Companies hiring data scientists in NYC and how much they pay - Business Insider [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Calling all rock stars: hire the right data scientist talent for your business - IDG Connect [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- How Professors Can Use AI to Improve Their Teaching In Real Time - EdSurge [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- BCG GAMMA, in Collaboration with Scikit-Learn, Launches FACET, Its New Open-Source Library for Human-Explainable Artificial Intelligence - PRNewswire [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Data Science Platform Market Insights, Industry Outlook, Growing Trends and Demands 2020 to 2025 The Courier - The Courier [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- UBIX and ORS GROUP announce partnership to democratize advanced analytics and AI for small and midmarket organizations - PR Web [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Praxis Business School is launching its Post Graduate Program in Data Engineering in association with Knowledge Partners - Genpact and LatentView... [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- What's So Trendy about Knowledge Management Solutions Market That Everyone Went Crazy over It? | Bloomfire, CSC (American Productivity & Quality... [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Want to work in data? Here are 6 skills you'll need Just now - Siliconrepublic.com [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Data, AI and babies - BusinessLine [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Here's how much Amazon pays its Boston-based employees - Business Insider [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Datavant and Kythera Increase the Value Of Healthcare Data Through Expanded Data Science Platform Partnership - GlobeNewswire [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- O'Reilly Analysis Unveils Python's Growing Demand as Searches for Data Science, Cloud, and ITOps Topics Accelerate - Business Wire [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Book Review: Hands-On Exploratory Data Analysis with Python - insideBIGDATA [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- The 12 Best R Courses and Online Training to Consider for 2021 - Solutions Review [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Software AG's TrendMiner 2021.R1 Release Puts Data Science in the Hands of Operational Experts - Yahoo Finance [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- The chief data scientist: Who they are and what they do - Siliconrepublic.com [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Berkeley's data science leader dedicated to advancing diversity in computing - UC Berkeley [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Awful Earnings Aside, the Dip in Alteryx Stock Is Worth Buying - InvestorPlace [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Why Artificial Intelligence May Not Offer The Business Value You Think - CMSWire [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Getting Prices Right in 2021 - Progressive Grocer [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Labelbox raises $40 million for its data labeling and annotation tools - VentureBeat [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- How researchers are using data science to map wage theft - SmartCompany.com.au [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Ready to start coding? What you need to know about Python - TechRepublic [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Women changing the face of science in the Middle East and North Africa - The Jerusalem Post [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Mapping wage theft with data science - The Mandarin [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Data Science Platform Market 2021 Analysis Report with Highest CAGR and Major Players like || Dataiku, Bridgei2i Analytics, Feature Labs and More KSU... [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Data Science Impacting the Pharmaceutical Industry, 2020 Report: Focus on Clinical Trials - Data Science-driven Patient Selection & FDA... [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- App Annie Sets New Bar for Mobile Analytics with Data Science Innovations - PRNewswire [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Data Science and Analytics Market 2021 to Showing Impressive Growth by 2028 | Industry Trends, Share, Size, Top Key Players Analysis and Forecast... [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- How Can We Fix the Data Science Talent Shortage? Machine Learning Times - The Predictive Analytics Times [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Opinion: How to secure the best tech talent | Human Capital - Business Chief [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Following the COVID science: what the data say about the vaccine, social gatherings and travel - Chicago Sun-Times [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Automated Data Science and Machine Learning Platforms Market Technological Growth and Precise Outlook 2021- Microsoft, MathWorks, SAS, Databricks,... [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- 9 investors discuss hurdles, opportunities and the impact of cloud vendors in enterprise data lakes - TechCrunch [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Rapid Insight to Present at Data Science Salon's Healthcare, Finance, and Technology Virtual Event - PR Web [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Aunalytics Acquires Naveego to Expand Capabilities of its End-to-End Cloud-Native Data Platform to Enable True Digital Transformation for Customers -... [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Tech Careers: In-demand Courses to watch out for a Lucrative Future - Big Easy Magazine [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Willis Towers Watson enhances its human capital data science capabilities globally with the addition of the Jobable team - GlobeNewswire [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Global Data Science Platform Market 2021 Industry Insights, Drivers, Top Trends, Global Analysis And Forecast to 2027 KSU | The Sentinel Newspaper -... [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- A Comprehensive Guide to Scikit-Learn - Built In [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Industry VoicesBuilding ethical algorithms to confront biases: Lessons from Aotearoa New Zealand - FierceHealthcare [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- How Intel Employees Volunteered Their Data Science Expertise To Help Costa Rica Save Lives During the Pandemic - CSRwire.com [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Learn About Innovations in Data Science and Analytic Automation on an Upcoming Episode of the Advancements Series - Yahoo Finance [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Symposium aimed at leveraging the power of data science for promoting diversity - Penn State News [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Rochester to advance research in biological imaging through new grant - University of Rochester [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- SoftBank Joins Initiative to Train Diverse Talent in Data Science and AI - Entrepreneur [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Participating in SoftBank/ Correlation One Initiative - Miami - City of Miami [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Increasing Access to Care with the Help of Big Data | Research Blog - Duke Today [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Heres how Data Science & Business Analytics expertise can put you on the career expressway - Times of India [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Yelp data shows almost half a million new businesses opened during the pandemic - CNBC [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Postdoctoral Position in Transient and Multi-messenger Astronomy Data Science in Greenbelt, MD for University of MD Baltimore County/CRESST II -... [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- DefinedCrowd CEO Daniela Braga on the future of AI, training data, and women in tech - GeekWire [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Gartner: AI and data science to drive investment decisions rather than "gut feel" by mid-decade - TechRepublic [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Jupyter has revolutionized data science, and it started with a chance meeting between two students - TechRepublic [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Working at the intersection of data science and public policy | Penn Today - Penn Today [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- The Future of AI: Careers in Machine Learning - Southern New Hampshire University [Last Updated On: April 4th, 2021] [Originally Added On: April 4th, 2021]
- SMU meets the opportunities of the data-driven world with cutting-edge research and data science programs - The Dallas Morning News [Last Updated On: April 4th, 2021] [Originally Added On: April 4th, 2021]
- Data, Science, and Journalism in the Age of COVID - Pulitzer Center on Crisis Reporting [Last Updated On: April 4th, 2021] [Originally Added On: April 4th, 2021]