Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

SQL Cheatsheet - Part Two (GROUP BY)

  • GROUP BY is fundamental to perform aggregation functions (集計関数)
  • When it throws an error, it's scary
  • When it works for some unknown reason, it's even scarier
  • Always wrap your aggregation targets in parentheses. AVG("age"), not AVG "age". PostgreSQL will absolutely lose it otherwise.

We will work with this table

table name: members

namecreated_daychannelage
エレン2021-02-13web27
こういち2021-02-13ad27
さゆり2021-02-15ad27
上谷2021-02-15ad33
あかり2021-02-16web24

COUNT: Counts The Number of Records

SELECT COUNT("name")
  FROM members
WHERE "created_day" = '2021-02-13';
count
2

GROUP BY: Groups the same records together

SELECT "created_day", COUNT("name")
  FROM members
GROUP BY "created_day";
created_daycount
2021-02-132
2021-02-152
2021-02-161
SELECT "created_day", "channel", COUNT("name")
  FROM members
GROUP BY "created_day";

This will throw an error, because the system doesn't know if 2021-02-13 in created_day corresponds to ad, or web in the column channel.

SELECT "created_day", "channel", COUNT("name")
  FROM members
GROUP BY "created_day", "channel";
created_daychannelcount
2021-02-13web1
2021-02-13ad1
2021-02-15ad2
2021-02-16web1

Aggregation functions: (集計関数)

Aggregates values

  • COUNT: number of records
  • AVG: the average value
  • MAX: the maximum
  • MIN: the minimum
  • SUM: the total
SELECT "created_day", AVG("age"), MAX("age")
  FROM members
GROUP BY "created_day";
created_dayavgmax
2021-02-132727
2021-02-153033
2021-02-162424