diff --git a/README.md b/README.md index aed014f..2e14e8b 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,7 @@ smart people at [Hashrocket](http://hashrocket.com/). - [Count Records By Type](postgres/count-records-by-type.md) - [Create A Composite Primary Key](postgres/create-a-composite-primary-key.md) - [Create hstore From Two Arrays](postgres/create-hstore-from-two-arrays.md) +- [Creating Conditional Constraints](postgres/creating-conditional-constraints.md) - [Default Schema](postgres/default-schema.md) - [Defining Arrays](postgres/defining-arrays.md) - [Edit Existing Functions](postgres/edit-existing-functions.md) diff --git a/postgres/creating-conditional-constraints.md b/postgres/creating-conditional-constraints.md new file mode 100644 index 0000000..9cb4c92 --- /dev/null +++ b/postgres/creating-conditional-constraints.md @@ -0,0 +1,17 @@ +# Creating Conditional Constraints + +There are times when it doesn't make sense for a constraint to apply to all +records in a table. For instance, if we have a table of pokemon, we may only +want to apply a unique index constraint to the names of non-wild pokemon. +This can be achieved with the following conditional constraint: + +```sql +create unique index pokemons_names on pokemons (names) +where wild = false; +``` + +If we try to insert a non-wild pokemon with a duplicate name, we will get an +error. Likewise, if we try to update a pokemon with a duplicate name from +wild to non-wild, we will get an error. + +[source](http://www.postgresguide.com/performance/conditional.html)