Skip to content

Commit 46c9766

Browse files
committed
Add Group By The Result Of A Function Call as a postgres til
1 parent 38f3258 commit 46c9766

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
99

1010
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1111

12-
_866 TILs and counting..._
12+
_867 TILs and counting..._
1313

1414
---
1515

@@ -434,6 +434,7 @@ _866 TILs and counting..._
434434
- [Get The Size Of A Table](postgres/get-the-size-of-a-table.md)
435435
- [Get The Size Of An Index](postgres/get-the-size-of-an-index.md)
436436
- [Getting A Slice Of An Array](postgres/getting-a-slice-of-an-array.md)
437+
- [Group By The Result Of A Function Call](postgres/group-by-the-result-of-a-function-call.md)
437438
- [Insert Just The Defaults](postgres/insert-just-the-defaults.md)
438439
- [Integers In Postgres](postgres/integers-in-postgres.md)
439440
- [Intervals Of Time By Week](postgres/intervals-of-time-by-week.md)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Group By The Result Of A Function Call
2+
3+
Typically, a query that I write involving a `group by` will look more or less
4+
like this:
5+
6+
```sql
7+
select category, count(*)
8+
from products
9+
group by category;
10+
```
11+
12+
The `category` column is the thing I'm grouping by. In this case, I'm doing a
13+
little data exploration.
14+
15+
We are not strictly limited to grouping by a column. We can use all sorts of
16+
functions offered by Postgres to get at more interesting results. [String
17+
functions](https://www.postgresql.org/docs/current/functions-string.html) are a
18+
great place to start.
19+
20+
Let's say our `products` table also has an `identifier` column with a naming
21+
scheme where the first three letters of the identifier correspond to the
22+
product's classification. We can group by that part of the `identifier`:
23+
24+
```sql
25+
select substring(identifier from 1 for 3), count(*)
26+
from products
27+
group by substring(identifier from 1 for 3);
28+
```
29+
30+
The funkiness of the `substring` syntax aside, we were able to group our
31+
products in a new way and learn something about our data.

0 commit comments

Comments
 (0)