KenSmooth
PRO
2 weeks ago
Kensmoothcountry asked

What is ROWS BETWEEN if it's not a window function?

Sudip Bhandari
Expert
2 weeks ago

Hi there! ROWS BETWEEN can be a bit confusing at first, so let’s break it down together.

First, ROWS BETWEEN is not actually a window function itself. Instead, it's a clause used inside a window function to define which rows should be considered for the calculation. It's like setting the boundaries or frame for your data analysis.

When you see the code

AVG(closing_price) OVER (
    ORDER BY date
    ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
)

The part "ROWS BETWEEN 6 PRECEDING AND CURRENT ROW" tells SQL to calculate the average of the current row and the past six rows, effectively allowing us to compute a 7-day moving average.

By specifying these boundaries, SQL knows how far back or forward to look from each row in the dataset when performing the calculation.

Hope this helps make things clearer! Feel free to ask if you have any more questions.

SQL
This question was asked as part of the Learn SQL Basics course.