PostgreSQL: NOT VALID 约束 vs 验证触发器

11
我有一个带有“货币”列的表格。 我想要防止插入某些货币,而不删除现有的货币
起初我考虑使用验证触发器。
后来我发现了ALTER TABLE ADD CONSTRAINTNOT VALID选项,可以防止对现有数据进行验证。 文档似乎暗示NOT VALID选项主要用于性能原因,以允许用户将验证延迟到以后。但是它没有明确说明它不能用于保留旧(无效)数据的目的。
这篇文章中,这个人说:“你甚至可以将约束保持在NOT VALID状态,因为这更好地反映了它实际执行的操作:检查新行,但不为现有的数据提供保证。 NOT VALID检查约束没有任何问题。
那么,NOT VALID选项可以用于这个目的吗?还是最好使用验证触发器?
1个回答

10
引语中省略的部分是这样的:

https://www.postgresql.org/docs/current/sql-altertable.html

"The constraint will still be enforced against subsequent inserts or updates. This means that they will fail unless there is a matching row in the referenced table, in the case of foreign keys, or they will fail unless the new row matches the specified check condition. So if someone updates the old rows again, the constraint will be applied. NOT VALID is just a way to spread the validation out over time. If you want to maintain multiple states of validation on the column, you will need a trigger to do that on whatever criteria you select."

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接