1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Insert A Bunch Of Records With Generate Series as a postgres til

This commit is contained in:
jbranchaud
2021-05-14 10:20:13 -05:00
parent 9e89734285
commit a77bb62429
2 changed files with 40 additions and 1 deletions

View File

@@ -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).
_1122 TILs and counting..._
_1123 TILs and counting..._
---
@@ -572,6 +572,7 @@ _1122 TILs and counting..._
- [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 A Bunch Of Records With Generate Series](postgres/insert-a-bunch-of-records-with-generate-series.md)
- [Insert Just The Defaults](postgres/insert-just-the-defaults.md)
- [Install Postgres With uuid-ossp Using asdf](postgres/install-postgres-with-uuid-ossp-using-asdf.md)
- [Integers In Postgres](postgres/integers-in-postgres.md)

View File

@@ -0,0 +1,38 @@
# Insert A Bunch Of Records With Generate Series
Sometimes you want to quickly insert a bunch of fake (or real) data into a
Postgres table. This is a great way to populate seed data or set up data
scenarios for testing things out.
For instance, I recently used the following query to generate a bunch of data
in a `roles` table to test out a query performance issue.
```sql
> insert into roles (
name,
resource_id,
resource_type,
created_at,
updated_at
)
select
'organization_user',
g.id,
'Organization',
now(),
now()
from generate_series(1,54000) as g(id);
```
The key part is the [`generate_series()`
function](https://www.postgresql.org/docs/current/functions-srf.html) which
will produce a row for every value between the two arguments. In this case, it
will generate `1`, `2`, `3`, etc. all the way up to `54000` -- so 54k rows in
total.
The query selects off that generated series with some static values and some
timestamps to create sufficiently fake data that can be inserted into the
specified columns of the `roles` table.
This quickly inserts tens of thousands of records that I can now use to test
out the performance of a SQL query.