SQL Window Frames Tutorial 🎯

beginner
23 min

SQL Window Frames Tutorial 🎯

Welcome to our SQL Window Frames tutorial! Today, we'll delve into this powerful SQL feature that lets you manipulate and analyze data across multiple rows. This knowledge will be invaluable in making your SQL queries more dynamic and informative.

What are SQL Window Functions? 📝

Window functions are SQL functions that let you perform calculations on a set of rows, instead of just individual rows. They help you compare current row's values with rows before or after it, making your queries more sophisticated.

Understanding SQL Window Frames 💡

A Window Frame defines the set of rows that are considered for a window function. There are three types of window frames:

  1. Rows Between Unbounded Preceding and Current Row (UNBOUNDED PRECEDING AND CURRENT ROW)

    This frame includes all rows before the current row.

  2. Rows Between Current Row and Unbounded Following (CURRENT ROW AND UNBOUNDED FOLLOWING)

    This frame includes all rows after the current row.

  3. Rows Between Specific Rows

    This frame includes a specific number of rows before and after the current row.

Now that we've defined the window frames, let's write some SQL queries to see them in action!

Practical Example ✅

Let's consider a simple table, Sales, with columns id, product_id, quantity, sale_price, and sale_date.

sql
CREATE TABLE Sales ( id INT PRIMARY KEY, product_id INT, quantity INT, sale_price DECIMAL(5, 2), sale_date DATE );

Example 1: Rows Between Unbounded Preceding and Current Row

sql
SELECT product_id, quantity, sale_price, SUM(quantity) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS total_sold FROM Sales ORDER BY sale_date;

In this example, we calculate the total quantity sold for each product up to the current row.

Example 2: Rows Between Current Row and Unbounded Following

sql
SELECT product_id, quantity, sale_price, SUM(quantity) OVER (ORDER BY sale_date ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS total_remaining_to_sell FROM Sales ORDER BY sale_date;

In this example, we calculate the total quantity remaining to sell for each product starting from the current row.

Quiz Time! 🎯

Question: Which window frame includes all rows before the current row?

A: Rows Between Current Row and Unbounded Following B: Rows Between Unbounded Preceding and Current Row C: Rows Between Specific Rows

Correct: B Explanation: The "Rows Between Unbounded Preceding and Current Row" frame includes all rows before the current row.


Stay tuned for the next part of our SQL Window Frames tutorial, where we'll dive deeper into various window functions and real-world applications!