PostgreSQL教程:约束(主键、非空、唯一、检查约束)

核心在于构建表时,要指定上一些约束。

约束

主键

-- 主键约束
drop table test;
create table test(
    id bigserial primary key ,
    name varchar(32)
);

非空

-- 非空约束
drop table test;
create table test(
    id bigserial primary key ,
    name varchar(32) not null
);

唯一

drop table test;
create table test(
    id bigserial primary key ,
    name varchar(32) not null,
    id_card varchar(32) unique
);
insert into test (name,id_card) values ('张三','333333333333333333');
insert into test (name,id_card) values ('李四','333333333333333333');
insert into test (name,id_card) values (NULL,'433333333333333333');

检查

-- 检查约束:必须达到指定条件
-- 价格的表,price,discount_price
drop table test;
create table test(
    id bigserial primary key,
    name varchar(32) not null,
    price numeric check(price > 0),
    discount_price numeric check(discount_price > 0),
    check(price >= discount_price)
);
insert into test (name,price,discount_price) values ('粽子',122,12);

给已有字段添加检查约束

在 PostgreSQL 中,您可以使用以下方法来检查约束:

  1. 创建表时定义约束:在创建表时,可以使用 CHECK 子句来定义约束条件。例如,考虑以下示例表:
CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    age INTEGER,
    CONSTRAINT check_age CHECK (age >= 18)
);

在上面的示例中,CHECK 子句定义了一个约束条件 age >= 18,它确保了 age 列的值必须大于或等于 18。

  1. 添加约束到现有表:您还可以使用 ALTER TABLE 语句来添加约束到现有表。例如,以下示例演示如何添加一个约束到现有的 employees 表:
ALTER TABLE employees ADD CONSTRAINT check_age CHECK (age >= 18);

这将在 employees 表上添加一个名为 check_age 的约束。

  1. 查看约束:要查看表上的约束信息,您可以使用 \d 命令或查询系统目录表。例如,使用 \d 命令查看约束信息:
\d employees

这将显示表的结构,包括约束信息。

  1. 删除约束:如果需要删除约束,您可以使用 ALTER TABLE 语句的 DROP CONSTRAINT 子句。以下是删除约束的示例:
ALTER TABLE employees DROP CONSTRAINT check_age;

这将从 employees 表中删除名为 check_age 的约束。

请注意,约束是用于确保数据完整性的重要工具,在设计数据库时应谨慎选择和使用约束。

默认值

一般公司内,要求表中除了主键和业务字段之外,必须要有5个字段

created,create_id,updated,update_id,is_delete
-- 默认值
create table test(
    id bigserial primary key,
    created timestamp default current_timestamp
);

猜你喜欢

转载自blog.csdn.net/a772304419/article/details/132928317