postgresql----数据库表的约束----NOT NULL,DEFAULT,CHECK

数据库表有NOT NULL,DEFAULT,CHECK,UNIQUE,PRIMARY KEY,FOREIGN KEY六种约束。

一、NOT NULL ---- 非空约束

NULL表示没有数据,不表示具体的数值,所以在数据库中NULL是不等于NULL的。判断表中的一个单元格是不是NULL使用的是IS NULL或者IS NOT NULL,而不是=NULL或者!=NULL,当一个字段设置NOT NULL约束后,INSERT时必须给该字段赋值,否则拒绝写入。在一些程序语言(如C)查询结果中出现NULL有可能会直接作为空指针,如果使用不当,会直接导致程序崩溃。所以一个字段要尽可能的设置NOT NULL约束,或者DEFAULT约束,当然OUTER JOIN的结果也有可能引入NULL,所以开发过程中要尽可能的做好保护。

1.设置NOT NULL约束的字段INSERT必须赋值,没有NOT NULL约束的字段INSERT没有赋值,会自动填充NULL。

/*
postgres=# create database test with template = template0 encoding=‘UTF8‘ lc_collate=‘C‘ lc_ctype=‘C‘;
CREATE DATABASE
postgres=#
postgres=#
postgres=#
postgres=# \c test
You are now connected to database "test" as user "postgres".
test=# create table tbl_null (a int not null,b varchar(12));
CREATE TABLE
test=# insert into tbl_null (a,b) values(1,‘1‘);
INSERT 0 1
test=# insert into tbl_null (a) values(2);
INSERT 0 1
test=# insert into tbl_null (b) values(‘3‘);
ERROR:  null value in column "a" violates not-null constraint
DETAIL:  Failing row contains (null, 3).
test=# select * from tbl_null;
 a | b
---+---
 1 | 1
 2 |
(2 rows)
*/

2.NOT NULL约束增加

已存在的字段设置NOT NULL约束前必须先删除为NULL的数据行。

/*
test=# alter table tbl_null alter COLUMN b set not null;
ERROR:  column "b" contains null values
test=# delete from tbl_null where b is null;
DELETE 1
test=# alter table tbl_null alter COLUMN b set not null;
ALTER TABLE
test=# \d tbl_null
          Table "public.tbl_null"
 Column |         Type          | Modifiers
--------+-----------------------+-----------
 a      | integer               | not null
 b      | character varying(12) | not null

test=# select * from tbl_null ;
 a | b
---+---
 1 | 1
(1 row)
*/

3.删除NOT NULL约束

/*
test=# alter table tbl_null alter COLUMN b drop not null;
ALTER TABLE
test=# \d tbl_null
          Table "public.tbl_null"
 Column |         Type          | Modifiers
--------+-----------------------+-----------
 a      | integer               | not null
 b      | character varying(12) |
*/

二、DEFAULT ---- 默认值

INSERT没有赋值的字段默认填充NULL(前提是该字段没有NOT NULL约束),设置DEFAULT默认值,INSERT没有赋值会默认填充该默认值。尤其是设置NOT NULL约束的字段,如果给定一个DEFAULT约束,即使INSERT没有给字段赋值也不会出错。

1.设置DEFAULT约束,既可以在创建表时直接设置,也可以在创建表后修改字段,字段新增默认值约束可以不用考虑已有数据。

/*
test=# create table tbl_default(a int not null,b varchar(12) not null default ‘try me‘);
CREATE TABLE
test=# \d tbl_default
                          Table "public.tbl_default"
 Column |         Type          |                  Modifiers
--------+-----------------------+----------------------------------------------
 a      | integer               | not null
 b      | character varying(12) | not null default ‘try me‘::character varying

test=# drop table tbl_default ;
DROP TABLE
test=# create table tbl_default(a int not null,b varchar(12) not null);
CREATE TABLE
test=# alter table tbl_default alter COLUMN b set default ‘try me‘;
ALTER TABLE
test=# \d tbl_default
                          Table "public.tbl_default"
 Column |         Type          |                  Modifiers
--------+-----------------------+----------------------------------------------
 a      | integer               | not null
 b      | character varying(12) | not null default ‘try me‘::character varying
*/

2.INSERT时赋值使用赋值填充,否则使用默认值填充。

/*
test=# insert into tbl_default (a,b) values(1,‘aloha‘);
INSERT 0 1
test=# insert into tbl_default (a) values(2);
INSERT 0 1
test=# select * from tbl_default ;
 a |   b
---+--------
 1 | aloha
 2 | try me
(2 rows)
*/

3.默认值约束的修改与删除,修改默认值直接新设置一个默认值即可。

/*
test=# alter table tbl_default alter COLUMN b set default ‘my god‘;
ALTER TABLE
test=# \d tbl_default
                          Table "public.tbl_default"
 Column |         Type          |                  Modifiers
--------+-----------------------+----------------------------------------------
 a      | integer               | not null
 b      | character varying(12) | not null default ‘my god‘::character varying

test=# alter table tbl_default alter COLUMN b drop default;
ALTER TABLE
test=# \d tbl_default
         Table "public.tbl_default"
 Column |         Type          | Modifiers
--------+-----------------------+-----------
 a      | integer               | not null
 b      | character varying(12) | not null

*/

三、CHECK ---- 检查约束

INSERT,UPDATE时检查字段值是否满足CHECK条件,若不满足则拒绝写入。

1.CHECK约束的设置

/*
test=# create table tbl_check(a int not null check (a>0),b varchar(12) not null check (b in (‘ab‘,‘Ab‘,‘aB‘,‘AB‘)));
CREATE TABLE
test=# drop table tbl_check ;
DROP TABLE
test=# create table tbl_check
test-# (
test(# a int not null,
test(# b varchar(12) not null,
test(# constraint ck_tbl_check_a check (a > 0),
test(# constraint ck_tbl_check_b check (b in (‘ab‘,‘aB‘,‘Ab‘,‘AB‘))
test(# );
CREATE TABLE
test=# create table tbl_check
(
a int not null,
b varchar(12) not null);
CREATE TABLE
test=# alter table tbl_check add constraint ck_tbl_check_a check (a > 0);
ALTER TABLE
test=# alter table tbl_check add constraint ck_tbl_check_b check (b in (‘ab‘,‘aB‘,‘Ab‘,‘AB‘));
ALTER TABLE
test=# \d tbl_check
          Table "public.tbl_check"
 Column |         Type          | Modifiers
--------+-----------------------+-----------
 a      | integer               | not null
 b      | character varying(12) | not null
Check constraints:
    "ck_tbl_check_a" CHECK (a > 0)
    "ck_tbl_check_b" CHECK (b::text = ANY (ARRAY[‘ab‘::character varying, ‘aB‘::character varying, ‘Ab‘::character varying, ‘AB‘::character varying]::text[]))
*/

2.以上表tbl_check为例,INSERT时a的值必须是大于0的整数,b的值只能在‘ab‘,‘aB‘,‘Ab‘,‘AB‘范围内。

/*
test=# insert into tbl_check (a,b) values(1,‘ab‘);
INSERT 0 1
test=# insert into tbl_check (a,b) values(-1,‘ab‘);
ERROR:  new row for relation "tbl_check" violates check constraint "ck_tbl_check_a"
DETAIL:  Failing row contains (-1, ab).
test=# insert into tbl_check (a,b) values(1,‘ac‘);
ERROR:  new row for relation "tbl_check" violates check constraint "ck_tbl_check_b"
DETAIL:  Failing row contains (1, ac).
*/

3.CHECK约束的删除

/*
test=# alter table tbl_check drop constraint ck_tbl_check_a;
ALTER TABLE
test=# insert into tbl_check (a,b) values(-1,‘ab‘);
INSERT 0 1

*/

4.CHECK约束的增加

新增CHECK约束必须首先删除已存在的不满足约束的数据

/*
test=# alter table tbl_check add constraint ck_tbl_check_a check (a > 0);
ERROR:  check constraint "ck_tbl_check_a" is violated by some row
test=# delete from tbl_check where a <= 0;
DELETE 1
test=# alter table tbl_check add constraint ck_tbl_check_a check (a > 0);
ALTER TABLE
*/
时间: 2024-08-29 09:03:32

postgresql----数据库表的约束----NOT NULL,DEFAULT,CHECK的相关文章

数据库表的约束

在设计数据库时,为了确保数据库表中数据的质量,需要考虑数据的完整性(数据的完整性是指数据的正确性和一致性).举个例子:当你要为学生建立一个基本信息表StudentInfo时,这个表中学生的名字可以相同但是学号必须不一样,而他的年龄也得限制在一定范围内,像这样类似的"限制"有很多,如果违反了这些限制就制造了与现实不符的失真数据即破坏了数据的完整性.因为数据库不能自行判断哪些数据失真,所以需要认为添加一些约束来保证数据的完整性. 数据库中对表的约束有五种: 1.主键约束(Primary K

PostgreSQL数据库表的内部结构

A page within a table contains three kinds of data described as follows: heap tuple(s) – A heap tuple is a record data itself. They are stacked in order from the bottom of the page. The internal structure of tuple is described in Section 5.2 and Chap

数据库表字段,DEFAULT NULL与NOT NULL DEFAULT

为什么要把字段设置成not null 呢? 1.空值是不占用空间的 2.mysql中的NULL其实是占用空间的,下面是来自于MYSQL官方的解释 "NULL columns require additional space in the row to record whether their values are NULL. For MyISAM tables, each NULL column takes one bit extra, rounded up to the nearest byt

PostgreSQL数据库中获取表主键名称

PostgreSQL数据库中获取表主键名称 一.如下表示,要获取teacher表的主键信息: select pg_constraint.conname as pk_name,pg_attribute.attname as colname,pg_type.typname as typename from pg_constraint inner join pg_class on pg_constraint.conrelid = pg_class.oid inner join pg_attribute

SQLYog执行SQL脚本提示:错误代码: 1067 - Invalid default value for &#39;数据库表&#39;查询:解决办法

强烈建议:完全卸载当前版本MySQL,重新安装5.6及以上版本 完全卸载方法:https://jingyan.baidu.com/article/3d69c551611290f0ce02d77b.html 卸载完之后记得删除C:\ProgramData下的隐藏文件MySQL 这是我在网上查阅多方资料,尝试无数次,踩了很多坑之后得到的最优解决办法! 至于网上修改sql_mode之类的办法,亲测无效,可能和我代码有关,不做赘述! 出现该错误原因:MySQL版本不同,导致5.6版本之前和之后的语法有很

将PostgreSQL数据库的表导入到elasticsearch中

1.查看PostgreSQL表结构和数据信息 edbstore=# \d customers Table "edbstore.customers" Column | Type | Modifiers ----------------------+-----------------------+---------------------------------------------------------------- customerid | integer | not null d

数据库表的列约束

1.主键约束——PRIMARY KEY 声明了主键约束的列上不允许插入重复的值,一个表中只能有一个主键,通常加在编号列上,查询的时候会按照主键标号从小到大排序,会加快查找速度.主键约束不允许为NULL 2.唯一约束——UNIQUE 声明了唯一约束的列上,不允许插入重复的值,但允许插入NULL,并且多个NULL.一个表中可以出现多个唯一约束. 3.非空约束——NOT NULL 声明了非空约束的列上禁止为NULL 4.检查约束——CHECK mysql不支持检查约束,认为会对服务器造成一定的压力,降

在Oracle 11.2的数据库中建表时遇到 RESULT_CACHE (MODE DEFAULT) ORA-00922: missing or invalid option

在Oracle 11.2的数据库中建表时遇到 RESULT_CACHE (MODE DEFAULT)  ORA-00922: missing or invalid option hostdr:[/home/oracle]$sqlplus / as sysdba SQL*Plus: Release 11.2.0.3.0 Production on Thu Jul 9 12:52:11 2015 Copyright (c) 1982, 2011, Oracle. All rights reserve

创建基本表、数据库、列级/表级约束

3.5创建药品表,药品代码是主码,批号取值唯一 Create table medicine( Medicinecode char(10)primary key, Medicinename varchar(50), Pycode char(10), Dosagefrom char(10), standard char(15), Batchnumber char(20) unique, Productiondate date, Expirationdate date, Category char(1