前の記事
SQLチューニング事例①(インデックスを利用する例)
インデックス作成方針の目安
複合インデックスを作成
# nameとageにインデックスを作成
create index idx_employees_name_age on employees(name, age);
select * from employees
where name = 'Taro' and age = 21; # ANDの場合、インデックスを利用できる
select * from employees
where name = 'Taro' or age = 21; # ORの場合、インデックスを利用できない
select * from employees
where name = 'Taro'; # nameだけの場合、インデックスを利用できる
select * from employees
where age = 21; # ageだけの場合、インデックスを利用できない
外部キーにインデックスを追加
select * from orders as od
inner join items as it
on od.item_id = it.id;
# 外部キーにインデックスを追加
create index idx_orders_item_id on orders(item_id);
*MySQLでは外部キー制約をつけると自動的にインデックスも付与される
外部キーにインデックスを追加する前:
explain analyze select * from prefectures as p
inner join customers as c
on p.prefecture_code = c.prefecture_code
and p.name = "北海道";
/*
-> Inner hash join (c.prefecture_code = p.prefecture_code) (cost=234227 rows=233475) (actual time=5.96..130 rows=12321 loops=1)
-> Table scan on c (cost=1216 rows=496756) (actual time=0.0325..98.4 rows=500000 loops=1)
-> Hash
-> Filter: (p.`name` = '北海道') (cost=5.7 rows=4.7) (actual time=5.91..5.91 rows=1 loops=1)
-> Table scan on p (cost=5.7 rows=47) (actual time=5.9..5.9 rows=47 loops=1)
*/
prefectures
47件
↓ 全件読む
北海道を検索
↓
1件
prefecture_code = 北海道のコード
↓
ハッシュテーブル作成
↓
customers 500,000件を全件読む
↓
1件ずつ prefecture_code を比較
↓
北海道の顧客 12,321件
↓
actual time = 130 ms
外部キーにインデックスを追加した後:
create index idx_customers_prefecture_code on customers(prefecture_code);
explain analyze select * from prefectures as p
inner join customers as c
on p.prefecture_code = c.prefecture_code
and p.name = "北海道";
/*
-> Nested loop inner join (cost=16068 rows=55589) (actual time=3.25..24.1 rows=12321 loops=1)
-> Filter: (p.`name` = '北海道') (cost=4.95 rows=4.7) (actual time=0.0362..0.0464 rows=1 loops=1)
-> Table scan on p (cost=4.95 rows=47) (actual time=0.0331..0.039 rows=47 loops=1)
-> Index lookup on c using idx_customers_prefecture_code (prefecture_code=p.prefecture_code) (cost=2487 rows=11828) (actual time=3.21..23.6 rows=12321 loops=1)
*/
prefectures
47件
↓
北海道を検索
↓
1件
prefecture_code = 01
↓
customersのインデックスを見る
↓
idx_customers_prefecture_code
│
├─01 → 北海道のcustomer
├─02 → 青森県のcustomer
├─03 → 岩手県のcustomer
...
↓
01だけ検索
↓
12,321件取得
↓
actual time = 24.1 ms
SQLチューニング事例②(インデックスが利用されない例)
インデックスの対象カラムに関数を使う
インデックスはカラムの値に対して作成される。
ただし、カラムの値を関数で変換した場合には、インデックスが利用できずにフルスキャンが実行される。
この場合は、関数にインデックスを作成する。
インデックスの対象カラムが数値の場合に計算をする
インデックスのカラムでも数値演算をしたものを比較に使うと、インデックスが利用できない。
select * from employees
where age + 2 = 20;
文字列のカラムの比較対象にシングルクォーテーション、ダブルクォーテーションをつけない
インデックスをCHAR型やVARCHAR型に張っている際、比較対象にシングルクォーテーション、ダブルクォーテーションをつけない場合、左辺の数値への変換が行われインデックスを利用できない。
BAD
select * from employees
where prefecture_code = 21;
GOOD
select * from employees
where prefecture_code = '21';
後方一致検索、中間一致検索を利用している
LIKE句を用いて検索する場合、前方一致はインデックスが利用されるが、後方一致、中間一致はインデックスが利用されない。
-- 後方一致はインデックスが利用されない
select * from employees
where name like '%太郎';
後方一致の改善案
-- 名前を逆順に格納したreverseカラムを用意して前方一致検索をする
select * from employees
where name_reverse like '%郎太';
SQLチューニング事例③(意味のない並び替えを避ける)
以下は並び替えが発生し処理に時間がかかる。
ORDER BY
GROUP BY
集計関数(SUM、COUNT、AVG、MIN、MAX)
DISTINCT
UNION、INTERSECT、EXCEPT
ウィンドウ関数
無駄なORDER BY、GROUP BYを避ける
利用する際は極力レコードの絞り込みができてから行う
MIN、MAXの計算はインデックスで高速化できる
create index idx_users_age on users(age);
select
min(age), max(age)
from users;
DISTINCTの代わりにEXISTSを利用する
select distinct p.product_id
from products as p
inner join histories as h
on p.product_id = h.product_id;
-- EXISTSでproduct_idを取り出す
select p.product_id
from products as p
where exists
(select 1 from histories as h where h.product_id = p.product_id);
UNIONの代わりにUNION ALLを利用する
UNIONは並び替えと重複削除が行われ処理に時間がかかるため、重複削除の必要がない場合は利用せず、UNION ALLを利用する。
SQLチューニング事例④(同じ処理を何度も行わない)
副問い合わせで同じテーブルを見る回数は1回にする
select *
from employees
where
department_id in (select id from departments where name = '営業部')
or
department_id in (select id from departments where name = '総務部');
↓
select *
from employees
where
department_id in (select id from departments where name in('営業部', '総務部'));
SELECT内の副問い合わせをやめてJOINを使う
selectの対象カラム内に副問い合わせを使うと、行ごとに副問い合わせのSQLが実行されて処理に時間がかかる。
select emp.*,
(select name from departments as dp where dp.id = emp.department_id)
from employees as emp;
↓
select emp.*,
dp.name
from employees as emp
left join departments as dp
on emp.department_id = dp.id;
何度も無駄に絞り込みを行わない
ウィンドウ関数を用いて絞り込み1回と集計1回にする。
select o1.*, o2.daily_summary
from orders as o1
left join
(select order_date, sum(order_amount * order_price) as 'daily_summary' from orders
where order_date between '2020-01-01' and '2020-01-31'
group by order_date) as o2
on o1.order_date = o2.order_date
where o1.order_date between '2020-01-01' and '2020-01-31';
↓
select
*, sum(o1.order_amount * o1.order_price) over(partition by o1.order_date) as daily_summary
from orders as o1
where o1.order_date between '2020-01-01' and '2020-01-31';
SQLチューニング事例⑤(INSERTの実行回数を減らす)
マルチインサートを用いると、1回のSQLで複数レコードを格納できる。
insert into projects(name, start_date, end_date)
values
('projectA', '2019-08-01', '2019-12-31');
insert into projects(name, start_date, end_date)
values
('projectB', '2019-05-01', '2019-11-20');
↓
insert into projects(name, start_date, end_date)
values
('projectA', '2019-08-01', '2019-12-31'),
('projectB', '2019-05-01', '2019-11-20');

