From 0ec8b98d005e3cbbf974acf24ab4abe034ca0cad Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 9 Mar 2021 19:25:57 -0600 Subject: [PATCH] Add Count How Many Records There Are Of Each Type as a postgres til --- README.md | 3 +- ...how-many-records-there-are-of-each-type.md | 47 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 postgres/count-how-many-records-there-are-of-each-type.md diff --git a/README.md b/README.md index 5d59cb5..25b482d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1077 TILs and counting..._ +_1078 TILs and counting..._ --- @@ -517,6 +517,7 @@ _1077 TILs and counting..._ - [Configure The Timezone](postgres/configure-the-timezone.md) - [Constructing A Range Of Dates](postgres/constructing-a-range-of-dates.md) - [Convert A String To A Timestamp](postgres/convert-a-string-to-a-timestamp.md) +- [Count How Many Records There Are Of Each Type](postgres/count-how-many-records-there-are-of-each-type.md) - [Count Records By Type](postgres/count-records-by-type.md) - [Count The Number Of Trues In An Aggregate Query](postgres/count-the-number-of-trues-in-an-aggregate-query.md) - [Create A Composite Primary Key](postgres/create-a-composite-primary-key.md) diff --git a/postgres/count-how-many-records-there-are-of-each-type.md b/postgres/count-how-many-records-there-are-of-each-type.md new file mode 100644 index 0000000..a3f3942 --- /dev/null +++ b/postgres/count-how-many-records-there-are-of-each-type.md @@ -0,0 +1,47 @@ +# Count How Many Records There Are Of Each Type + +Let's say I have a `books` table full of data. One of the columns on this table +is `status` which represents whether the book is published, in review, or still +a draft. + +We can find out how many records (books) there are for each `status` using a +`group by` clause and the `count` aggregate function. + +```sql +> select status, count(*) + from books + group by status; + + status | count +-----------+------- + ø | 123 + published | 611 + draft | 364 + review | 239 +(4 rows) +``` + +Because we don't have a `not null` constraint on the `status` column, there are +also some records that have a null value. + +We can take this a step further by ordering the output in a consistent +way—descending order of the count column. + +```sql +> select status, count(*) + from books + group by status + order by 2 desc; + + status | count +-----------+------- + published | 611 + draft | 364 + review | 239 + ø | 123 +(4 rows) +``` + +This `order by` clauses uses [a positional index from the select +arguments](use-argument-indexes.md), so the `2` references the `count(*)` +argument.