けむブログ

データ分析に関する気付きや学びを記録するブログ

where句とhaving句の実行順番の違い

実行順番

FROM → WHERE GROUPBY HAVING → SELECT → ORDERBY

つまり
  • GroupByでグルーピングする前に抽出するのがWhere句
  • GroupByでグルーピングした後に抽出するのがHaving句
具体例

「グレーパーカー」より売上額が高い商品の「名前」「商品の値段」「売上額」を取得する場合

テーブルは2種類で sales_records, items,

  • NG
select items.name, items.price, items.price * count(*) as "売上額"
from sales_records
left join items
on items.id = sales_records.item_id
where  (items.price * count(*)) > 
  (
    select items.price * count(*)
    from sales_records
    left join items
    on items.id = sales_records.item_id
    where items.name = "グレーパーカー"
  )
group by items.id ;
  • OK
select items.name, items.price, items.price * count(*) as "売上額"
from sales_records
left join items
on items.id = sales_records.item_id
group by items.id
having  (items.price * count(*)) > 
  (
    select items.price * count(*)
    from sales_records
    left join items
    on items.id = sales_records.item_id
    where items.name = "グレーパーカー"
  )
 ;

参考:https://dev.classmethod.jp/server-side/db/difference-where-and-having/