sql - 向表添加约束的 PostgreSQL 语法是否存在不一致?

标签 sql postgresql

来自 PostgreSQL 文档

To add a constraint, the table constraint syntax is used. For example:

ALTER TABLE products ADD CHECK (name <> '');
ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no);
ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES product_groups;

To add a not-null constraint, which cannot be written as a table constraint, use this syntax:

ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;

为什么 ADD 后面的词对于不同类型的约束不同?

为什么唯一约束具有比检查和外键更通用的 ADD CONSTRAINT some_name

为什么 ALTER COLUMN 没有指定空约束,而不是 ADD CONSTRAINT some_name NOT NULL (col_name)

PostgreSQL 对表添加约束的语法是否不一致? 这是否属于 SQL 标准?

最佳答案

ADD 之后的词不同所以数据库知道你的意思。例如。 CHECK引入通用 bool 条件; UNIQUE后面是列名列表; FOREIGN KEY后跟一个列名,REFERENCES和一个目标表/列。如果没有这些关键字,您指的是哪种约束将是不明确的。

CONSTRAINT <i>constraint_name</i>语法不限于唯一约束。参见 column_constraint 的定义 table_constraint https://www.postgresql.org/docs/10/static/sql-createtable.html ;两者都允许可选的前导 CONSTRAINT <i>constraint_name</i>命名约束。

至于NOT NULL , 请参阅 https://www.postgresql.org/docs/10/static/ddl-constraints.html#id-1.5.4.5.6 :

A not-null constraint is always written as a column constraint. A not-null constraint is functionally equivalent to creating a check constraint CHECK (<i>column_name</i> IS NOT NULL), but in PostgreSQL creating an explicit not-null constraint is more efficient. The drawback is that you cannot give explicit names to not-null constraints created this way.

我假设非空约束在内部是一种特殊情况,允许比通用 CHECK 更好的优化约束,可以使用任何 bool 表达式。

关于sql - 向表添加约束的 PostgreSQL 语法是否存在不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51183026/

相关文章:

mysql连接表

SQL 可移植性陷阱

mysql - MySQL 字符串函数(例如 "TRIM")可以作用于 1 列 SELECT 子句吗?

python - 我需要如何将 sql 插入、通用值、哪些列和值可变化?

sql - 使用 SQL 使数据库中的列与相等的行相等

从多个表进行 SQL 查询

mysql - mySQL 查询 INNER JOIN 之间的区别

postgresql - 如何在1000张表上批量创建索引

postgresql - 具有不同模式的 2 个 Odoo 8.0 postgresql 数据库之间的数据库复制

sql - 单个对象的交叉引用表