0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQL 記述・実行順序 or Group by・Having・Order by句の記述方法

Last updated at Posted at 2021-11-21

記事内容

  • select文の記述順序と実行順序
  • テーブルデータのグループ化
  • 集約結果の絞り込み
  • 取得データの並び替え

select文の記述順序と実行順序

記述する順序は下記表の通りに決められている

select文の記述順序と実行順序は異なるので注意

記述順 文・句 意味 実行順 文・句 意味
1 select 取得行(カラム)の指定 1 from 対象テーブルの指定
2 from 対象テーブルの指定 2 inner join 結合処理
3 inner join 結合処理 3 where 絞り込みの指定
4 where 絞り込みの指定 4 group by グループ化の条件を指定
5 group by グループ化の条件を指定 5 having グループ化した後の絞り込み条件の指定
6 having グループ化した後の絞り込み条件の指定 6 select 取得行(カラム)の指定
7 order by 並び替え条件の指定 7 order by 並び替え条件の指定
8 limit 取得する行数の制限 8 limit 取得する行数の制限

group by

テーブルデータのグループ化

  • group byで指定する列名によってグループ化される
  • 列名複数指定可
  • count関数グループ別に集計
-- prefecture_id = 都道府県ID

-- 都道府県別のユーザー数を取得
select
  prefecture_id,
  count(*)
from
  users
group by
  prefecture_id;

having

集約結果をさらに絞り込むことができる句

  • テーブルデータを集約した結果に対して、条件式を適用する場合に利用
  • havinggroup byの後に記述
-- access_logs = アクセスログテーブル
-- request_month = アクセスした年月日
-- user_id = アクセスしたユーザーID

-- 2017年のアクセスログから月間ユニークユーザー数が600人以上の月の一覧を取得

select
  request_month,
  count(distinct user_id)
from
  access_logs
where
  request_month >= '2017-01-01'
  and request_month < '2018-01-01'
group by
  request_month
having
  count(distinct user_id) >= 600;

order by

取得データの並び替え

  • 並び替えの指定
    • asc ・・・ 昇順 (ascending)
    • desc ・・・ 降順 (descending)

取得するデータの並び順が重要な場合、order by句を使用して明示的に指定

-- 構文
order by 列や式 並び替え, ...;

-- 価格が低い順に取得
select * from products order by price asc;
-- asc はデフォルト設定のため、省略可
select * from products order by price;

並び替え条件の指定

-- 商品価格が高い順に並び替えを行い、商品価格が同じ場合は登録順に並び替えて取得
select * from products order by price desc, id asc; 

参考教材

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?