From a77bb6242996cc10e0bad82cbe61490bfabc7cd3 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 14 May 2021 10:20:13 -0500 Subject: [PATCH] Add Insert A Bunch Of Records With Generate Series as a postgres til --- README.md | 3 +- ...a-bunch-of-records-with-generate-series.md | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 postgres/insert-a-bunch-of-records-with-generate-series.md diff --git a/README.md b/README.md index 62ffa39..545f522 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/postgres/insert-a-bunch-of-records-with-generate-series.md b/postgres/insert-a-bunch-of-records-with-generate-series.md new file mode 100644 index 0000000..322e066 --- /dev/null +++ b/postgres/insert-a-bunch-of-records-with-generate-series.md @@ -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.