SQLのCOUNT,MAX関数はソートを発生させるのか PostgreSQL編
この記事の続きてです 今回も同じようなデータを使います。
id | age | country |
---|---|---|
0001 | 18 | JP |
0002 | 23 | US |
0003 | 56 | SK |
0004 | 99 | SK |
0005 | 11 | US |
0006 | 34 | JP |
create table people( id char(4) not null primary key, age integer not null, country char(2) not null ); -- people INSERT INTO people(id, age, country) VALUES('0001', '18', 'JP'); INSERT INTO people(id, age, country) VALUES('0002', '23', 'US'); INSERT INTO people(id, age, country) VALUES('0003', '56', 'SK'); INSERT INTO people(id, age, country) VALUES('0004', '99', 'SK'); INSERT INTO people(id, age, country) VALUES('0005', '11', 'US'); INSERT INTO people(id, age, country) VALUES('0006', '34', 'JP');
PostgreSQLでのソート
PostgreSQLではソートが入るとSort演算子が実行計画に表示される
postgres=# explain select * from people order by age; QUERY PLAN ----------------------------------------------------------------- Sort (cost=88.17..91.35 rows=1270 width=36) Sort Key: age -> Seq Scan on people (cost=0.00..22.70 rows=1270 width=36) (3 rows)
count関数
postgres=# select country, count(*) from people group by country; country | count ---------+------- US | 2 JP | 2 SK | 2 (3 rows) postgres=# explain select country, count(*) from people group by country ; QUERY PLAN ----------------------------------------------------------------- HashAggregate (cost=29.05..31.05 rows=200 width=20) Group Key: country -> Seq Scan on people (cost=0.00..22.70 rows=1270 width=12) (3 rows)
- Sort確認できず
max関数
postgres=# select country, max(age) from people group by country; country | max ---------+----- US | 23 JP | 34 SK | 99 (3 rows) postgres=# explain select country, max(age) from people group by country ; QUERY PLAN ----------------------------------------------------------------- HashAggregate (cost=29.05..31.05 rows=200 width=16) Group Key: country -> Seq Scan on people (cost=0.00..22.70 rows=1270 width=16) (3 rows)
- sort確認できず
集約なしmax関数
postgres=# explain select max(age) from people; QUERY PLAN ---------------------------------------------------------------- Aggregate (cost=25.88..25.89 rows=1 width=4) -> Seq Scan on people (cost=0.00..22.70 rows=1270 width=4) (2 rows)
- sort確認できず
結論
実行計画を見たところsortが発生している箇所はなさそうです。
おうちで学べるデータベースの基本はMySQLを念頭に置いているので、
本書では、実際にいくつかの章(特に後半)で「MySQL」というデータベースを操作することで、「データベースとは何か?」ということをわかりやすく解説しています。
MySQLの動作としてMax,Countを集約関数と同時に使うと ソートが発生するという記載は適当なのだと思います。
- 作者: ミック,木村明治
- 出版社/メーカー: 翔泳社
- 発売日: 2015/02/13
- メディア: 単行本(ソフトカバー)
- この商品を含むブログを見る