默认值

  • 可以理解为建表时没定义的默认值为null,表示未知,//注意和js中null不一样;

  • 建表时设置

create table child(id int, age int default 18);
  • 更新时使用
update child set age = default where id = 1;
  • 默认值可以是个表达式,它会在插入时计算
create table test (id int, created_time timestamp default now());

约束

检查约束

  • check给某些字段值指定一个范围:
create table child (name text, age int constraint ck_age check (age < 18 and age > 7) );
create table NotChild (name text, age int constraint ck_age check (age >18 or age < 7) ); //也可以都放到最后
create table books (book_no int, name text, price numeric, discounted_price numeric,
check(price > 0), check(discounted_price > 0), check(price > discounted_price) ); create table books (book_no int, name text, price numeric, discounted_price numeric,
check(price > 0 and discounted_price > 0 and price > discounted_price) );

非空约束

  • 确保一个字段值不为空
create table books (book_no int not null, name text);

//相当于
create table books (book_no int, name text, check(book_no is not null));

主键

  • 如果表的主键只是一个字段组成,则可以通过直接在后面加primary key来指定主键;
  • 如果由多个字段组成,成为组合主键;
create table test (id1 int, id2 int, note varchar(20), constraint key_test primary key(id1, id2) );

唯一约束

  • 也可以指定唯一键;

    • 主键一定是唯一键,反之不是;
    • 主键不能为空,唯一键可以;
create table test (id1 int, id2 int, id3 int, note varchar(20), constraint key_test primary key(id1, id2) , constraint uk_test unique(id3) );

外键约束

  • 用于约束本表中的一个字段或多个字段的数值必须出现在另一个表的资格或多个字段中
//注意:这里要确保class_no unique

create table class(
class_no int primary key,
class_name varchar(40)
); create table student(
student_no int primary key,
student_name varchar(40),
age int,
class_no int references class(class_no)
); //建立外键之后,student中就不能插入class中不存在的class_no值

用其他表作为模版创建

create table baby (like child);

//注意这样创建并没有把源表的约束复制过来,需要添加
including defaults
including constraints
including indexs
including storage
including comments
including all create table baby2 (like child including all);

临时表

  • 创建的临时表会在一个特殊的模式中: pg_temp_XX;
  • 无论是那种临时表,会话结束后就会消失;
  • 会话级的临时表, 数据只保存在当前会话周期中;
  • 在另一个session中无法访问
create temporary table tmp (id int primary key, note text);   //temporary可以缩写为temp
  • 事务级临时表,数据只保存在当前事务中;
create temporary table tmp (id int primary key, note text) on commit delete rows;

begin; //事务开始

insert into values(1, 'a');  //注意在事务外是无法插入数据的
insert into values(2, 'b');
select * from tmp;
end; //事务结束,tmp表还存在。但数据已经消失;

修改表

  • 对已经建立的表使用alter table来修改表结构

增加字段

alter table class add column class_teacher varchar(40);

//设置默认值会对已经存在的行会自动填充;

删除字段

  • 和这个字段相关的约束也会被删除;
alter table class drop column class_no;
  • 如果存在外键依赖不能直接删除,必须要指明删除任何依赖在该字段的东西;
alter table class drop column class_no cascade;

增加约束

  • 给表增加约束前要确定该表符合约束条件,否则会失败;
alter table student alter column student_name set not null;  //非空约束

alter table student add check(age < 16);  //检查约束

alter table class add constraint unique_class_teacher unique(class_teacher);  //唯一约束

删除约束

alter table student drop constraint student_age_check;

//非空约束是没有名称的

alter table student alter column student_name drop not null;

修改默认值

  • 不会影响已保存的行数据
alter table student alter column age set default 15;

删除默认值

  • 不会影响已保存的行数据
alter table student alter column age drop default;

修改字段数据类型

  • 只有每一行的该项数据都能隐式地替换成新的类型,转行才能成功;
alter table student alter column student_name type text;
  • 注意PostgesSQL会试图把字段的约束/默认值做相应转换,但不一定会成功;所有最好成功改变类型后再手动添加一遍;

重命名字段

alter table book rename column book_no to book_id;

重命名表

alter table class rename to classes;

增加约束时的判断方法

  • 对表增加约束,如果约束已经存在则跳过;
 CREATE OR REPLACE FUNCTION create_constraint_if_not_exists (t_name text, c_name text, constraint_sql text)
RETURNS void
AS
$$
begin
if not exists (select constraint_name
from information_schema.constraint_column_usage
where table_name = t_name and constraint_name = c_name) then
execute 'ALTER TABLE ' || t_name || ' ADD CONSTRAINT ' || c_name || ' ' || constraint_sql;
end if;
end;
$$
LANGUAGE plpgsql VOLATILE; //excute SELECT create_constraint_if_not_exists ('user_sessions', 'session_pkey', 'PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE');

psql-06表:约束的更多相关文章

  1. 常用sql语句总结(二)(更新数据,序列,创建数据表,约束,注释)

    常用sql语句总结(二)(更新数据,序列,创建数据表,约束,注释) 一. 增 INSERT INTO 数据表(字段,字段,-) VALUES(值,值-); INSERT INTO emp(empno, ...

  2. Sql中常用的创建表 约束 主外键 增删改查的语句

    创建数据库 USE master; GO --日记数据库 create database DiaryBase on ( name=DiaryBase_Dat,--逻辑名称 FILENAME='c:\D ...

  3. oracle习题练习-表空间-用户-表-约束

    题一 1.       创建名字为hy_tablespace的表空间,默认大小为10M;@@ 2.       创建一个用户,用户名以自己名字命名,并指定命名空间为hy_tablespace;@@@@ ...

  4. SQL Tuning 基础概述06 - 表的关联方式:Nested Loops Join,Merge Sort Join & Hash Join

    nested loops join(嵌套循环)   驱动表返回几条结果集,被驱动表访问多少次,有驱动顺序,无须排序,无任何限制. 驱动表限制条件有索引,被驱动表连接条件有索引. hints:use_n ...

  5. css整理-06 表和列表

    表格式化 表布局 table, display:table caption, display: table-caption thead, display: table-header-group tbo ...

  6. 22----2013.06.29---HTML--html介绍.超链接和图片,表格,表单,表单标签,meta,复习当天内容

    01 HTML HTML :Hypertext Markup Language   超文本标记语言(类似于 裸奔的人.) 作用:向用户展示信息. CSS: Cascading 层叠样式表(类似于 人的 ...

  7. MySQL数据库基础(二)(约束以及修改数据表)

    一,约束以及修改数据表 约束的作用?1.约束保证数据的完整性.一致性:2.约束分为表级约束.列级约束:3.约束类型包括:NOT NULL(非空约束).PRIMARY KEY(主键约束).UNIQUE ...

  8. MySQL基础(二)(约束以及修改数据表)

    一,约束以及修改数据表 约束的作用?1.约束保证数据的完整性.一致性:2.约束分为表级约束.列级约束:3.约束类型包括:NOT NULL(非空约束).PRIMARY KEY(主键约束).UNIQUE ...

  9. MySQL数据库3分组与单表、多表查询

    目录 一.表操作的补充 1.1null 和 not null 1.2使用not null的时候 二.单表的操作(import) 2.1分组 2.1.1聚合函数 2.1.2group by 2.1.3h ...

随机推荐

  1. 浅析 Cordova for iOS

    转自@夏小BO的技术博客: Cordova,对这个名字大家可能比较陌生,大家肯定听过 PhoneGap 这个名字,Cordova 就是 PhoneGap 被 Adobe 收购后所改的名字.(Cordo ...

  2. xmpp SASL 定义

    SASL 定义 <摘抄自:xmpp_3920> [SASL]的 profiling 需求要求协议定义 供以下信息: 服务名:“xmpp” 初始序列:初始实体 供一个开放 XML 流头后,并 ...

  3. device host global 函数要求

    转自:https://kheresy.wordpress.com/2007/11/05/nvidia-cuda-api%EF%BC%88%E4%B8%8A%EF%BC%89/ Function typ ...

  4. 关于Visual Studio 2013 编译 multi-byte character set MFC程序出现 MSB8031 错误的解决办法

    转自:http://blog.csdn.net/xiaochunzao/article/details/16987703 Visual Studio 2013 编译旧的 multi-byte char ...

  5. 群内大神与你交流WEB经验 业内专家指点就职技巧

    就知道你是一个有理想要抱负的人,不会满足于做一个初级的前端开发工程师.在接下来的这个阶段,我们将走上前端开发的进阶之路,将自己的能力再往上拔高一个等级.同样,薪资也会往上升一个等级!但是,如果你是一个 ...

  6. Centos7 设置Swap分区

    1.使用dd命令创建一个swap交换文件 dd if=/dev/zero of=/home/swap bs=1024 count=1024000 2.制作为swap格式文件: mkswap /home ...

  7. IOS开发之实现App消息推送

    转自:http://blog.csdn.net/shenjie12345678/article/details/41120637 第一部分 首先第一步当然是介绍一下苹果的推送机制(APNS)咯(ps: ...

  8. myaql常用函数

    一.数学函数 abs(x)   返回x的绝对值 bin(x)   返回x的二进制(oct返回八进制,hex返回十六进制) ceiling(x)   返回大于x的最小整数值 exp(x)   返回值e( ...

  9. Cocoapods 更新后 使用

    platform:ios,'8.0'target 'APPNAME' do pod 'SMSSDK' pod 'MBProgressHUD', '0.9.1' pod 'AFNetworking', ...

  10. SQLServer子查询

    in谓词子查询 select * from dbo.Worker where did in (select dID from DepartMent) 比较运算子查询 select * from Wor ...