学习表的约束、表的默认值、自增类型等技术
1.创建表的时候定义列级约束
drop table if exists tab1;
create table tab1(
c1 number(10) primary key,
c2 varchar(10) not null,
c3 int
);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tab1_pkey" for table "tab1"
CREATE TABLE
omm=# --插入数据
omm=# insert into tab1 values(1,'aaa',50);
INSERT 0 1
omm=# --查看数据
omm=# select * from tab1;
omm=# c1 | c2 | c3
----+-----+----
1 | aaa | 50
(1 row)
--查看约束
\d tab1
Table "public.tab1"
Column | Type | Modifiers
--------+-----------------------+-----------
c1 | numeric(10,0) | not null
c2 | character varying(10) | not null
c3 | integer |
Indexes:
"tab1_pkey" PRIMARY KEY, btree (c1) TABLESPACE pg_default
2.创建表的时候定义表级约束
drop table if exists tab2;
create table tab2(
c1 bigint,
c2 varchar(10) not null, -- 创建列级not null约束
c3 int,
primary key(c1) -- 创建表级约束
);
omm=# drop table if exists tab2;
NOTICE: table "tab2" does not exist, skipping
DROP TABLE
omm=# create table tab2(
omm(# c1 bigint,
omm(# c2 varchar(10) not null, -- 创建列级not null约束
omm(# omm(# c3 int,
primary key(c1) -- 创建表级约束
omm(# );
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tab2_pkey" for table "tab2"
CREATE TABLE
omm=# insert into tab2 values(1,'bbb',50);
INSERT 0 1
omm=# select * from tab2;
c1 | c2 | c3
----+-----+----
1 | bbb | 50
(1 row)
\d tab2
Table "public.tab2"
Column | Type | Modifiers
--------+-----------------------+-----------
c1 | bigint | not null
c2 | character varying(10) | not null
c3 | integer |
Indexes:
"tab2_pkey" PRIMARY KEY, btree (c1) TABLESPACE pg_default
3.为表的属性定义默认值
drop table if exists tab3;
create table tab3(
c1 bigint,
c2 varchar(28) not null,
c3 int default 100, -- 为该列定义默认值为20
primary key(c1)
);
--下面的SQL insert语句,在向表tab3插入数据时,没有提供c3列的值:
insert into tab3(c1,c2) values(1,'user1');
insert into tab3(c1,c2) values(2,'user2');
select * from tab3;

4.如果在创建表的时候,没有为某列定义默认值,缺省的默认值是空值null
drop table if exists tab4;
create table tab4(
c1 bigint,
c2 varchar(50) not null,
c3 int,
primary key(c1)
);
insert into tab4(c1,c2) values(1,'user1');
select * from tab4;

5.创建表时使用自增数据类型
drop table if exists tab5;
create table tab5(c1 serial NOT NULL,c2 varchar(20));
--为表tab5插入3条记录,并查看插入数据后的表的数据:
insert into tab5(c2) values('user1');
insert into tab5(c2) values('user2');
insert into tab5(c2) values('user3');
--可以看到每插入一条记录到表tab5后,列c1的值会自增1。
select * from tab5;

6.使用现有的表创建新表
--执行下面的SQL语句,将创建新表,并且会将旧表的数据拷贝给新表:
DROP TABLE if exists tab6;
CREATE TABLE tab6 AS SELECT * FROM tab5;
SELECT * FROM tab6;
--执行下面的SQL语句,创建和旧表的表结构相同的新表,但是不会将旧表的数据拷贝给新表:
DROP TABLE if exists tab7;
CREATE TABLE tab7 AS SELECT * FROM tab5 WHERE 1=2;
SELECT * FROM tab7;

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




