From 46c976618d16b7ddd7475f55875ffb7aafc1175f Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 13 Nov 2019 13:06:13 -0600 Subject: [PATCH] Add Group By The Result Of A Function Call as a postgres til --- README.md | 3 +- .../group-by-the-result-of-a-function-call.md | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 postgres/group-by-the-result-of-a-function-call.md diff --git a/README.md b/README.md index a7e93af..92104af 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_866 TILs and counting..._ +_867 TILs and counting..._ --- @@ -434,6 +434,7 @@ _866 TILs and counting..._ - [Get The Size Of A Table](postgres/get-the-size-of-a-table.md) - [Get The Size Of An Index](postgres/get-the-size-of-an-index.md) - [Getting A Slice Of An Array](postgres/getting-a-slice-of-an-array.md) +- [Group By The Result Of A Function Call](postgres/group-by-the-result-of-a-function-call.md) - [Insert Just The Defaults](postgres/insert-just-the-defaults.md) - [Integers In Postgres](postgres/integers-in-postgres.md) - [Intervals Of Time By Week](postgres/intervals-of-time-by-week.md) diff --git a/postgres/group-by-the-result-of-a-function-call.md b/postgres/group-by-the-result-of-a-function-call.md new file mode 100644 index 0000000..3f7aa96 --- /dev/null +++ b/postgres/group-by-the-result-of-a-function-call.md @@ -0,0 +1,31 @@ +# Group By The Result Of A Function Call + +Typically, a query that I write involving a `group by` will look more or less +like this: + +```sql +select category, count(*) + from products + group by category; +``` + +The `category` column is the thing I'm grouping by. In this case, I'm doing a +little data exploration. + +We are not strictly limited to grouping by a column. We can use all sorts of +functions offered by Postgres to get at more interesting results. [String +functions](https://www.postgresql.org/docs/current/functions-string.html) are a +great place to start. + +Let's say our `products` table also has an `identifier` column with a naming +scheme where the first three letters of the identifier correspond to the +product's classification. We can group by that part of the `identifier`: + +```sql +select substring(identifier from 1 for 3), count(*) + from products + group by substring(identifier from 1 for 3); +``` + +The funkiness of the `substring` syntax aside, we were able to group our +products in a new way and learn something about our data.