Skip to main content
Practice

Introduction to Window Functions

Window functions add a new layer of power to SQL by letting you calculate values across a set of rows related to the current row, without collapsing them into a single output.

Unlike aggregation functions that group rows together, window functions preserve the individual rows while adding new calculated columns like ranks, running totals, or differences.


Why Window Functions?

Traditional SQL can be limiting when you need to compare or rank rows while still keeping them in view. Window functions allow you to:

  • Assign ranks or row numbers within groups
  • Compare a row to its neighbors
  • Compute running totals or moving averages
  • Access previous or next row values

This is especially useful in analytics, reporting, and dashboards where row-level context matters.


Window Functions vs Aggregates

Consider this question:

"What is each student's grade and how does it compare to the class average?"

A regular GROUP BY query would give the average per class, but not retain individual student records. A window function lets you show both the student's grade and the class average in the same row.


The OVER Clause

Window functions use the OVER clause to define the scope of the “window” — the set of rows the function should consider.

It can include:

  • PARTITION BY — to restart the calculation for each group (like a department or course)
  • ORDER BY — to define sequence for calculations like rankings or running totals

Check out the slide deck on the right to explore syntax and real-world examples like RANK(), ROW_NUMBER(), and how the OVER() clause shapes their behavior.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.