mirror of
https://github.com/jbranchaud/til
synced 2026-01-07 09:08:01 +00:00
Add Count How Many Records There Are Of Each Type as a postgres til
This commit is contained in:
@@ -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)
|
||||
|
||||
47
postgres/count-how-many-records-there-are-of-each-type.md
Normal file
47
postgres/count-how-many-records-there-are-of-each-type.md
Normal file
@@ -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.
|
||||
Reference in New Issue
Block a user