Skip to content

Constraint

一句话解释

constraint 是规则 enforced 通过数据库 — 它拒绝任何数据那个 violates 规则.

用大白话说

Constraints are rules you define on table columns that the database enforces automatically. If you try to insert or update data that violates a constraint, the database rejects the operation with an error.

Common constraints:

  • NOT NULL: the column must have a value.
  • UNIQUE: no two rows can have the same value.
  • PRIMARY KEY: a unique, not-null identifier for each row.
  • FOREIGN KEY: the value must reference an existing row in another table.
  • CHECK: the value must satisfy a custom condition.
  • DEFAULT: a value used if none is provided.

Constraints are the database's way of protecting data integrity. They are checked on every INSERT, UPDATE, and (for foreign keys) DELETE. Defining good constraints is a key part of database design.

示例

sql
CREATE TABLE products (
  id     SERIAL PRIMARY KEY,
  name   TEXT NOT NULL,
  price  NUMERIC(10,2) CHECK (price > 0),
  sku    TEXT UNIQUE NOT NULL,
  cat_id INTEGER REFERENCES categories(id)
);

Five constraints: PRIMARY KEY, NOT NULL, CHECK (price > 0), UNIQUE, and FOREIGN KEY.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表