iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐬

Window Functions

に公開

This is an article for Day 11 of the MySQL Advent Calendar.

https://qiita.com/advent-calendar/2022/mysql


Having grown up in the "MySQL village," I didn't know much about window functions, but I recently had to use them at work, so I'm writing this down as a note. By the way, we use PostgreSQL at my company.

Window functions became available in MySQL starting from version 8.0, but PostgreSQL has supported them since version 8.4.
PostgreSQL 8.4 was released in 2009, while MySQL 8.0 was released in 2018, so support arrived about 9 years later.

My rough understanding is that window functions are like GROUP BY, but instead of collapsing the grouped records into one, they add a window function column to each individual record.

The evaluation order when combining GROUP BY and window functions was a bit confusing, but it's probably something like this:

Table
  ↓
WHERE
  ↓
Regular expressions and functions written in SELECT
  ↓
GROUP BY (Aggregate functions)
  ↓
HAVING
  ↓
Window functions ★
  ↓
DISTINCT
  ↓
ORDER BY
  ↓
LIMIT

Assuming we have a table like this (it's not normalized at all, and the table and column names are just placeholders), [1]

mysql> SELECT * FROM city ORDER BY city_code;
+-----------+--------------+-----------+--------------------------+------+----------+------------+---------+
| pref_code | pref_name    | city_code | city_name                | type | pop_male | pop_female | area    |
+-----------+--------------+-----------+--------------------------+------+----------+------------+---------+
|         1 | 北海道       |      1000 | 北海道                   | a    |  2465088 |    2759526 | 83424.4 |
|         1 | 北海道       |      1100 | 札幌市                   | 1    |   918682 |    1054713 | 1121.26 |
|         1 | 北海道       |      1101 | 札幌市中央区             | 0    |   112853 |     135827 |   46.42 |
|         1 | 北海道       |      1102 | 札幌市北区               | 0    |   136596 |     152727 |   63.57 |
|         1 | 北海道       |      1103 | 札幌市東区               | 0    |   126023 |     139356 |   56.97 |
|         1 | 北海道       |      1104 | 札幌市白石区             | 0    |   100062 |     111773 |   34.47 |
〜〜
|        47 | 沖縄県       |     47360 | 伊名村                 | 3    |      718 |        604 |   15.43 |
|        47 | 沖縄県       |     47361 | 久米島町                 | 3    |     3823 |       3369 |   63.65 |
|        47 | 沖縄県       |     47362 | 八重瀬町                 | 3    |    15244 |      15697 |   26.96 |
|        47 | 沖縄県       |     47375 | 多良間村                 | 3    |      575 |        483 |      22 |
|        47 | 沖縄県       |     47381 | 竹富町                   | 3    |     2033 |       1909 |   334.4 |
|        47 | 沖縄県       |     47382 | 与那国町                 | 3    |      923 |        753 |    28.9 |
+-----------+--------------+-----------+--------------------------+------+----------+------------+---------+
1964 rows in set (0.00 sec)

Let's try ranking them in descending order of population using RANK().

mysql> SELECT city_name, pop_male+pop_female 人口,
    -> RANK() OVER(ORDER BY pop_male+pop_female desc) 順位 FROM city
    -> ORDER BY 順位;
+--------------------------+----------+--------+
| city_name                | 人口     | 順位   |
+--------------------------+----------+--------+
| 東京都                   | 14047594 |      1 |
| 特別区部                 |  9733276 |      2 |
| 神奈川県                 |  9237337 |      3 |
| 大阪府                   |  8837685 |      4 |
| 愛知県                   |  7542415 |      5 |
| 埼玉県                   |  7344765 |      6 |
| 千葉県                   |  6284480 |      7 |
| 兵庫県                   |  5465002 |      8 |
| 北海道                   |  5224614 |      9 |
| 福岡県                   |  5135214 |     10 |
| 横浜市                   |  3777491 |     11 |
| 静岡県                   |  3633202 |     12 |
〜〜

Setting aside the 23 wards of Tokyo (Special Ward area), I realized Yokohama City also has a fairly large population...

If I try to filter by WHERE to see the rank of Nagano Prefecture here, it won't work. This is because window functions are evaluated after the WHERE clause.

mysql> SELECT city_name, pop_male+pop_female 人口,
    -> RANK() OVER(ORDER BY pop_male+pop_female desc) 順位 FROM city
    -> WHERE city_name='長野県';
+-----------+---------+--------+
| city_name | 人口    | 順位   |
+-----------+---------+--------+
| 長野県    | 2048011 |      1 |
+-----------+---------+--------+

It's the same even if you use GROUP BY HAVING. This is because window functions are evaluated after GROUP BY.

mysql> SELECT city_name, pop_male+pop_female 人口,
    -> RANK() OVER(ORDER BY pop_male+pop_female desc) 順位 FROM city
    -> GROUP BY city_name, 人口 HAVING city_name='長野県';
+-----------+---------+--------+
| city_name | 人口    | 順位   |
+-----------+---------+--------+
| 長野県    | 2048011 |      1 |
+-----------+---------+--------+

In cases like this, I guess using a subquery is the only way.

mysql> SELECT * FROM (
    ->   SELECT city_name, pop_male+pop_female 人口,
    ->   RANK() OVER(ORDER BY pop_male+pop_female desc) 順位 FROM city
    -> ) t WHERE city_name='長野県';
+-----------+---------+--------+
| city_name | 人口    | 順位   |
+-----------+---------+--------+
| 長野県    | 2048011 |     20 |
+-----------+---------+--------+

Even if it's not a function specifically designed for window functions like RANK(), regular aggregate functions also work as window functions when you add OVER.

You can get the number of municipalities in each prefecture using GROUP BY like this:

mysql> SELECT pref_name, COUNT(*) 市町村数
    -> FROM city
    -> WHERE type IN ('1','2','3')
    -> GROUP BY pref_name, pref_code ORDER BY pref_code;
+--------------+--------------+
| pref_name    | 市町村数     |
+--------------+--------------+
| 北海道       |          179 |
| 青森県       |           40 |
| 岩手県       |           33 |
| 宮城県       |           35 |
| 秋田県       |           25 |
| 山形県       |           35 |
〜〜
| 長崎県       |           21 |
| 熊本県       |           45 |
| 大分県       |           18 |
| 宮崎県       |           26 |
| 鹿児島県     |           43 |
| 沖縄県       |           41 |
+--------------+--------------+

Let's try doing something similar with a window function.

mysql> SELECT pref_name,
    -> COUNT(*) OVER(PARTITION BY pref_name) 市町村数
    -> FROM city
    -> WHERE type IN ('1','2','3')
    -> ORDER BY pref_code;
+--------------+--------------+
| pref_name    | 市町村数     |
+--------------+--------------+
| 北海道       |          179 |
| 北海道       |          179 |
| 北海道       |          179 |
| 北海道       |          179 |
| 北海道       |          179 |
| 北海道       |          179 |
〜〜
| 沖縄県       |           41 |
| 沖縄県       |           41 |
| 沖縄県       |           41 |
| 沖縄県       |           41 |
| 沖縄県       |           41 |
| 沖縄県       |           41 |
+--------------+--------------+

If you apply DISTINCT to this, it yields the same result as GROUP BY.
(When combining DISTINCT and ORDER BY, the column specified in ORDER BY must be included in the SELECT list, so I've added it.)

mysql> SELECT DISTINCT pref_code, pref_name,
    -> COUNT(*) OVER(PARTITION BY pref_name) 市町村
    -> FROM city
    -> WHERE type IN ('1','2','3')
    -> ORDER BY pref_code;
+-----------+--------------+-----------+
| pref_code | pref_name    | 市町村    |
+-----------+--------------+-----------+
|         1 | 北海道       |       179 |
|         2 | 青森県       |        40 |
|         3 | 岩手県       |        33 |
|         4 | 宮城県       |        35 |
|         5 | 秋田県       |        25 |
|         6 | 山形県       |        35 |
〜〜

Whether an aggregate function can be used as a window function seems to depend on the function; for example, COUNT(DISTINCT *) OVER() doesn't work. This is the same for PostgreSQL.

MySQL:

mysql> SELECT COUNT(DISTINCT pref_name) OVER() FROM city;
ERROR 1235 (42000): This version of MySQL doesn't yet support '<window function>(DISTINCT ..)'

PostgreSQL:

test=# SELECT count(DISTINCT pref_name) over() FROM city;
ERROR:  DISTINCT is not implemented for window functions
LINE 1: SELECT count(DISTINCT pref_name) over() FROM city;
               ^

By the way, here is what happens when you use GROUP BY and a window function at the same time:

mysql> SELECT pref_name,
    -> COUNT(*) g_count,
    -> COUNT(*) OVER(PARTITION BY pref_name) w_count
    -> FROM city
    -> WHERE type IN ('1','2','3')
    -> GROUP BY pref_name, pref_code
    -> ORDER BY pref_code;
+--------------+---------+---------+
| pref_name    | g_count | w_count |
+--------------+---------+---------+
| 北海道       |     179 |       1 |
| 青森県       |      40 |       1 |
| 岩手県       |      33 |       1 |
| 宮城県       |      35 |       1 |
| 秋田県       |      25 |       1 |
| 山形県       |      35 |       1 |
〜〜

Since the window function is applied to the result of the GROUP BY, the COUNT for the window function is 1. This part is not very intuitive. Maybe it just takes some getting used to.

Still, it's a bit of a downside of SQL that the evaluation timing differs between regular functions, aggregate functions, and window functions even when they are listed together in the SELECT clause...

The evaluation order of SELECT is as follows. Hmmm.

SELECT
  DISTINCT         -- ⑦
  hoge             -- ③
  LENGTH(hoge),    -- ③
  COUNT(*),        -- ④
  COUNT(*) OVER()  -- ⑥
FROM table         -- ①
WHERE condition    -- ②
GROUP BY hoge      -- ④
HAVING condition   -- ⑤
ORDER BY hoge      -- ⑧
LIMIT x            -- ⑨
脚注
  1. The data was obtained from the Statistics Bureau of Japan website / 2020 Population Census / Survey Results, so it should be accurate. ↩︎

Discussion