r/learnSQL • • Mar 12 '26

Before your next SQL interview, make sure you understand how ORDER BY behaves inside window functions!!!

/r/TheQueryLab/comments/1rrj4ul/before_your_next_sql_interview_make_sure_you/
3 Upvotes

3 comments sorted by

2

u/ComicOzzy Mar 12 '26

It should also be noted that "ROWS BETWEEN ..." can be faster than the default as well.

1

u/ogzracker16 Mar 12 '26

I did not come across this "rows between" command in training often. Are there any good videos that expand on this topic?

1

u/tlefst Mar 26 '26

Here is a sales by month table for some retail store:

MonthSalesAmt
05 March1000
06 March1500
07 March2300
08 March1200

We will calculate CumulativeSales for March:

Case-1: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW

MonthSalesAmtCumulativeSales
05 March10001000
06 March1500(1000+1500=) 2500
07 March2300(1000+1500+2300=) 4800
08 March1200(1000+1500+2300+1200=) 6000

Case-2: ROWS BETWEEN 2 PRECEDING AND CURRENT ROW

MonthSalesAmtCumulativeSales
05 March10001000
06 March1500(1000+1500=) 2500
07 March2300(1000+1500+2300=) 4800
08 March1200(1500+2300+1200=) 5000

Case-3: ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING

MonthSalesAmtCumulativeSales
05 March1000(1000+1500=) 2500
06 March1500(1000+1500+2300=) 4800
07 March2300(1500+2300+1200=) 5000
08 March1200(2300+1200=) 3500

Case-4: ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING

MonthSalesAmtCumulativeSales
05 March1000(1000+1500+2300+1200=) 6000
06 March1500(1500+2300+1200=) 5000
07 March2300(2300+1200=) 3500
08 March12001200