mirror of
https://github.com/jbranchaud/til
synced 2026-01-04 23:58:01 +00:00
Add Adding Composite Uniqueness Constraints as a postgres til.
This commit is contained in:
@@ -108,6 +108,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
||||
### postgres
|
||||
|
||||
- [A Better Null Display Character](postgres/a-better-null-display-character.md)
|
||||
- [Adding Composite Uniqueness Constraints](postgres/adding-composite-uniqueness-constraints.md)
|
||||
- [Auto Expanded Display](postgres/auto-expanded-display.md)
|
||||
- [Checking The Type Of A Value](postgres/checking-the-type-of-a-value.md)
|
||||
- [Configure The Timezone](postgres/configure-the-timezone.md)
|
||||
|
||||
22
postgres/adding-composite-uniqueness-constraints.md
Normal file
22
postgres/adding-composite-uniqueness-constraints.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# Adding Composite Uniqueness Constraints
|
||||
|
||||
There are two ways in Postgres to create a composite uniqueness constraint,
|
||||
that is, a constraint that ensures that the combination of two or more
|
||||
values on a table only appear once. For the following two code snippets,
|
||||
assume that we have a table relating Pokemon and Trainers and that our
|
||||
domain restricts each Trainer to only having at most one of each Pokemon.
|
||||
|
||||
The first approach is to create a `constraint` directly on the table:
|
||||
|
||||
```sql
|
||||
alter table pokemons_trainers
|
||||
add constraint pokemons_trainers_pokemon_id_trainer_id_key
|
||||
unique (pokemon_id, trainer_id);
|
||||
```
|
||||
|
||||
The second approach is to create a unique index:
|
||||
|
||||
```sql
|
||||
create unique index pokemons_trainers_pokemon_id_trainer_id_idx
|
||||
on pokemons_trainers (pokemon_id, trainer_id);
|
||||
```
|
||||
Reference in New Issue
Block a user