From 8fecb0e86356dfb7f6ba7ea11cf091fd3941ed02 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 19 Jun 2025 09:59:12 -0500 Subject: [PATCH] Add References Target Primary Key By Default as a Postgres TIL --- README.md | 3 +- ...eferences-target-primary-key-by-default.md | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 postgres/references-target-primary-key-by-default.md diff --git a/README.md b/README.md index 7dc9d5f..a6348b3 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). -_1647 TILs and counting..._ +_1648 TILs and counting..._ See some of the other learning resources I work on: - [Get Started with Vimium](https://egghead.io/courses/get-started-with-vimium~3t5f7) @@ -912,6 +912,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Prevent A Query From Running Too Long](postgres/prevent-a-query-from-running-too-long.md) - [Print The Query Buffer In psql](postgres/print-the-query-buffer-in-psql.md) - [Put Unique Constraint On Generated Column](postgres/put-unique-constraint-on-generated-column.md) +- [References Target Primary Key By Default](postgres/references-target-primary-key-by-default.md) - [Remove Not Null Constraint From A Column](postgres/remove-not-null-constraint-from-a-column.md) - [Renaming A Sequence](postgres/renaming-a-sequence.md) - [Renaming A Table](postgres/renaming-a-table.md) diff --git a/postgres/references-target-primary-key-by-default.md b/postgres/references-target-primary-key-by-default.md new file mode 100644 index 0000000..0241a6b --- /dev/null +++ b/postgres/references-target-primary-key-by-default.md @@ -0,0 +1,37 @@ +# References Target Primary Key By Default + +Typically when I am creating a table or adding a column that involves a foreign +key constraint, I explicitly name the reference column. + +```sql +create table contacts ( + id int generated always as identity primary key, + user_id int references users(id); +); +``` + +The [Create Table PostgreSQL +Docs](https://www.postgresql.org/docs/17/sql-createtable.html) point out that +specifying the reference column isn't strictly necessary. + +> These clauses specify a foreign key constraint, which requires that a group +> of one or more columns of the new table must only contain values that match +> values in the referenced column(s) of some row of the referenced table. If +> the refcolumn list is omitted, the primary key of the reftable is used. + +If we're using the primary key as the reference column, then we can choose to +omit the reference column. + +```sql +create table contacts ( + id int generated always as identity primary key, + user_id int references users; +); +``` + +In the same way we can do this when adding a column. + +```sql +alter table contacts + add column account_id int references account; +```