Window Functions in SQL: A Complete Tutorial with Examples

Galaxy Glossary

Where can I find a tutorial on window functions with examples?

Window functions add analytical power to SQL by allowing calculations across sets of rows related to the current row without collapsing results.

Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

SQL Window Functions Tutorial

Window functions allow you to perform running totals, moving averages, rankings, gap-filling, and year-over-year comparisons—all in a single SQL query and without rewriting business logic in application code.

What Are Window Functions?

Window functions (also called analytic functions) operate on a set of rows called a window that is defined by the OVER() clause. Unlike aggregate functions that condense rows into a single output, window functions return one value for every row in the original result set while still giving you access to aggregates, rankings, or calculations over that window.

Key Characteristics

  • Partitioning – Decide which rows belong to the same group via PARTITION BY.
  • Ordering – Specify row order inside each partition with ORDER BY.
  • Framing – Optionally limit the range with ROWS BETWEEN or RANGE.
  • Non-destructive – Original rows are preserved; results are added as new columns.

Why Are Window Functions Important?

Modern analytics requires complex calculations that go beyond simple aggregation. Window functions:

  • Eliminate multi-step subqueries and self-joins, reducing query complexity.
  • Improve performance by letting the database engine process data in a single pass.
  • Enable real-time dashboards with running totals or cumulative metrics.
  • Maintain row granularity, simplifying downstream joins and BI transformations.
  • Integrate seamlessly with tools like Galaxy, whose AI copilot can auto-suggest window frames, partitions, and even explain each function inline.

Core Window Functions Explained

Aggregate Variants

SUM(), AVG(), MIN(), and MAX() can all be used as window functions. Adding OVER() transforms them from collapsing aggregates to row-aware analytics.

Ranking Functions

  • ROW_NUMBER() – unique sequential number.
  • RANK() – same rank for ties, leaving gaps.
  • DENSE_RANK() – same rank for ties, no gaps.
  • NTILE(n) – divides the partition into n buckets.

Value Functions

  • LAG() / LEAD() – access preceding or following rows.
  • FIRST_VALUE() / LAST_VALUE() – pull boundary values.
  • NTH_VALUE(expr, n) – fetch the nth row’s value.

Detailed Examples

Running Total of Orders

SELECT order_id,
order_date,
amount,
SUM(amount) OVER (ORDER BY order_date) AS running_sales
FROM orders
ORDER BY order_date;

This adds a cumulative sales column without losing individual orders.

Department-Level Salary Average

SELECT employee_id,
department,
salary,
AVG(salary) OVER (PARTITION BY department) AS avg_dept_salary
FROM employees;

Each row carries both the employee’s salary and their department’s average, enabling quick variance checks.

Year-over-Year Growth

WITH revenue AS (
SELECT date_trunc('month', created_at) AS month,
SUM(amount) AS monthly_revenue
FROM payments
GROUP BY 1)
SELECT month,
monthly_revenue,
LAG(monthly_revenue) OVER (ORDER BY month) AS last_year,
100.0 * (monthly_revenue - last_year) / last_year AS yoy_growth
FROM revenue;

Top N per Group (Keep Ties)

WITH ranked AS (
SELECT product_id,
category,
sales,
RANK() OVER (PARTITION BY category ORDER BY sales DESC) AS rnk
FROM product_sales)
SELECT *
FROM ranked
WHERE rnk <= 3; -- top 3 per category (ties included)

Best Practices

  • Index on Partition & Order Columns to speed sorting.
  • Explicit Frames – Define frames like ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for predictable behavior across databases.
  • Minimize Columns – Select only needed fields; window queries can be memory-intensive.
  • Use CTEs – Break complex logic into readable stages.
  • Leverage Tooling – Galaxy’s AI copilot surfaces frame suggestions and highlights inefficient patterns before execution.

Common Mistakes & How to Fix Them

  1. Forgetting ORDER BY in ranking functions, leading to non-deterministic results. Always specify an order column.
  2. Confusing Aggregates with Window Functions. A missing OVER() collapses rows. Add the clause to retain detail.
  3. Using LAG() without Default causes NULLs in first rows. Provide a default: LAG(x,1,0).

Galaxy-Specific Workflow

In Galaxy’s desktop SQL editor you can:

  • Type avg_sales and press Tab; the AI copilot expands a templated window function with correct partitioning.
  • Hover over ROWS BETWEEN to see an inline explanation of the frame.
  • Share the saved query in a Collection for peer endorsement, ensuring everyone reuses the same logic.

Putting It All Together

Window functions unlock advanced analytics inside the database layer, trimming data wrangling time and boosting performance. Whether you are building KPI dashboards, fraud-detection pipelines, or financial models, mastering them is a must. With a modern editor like Galaxy, discovering, writing, and sharing these queries becomes even faster and safer.

Why Window Functions in SQL: A Complete Tutorial with Examples is important

Window functions enable sophisticated analytics—running totals, rankings, YoY comparisons—without losing row-level detail or relying on complicated subqueries. They are essential for real-time dashboards, data warehouses, and feature engineering in ML pipelines. Because they push computation close to the data, they reduce latency and cost while increasing maintainability.

Window Functions in SQL: A Complete Tutorial with Examples Example Usage


SELECT *, AVG(salary) OVER (PARTITION BY department) AS avg_dept_salary FROM employees;

Common Mistakes

Frequently Asked Questions (FAQs)

What databases support window functions?

Most modern relational engines—PostgreSQL, MySQL 8+, SQL Server, Snowflake, BigQuery, Redshift, DuckDB—fully support ANSI SQL window functions.

How do window functions differ from GROUP BY aggregates?

GROUP BY collapses rows into one output per group, while window functions preserve every row and append analytical calculations as extra columns.

Can Galaxy help me write window functions?

Yes. Galaxy’s context-aware AI copilot suggests partitioning keys, auto-explains frames, and can refactor legacy queries into window-based alternatives.

Do window functions hurt performance?

They can be resource-heavy if misused. Proper indexing, selective columns, and explicit frames typically yield performant queries.

Want to learn about other SQL terms?