一、create table 语句概述
postgresql 使用 create table 语句来创建数据库表格,这是数据库设计中最基础也是最重要的操作之一。通过创建表格,我们定义了数据的存储结构和约束条件。
基本语法
create table table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnn datatype, primary key( 一个或多个列 ) );
二、语法元素详解
1. 表名(table_name)
表名必须满足以下条件:
- 在当前数据库中唯一
- 不能与同一模式下的其他表、序列、索引、视图或外部表重名
- 通常使用小写字母和下划线组合(如
employee_info)
2. 列定义(columnn datatype)
每个列定义包含:
- 列名
- 数据类型
- 可选的约束条件
3. 主键(primary key)
主键是唯一标识表中每一行的列或列组合,具有以下特性:
- 不能为null
- 值必须唯一
- 一个表只能有一个主键
三、创建表示例
示例1:创建公司表
create table company( id int primary key not null, name text not null, age int not null, address char(50), salary real );
示例2:创建部门表
create table department( id int primary key not null, dept char(50) not null, emp_id int not null );
四、表格结构查看
postgresql提供了方便的元命令来查看表格结构:
1. 查看所有表
\d
输出示例:
list of relations schema | name | type | owner --------+------------+-------+---------- public | company | table | postgres public | department | table | postgres (2 rows)
2. 查看特定表结构
\d company
输出示例:
table "public.company"
column | type | collation | nullable | default
---------+---------------+-----------+----------+---------
id | integer | | not null |
name | text | | not null |
age | integer | | not null |
address | character(50) | | |
salary | real | | |
indexes:
"company_pkey" primary key, btree (id)
五、表格创建流程

六、表格架构图

七、数据类型选择指南
postgresql提供了丰富的数据类型,常见的有:
| 数据类型 | 描述 | 示例 |
|---|---|---|
| int/integer | 整数 | 年龄、数量 |
| serial | 自增整数 | 自动生成的id |
| text | 可变长度字符串 | 名称、描述 |
| varchar(n) | 有限长度字符串 | 短文本 |
| char(n) | 固定长度字符串 | 编码、固定格式 |
| real/float | 浮点数 | 价格、测量值 |
| numeric(p,s) | 精确小数 | 金融数据 |
| boolean | 布尔值 | 是否、真假 |
| date | 日期 | 出生日期 |
| timestamp | 时间戳 | 创建时间 |
八、常见约束条件
- not null:确保列不能有null值
- unique:确保列中的所有值都不同
- primary key:not null和unique的组合
- foreign key:确保一个表中的数据匹配另一个表中的值
- check:确保列中的值满足特定条件
- default:为列设置默认值
九、高级表创建选项
1. 继承表
postgresql支持表继承,这是其特色功能之一:
create table cities (
name text,
population real,
elevation int
);
create table capitals (
state char(2)
) inherits (cities);
2. 分区表
对于大型表,可以使用分区提高性能:
create table measurement (
city_id int not null,
logdate date not null,
peaktemp int,
unitsales int
) partition by range (logdate);
十、最佳实践
- 命名规范:使用一致的命名约定(如全小写、下划线分隔)
- 主键选择:优先使用无业务意义的自增id
- 数据类型:选择最合适的最小数据类型
- 约束:尽可能添加约束以保证数据完整性
- 文档:为表和列添加注释(使用comment语句)
- 权限:设置适当的表权限
十一、总结
postgresql的create table语句功能强大而灵活,通过合理设计表结构,可以为应用程序提供坚实的数据存储基础。掌握表创建不仅是数据库管理的基础,也是优化数据库性能的第一步。在实际应用中,应根据业务需求选择合适的数据类型和约束条件,确保数据的完整性和一致性。
到此这篇关于postgresql创建表示例及最佳实践详解的文章就介绍到这了,更多相关postgresql创建表内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论