默认值

  • 可以理解为建表时没定义的默认值为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. JS 基本语句

    1.循环中必备的条件: 初始值  循环条件  状态改变   循环体 for(初始值  循环条件  状态改变)    {       循环体     } for(var i=0;i<100;i++ ...

  2. 当你的IIS需要运行ASP网站时,需要这样配置下你的IIS

    1.进入Windows 7的 控制面板->程序和功能->选择左上角的 打开或关闭Windows功能 2.现在出现了安装Windows功能的选项菜单,注意选择的项目,红色箭头所示的地方都要选 ...

  3. Android笔记:限定符

    屏幕特征限定符描述大小 small 提供给小屏幕设备的资源 normal 提供给中等屏幕设备的资源 large 提供给大屏幕设备的资源 xlarge 提供给超大屏幕设备的资源分辨率 ldpi 提供给低 ...

  4. 定时器(NSTimer)

    iOS中定时器NSTimer的使用 1.初始化 + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget sel ...

  5. Mysql游标

    14.6.6.1 Cursor CLOSE Syntax 14.6.6.2 Cursor DECLARE Syntax 14.6.6.3 Cursor FETCH Syntax 14.6.6.4 Cu ...

  6. No space left on device 解决Linux系统磁盘空间满的办法

    最近Linux电脑在执行mvn时候总是报错: No space left on device   原因是磁盘空间满了,我马上加了20G的硬盘容量,但是还是报错,上网查了一下,发现了解决方法,我用了其中 ...

  7. 常用iOS的第三方框架

    图像:1.图片浏览控件MWPhotoBrowser       实现了一个照片浏览器类似 iOS 自带的相册应用,可显示来自手机的图片或者是网络图片,可自动从网络下载图片并进行缓存.可对图片进行缩放等 ...

  8. UVA 10192 Vacation

    裸最长公共子序列 #include<time.h> #include <cstdio> #include <iostream> #include<algori ...

  9. iOS 判断第一个字符是数字还是汉字

       NSString *titleStr = @"琳小兮";  //先截取字符串,拿到第一个字符         NSString *firstStr = [titleStr s ...

  10. Python 自然语言处理(1) 计数词汇

    Python有一个自然语言处理的工具包,叫做NLTK(Natural Language ToolKit),可以帮助你实现自然语言挖掘,语言建模等等工作.但是没有NLTK,也一样可以实现简单的词类统计. ...