mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add References Target Primary Key By Default as a Postgres TIL
This commit is contained in:
@@ -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)
|
||||
|
||||
37
postgres/references-target-primary-key-by-default.md
Normal file
37
postgres/references-target-primary-key-by-default.md
Normal file
@@ -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;
|
||||
```
|
||||
Reference in New Issue
Block a user