diff --git a/README.md b/README.md index 5b9bfd8..80b752b 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://crafty-builder-6996.ck.page/e169c61186). -_1446 TILs and counting..._ +_1447 TILs and counting..._ --- @@ -736,6 +736,7 @@ _1446 TILs and counting..._ - [Fizzbuzz With Common Table Expressions](postgres/fizzbuzz-with-common-table-expressions.md) - [Force SSL When Making A psql Connection](postgres/force-ssl-when-making-a-psql-connection.md) - [Generate A UUID](postgres/generate-a-uuid.md) +- [Generate Modern Primary Key Columns](postgres/generate-modern-primary-key-columns.md) - [Generate Random UUIDs Without An Extension](postgres/generate-random-uuids-without-an-extension.md) - [Generate Series Of Numbers](postgres/generate-series-of-numbers.md) - [Generating UUIDs With pgcrypto](postgres/generating-uuids-with-pgcrypto.md) diff --git a/postgres/generate-modern-primary-key-columns.md b/postgres/generate-modern-primary-key-columns.md new file mode 100644 index 0000000..5e18547 --- /dev/null +++ b/postgres/generate-modern-primary-key-columns.md @@ -0,0 +1,43 @@ +# Generate Modern Primary Key Columns + +Chances are if you have looked at some examples, blog posts, or real-world +instances of a `create table` statement, it defined the primary key with +`serial` (or `bigserial`). + +```sql +create table books ( + id serial primary key, + title text not null, + author text not null, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); +``` + +The `serial` syntax is everywhere, but for quite a while now it has not been +the recommended way to define a primary key column for the `int` or `bigint` +data types. + +The ["Don't Do This" page of the PostgreSQL +wiki](https://wiki.postgresql.org/wiki/Don%27t_Do_This#Don.27t_use_serial) says +"Don't use serial". + +> For new applications, identity columns should be used instead. The serial +> types have some weird behaviors that make schema, dependency, and permission +> management unnecessarily cumbersome. + +The modern way to define a primary key column for `int` or `bigint` is with a +generated identity column. + +```sql +create table books ( + id int primary key generated always as identity, + title text not null, + author text not null, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); +``` + +Check out the PostgreSQL docs for more about [identity +columns](https://www.postgresql.org/docs/17/ddl-identity-columns.html).