[Postgres] Keep Data Integrity with Constraints

If the data in your tables do not have integrity, meaning there are missing rows, incorrect values, or duplicate rows, your table is not worth much. Data is king and there are simple ways we can make sure we keep this integrity. Constraints are ways to make sure our data stays in a healthy state. Not nulls, uniques, primary keys, and foreign keys, are all constraints we will review in this lesson to give you the tools to keep your data in check.

For example you want to make sure every time we add new data into Purchases table, we should have a reference for User table:

create table purchases (
   date date not null, 
   user_handle uuid references Users (user_handle),
   sku uuid not null,
   quantity int not null)

With that in place, if we try to insert a random user_handle into Purchases, we get an error.

原文地址:https://www.cnblogs.com/Answer1215/p/13579611.html