Skip to Content
Navigation:

A stick figure smiling

Here's a preview from my zine, Become a SELECT Star!! If you want to see more comics like this, sign up for my saturday comics newsletter or browse more comics!

Image of a comic. To read the full HTML alt text, click "read the transcript".

browse more comics! get the zine!
read the transcript!

A “window” is a set of rows:

name class grade
juan 1 93
lucia 1 98

(a window!)

A window can be as big as the whole table (an empty OVER() is the whole table!) or as small as just one row.

OVER() is confusing at first, so here’s an example! Let’s run this query that ranks students in each class by grade:

SELECT name, class, grade,
       ROW_NUMBER() OVER (PARTITION BY class
                         ORDER BY grade DESC)
         AS rank_in_class
FROM grades

Step 1: Assign every row a window. OVER (PARTITION BY class) means that there are 2 windows: one each for class 1 and 2.

grades:

name class grade
juan 1 93
lucia 1 98
raph 2 88
chen 2 90

(Beside this table there is an illustration of two smaller popped-out tables showing the first two rows, and the second two rows respectively)

Step 2: Run the function. We need to run ROW_NUMBER() to find each row’s rank in its window:

query output:

name class grade rank_in_class
juan 1 93 2
lucia 1 98 1
raph 2 88 2
chen 2 90 1

Saturday Morning Comics!

Want another comic like this in your email every Saturday? Sign up here!

I'll send you one of my favourite comics from my archives every Saturday.
© Julia Evans 2024 | All rights reserved (see the FAQ for notes about licensing)