Skip to content

Commit 1d68627

Browse files
committed
add unnest
1 parent d3bf175 commit 1d68627

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
File renamed without changes.

2023-12-07-unnest.md

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
---
2+
title: Unnest arrays from multiple rows
3+
categories: [sql]
4+
---
5+
6+
Once you start moving off of the classic relational model in a sql
7+
database and start using arrays you keep needing to put an array back
8+
into a table when further dealing with the values.
9+
10+
A basic case is when using an array of values from your programming language into a sql query.
11+
12+
That's how I usually do it:
13+
14+
```sql
15+
with users as (select id::uuid from unnest(?) as id)
16+
select id from users;
17+
```
18+
19+
Another common usecase for arrays is when aggregating values in a
20+
group by. There you got to different groups bucketed in different
21+
arrays, and you may want to get a subset of them in table form:
22+
23+
24+
```sql
25+
with users as (select status, count(*), array_agg(id) as ids from users group by status)
26+
select unnest(ids) from (select ids from users where status in ('active', 'inactive')) as t;
27+
```
28+
29+
It's a nice pattern to keep in mind, while reminding that functions
30+
can usually run in the "from" side, but also in the "select" side.

0 commit comments

Comments
 (0)