默认值

  • 可以理解为建表时没定义的默认值为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. 通过JavaScript操作HTML中select标签

    添加: Js代码 1.function selectChange() 2.{ 3.var sel=document.getElementById("select1"); 4. Op ...

  2. IOS-Uikit框架介绍

    •UIKit可识别三种类型的输入事件: –触摸事件 –运动(加速计)事件 –远程控制事件 IKit框架将触击信息封装为一个UIEvent对象,并派发给恰当的视图(有关UIKit如何将事件递送给您的视图 ...

  3. 关闭Eclipse的控制台console自动跳出

    一.背景 在eclipse中进行开发,尤其是在后台有项目运行的时候,当有log或者错误需要打印到console中时,控制台就会被自动弹出,恰好这时候你又在编写代码,就会感觉瞬间想杀人,下面我们就来分享 ...

  4. [Android Pro] linux下查看一个文件的属性(ls,lsattr,file,stat)

    reference to : http://blog.chinaunix.net/uid-28458801-id-4615294.html 查看文件属性有多种方法,且这些方法中偏向不同,具体如下: 1 ...

  5. 零基础十分钟学会用git在coding.net上传(pull)和push

    ---恢复内容开始--- 对于入门者来说,特别是刚刚接触计算机的人来说,模仿是最快的学习方式了,先能够会使用(对于初学者来说,这种使用新事物的感觉很能爽的)至于原理,以后再说.下面先让初学者快速的学会 ...

  6. Stanford大学机器学习公开课(四):牛顿法、指数分布族、广义线性模型

    (一)牛顿法解最大似然估计 牛顿方法(Newton's Method)与梯度下降(Gradient Descent)方法的功能一样,都是对解空间进行搜索的方法.其基本思想如下: 对于一个函数f(x), ...

  7. Lattice Diamond 学习之编译、检查和设置约束

    在新建工程以及完成代码的输入之后.则就要进行编译,并检测错误. 一. Generate Hierarchy(产生层次结构). 1. 点击Generate Hierarchy 图标或者Design -- ...

  8. EasyUi–8.datebox赋值的问题

    这个问题要从EasyUI的datebox组件说起,小菜用这个组件的时候,发现用$("#id").val()这种形式,居然拿不到文本框的值!      经过度娘的帮助,发现可以用$( ...

  9. Linux 标准目录结构

    初学Linux,首先需要弄清Linux 标准目录结构 / root --- 启动Linux时使用的一些核心文件.如操作系统内核.引导程序Grub等. home --- 存储普通用户的个人文件 ftp ...

  10. JavaWeb学习之什么JSP、JSP是如何工作的、JSP语言(各种指令和九大内置对象)、EL表达式简单使用(5)

    1.什么JSP * servlet:java编写的处理动态web的技术 * 特点:Java代码中嵌套html代码 * jsp * 特点:HTMl代码中嵌套java代码 * %tomcat%/conf/ ...