From f2d08564e557ee2d19b55a237f73c5555d991c72 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 28 Apr 2016 20:49:55 -0500 Subject: [PATCH] Add Use Not Valid To Immediately Enforce A Constraint as a postgres til --- README.md | 3 +- ...lid-to-immediately-enforce-a-constraint.md | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 postgres/use-not-valid-to-immediately-enforce-a-constraint.md diff --git a/README.md b/README.md index 7262d6c..5898d20 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_404 TILs and counting..._ +_405 TILs and counting..._ --- @@ -243,6 +243,7 @@ _404 TILs and counting..._ - [Types By Category](postgres/types-by-category.md) - [Use A psqlrc File For Common Settings](postgres/use-a-psqlrc-file-for-common-settings.md) - [Use Argument Indexes](postgres/use-argument-indexes.md) +- [Use Not Valid To Immediately Enforce A Constraint](postgres/use-not-valid-to-immediately-enforce-a-constraint.md) - [Using Expressions In Indexes](postgres/using-expressions-in-indexes.md) - [Using Intervals To Offset Time](postgres/using-intervals-to-offset-time.md) - [Who Is The Current User](postgres/who-is-the-current-user.md) diff --git a/postgres/use-not-valid-to-immediately-enforce-a-constraint.md b/postgres/use-not-valid-to-immediately-enforce-a-constraint.md new file mode 100644 index 0000000..418e761 --- /dev/null +++ b/postgres/use-not-valid-to-immediately-enforce-a-constraint.md @@ -0,0 +1,30 @@ +# Use Not Valid To Immediately Enforce A Constraint + +When adding a constraint to a table, you can optionally include `not valid`. +This tells Postgres that it doesn't need to enforce the constraint on +existing records in the table. At least not immediately. This constraint +will be enforced for any updates and subsequent insertions. Thus, you can +immediately enforce the constraint while giving yourself time to clean up +or massage any existing records that conflict with the constraint. + +Here is an example of how you would add a constraint this way: + +```sql +alter table boxes +add constraint check_valid_length +check (length > 0) not valid; +``` + +Eventually, you will want to ensure that all data in the table conforms to the +constraint. Once you get to that point, you can mark the constraint as valid +with a `validate constraint` command: + +```sql +alter table boxes +validate constraint check_valid_length; +``` + +As long as all records are valid with respect to this constraint, it will be +marked as valid. + +h/t Chris Erin