字段类型

数值类型

Name Storage Size Description Range
smallint 2 bytes small-range integer -32768 to +32767
integer 4 bytes typical choice for integer -2147483648 to +2147483647
bigint 8 bytes large-range integer -9223372036854775808 to +9223372036854775807
decimal variable user-specified precision, exact up to 131072 digits before the decimal point; up to 16383 digits after the decimal point
numeric variable user-specified precision, exact up to 131072 digits before the decimal point; up to 16383 digits after the decimal point
real 4 bytes variable-precision, inexact 6 decimal digits precision
double precision 8 bytes variable-precision, inexact 15 decimal digits precision
smallserial 2 bytes small autoincrementing integer 1 to 32767
serial 4 bytes autoincrementing integer 1 to 2147483647
bigserial 8 bytes large autoincrementing integer 1 to 9223372036854775807

金额类型

Name Storage Size Description Range
money 8 bytes currency amount -92233720368547758.08 to +92233720368547758.07

numeric, int, 和 bigint 类型可以转为 money. 从 real 和 double precision 则需要先转为 numeric first, 例如

  1. SELECT '12.34'::float8::numeric::money;

money 可以无损转换为 numeric, 转换为其他类型则会有精度损失, 例如

  1. SELECT '52093.89'::money::numeric::float8;

字符串类型

Name Description
character varying(n), varchar(n) variable-length with limit
character(n), char(n) fixed-length, blank padded
text variable unlimited length

二进制类型

Name Storage Size Description
bytea 1 or 4 bytes plus the actual binary string variable-length binary string

二进制表示, 使用 \x sequence

  1. SELECT '\xDEADBEEF';

时间类型

Name Storage Size Description Low Value High Value Resolution
timestamp [ (p) ] 8 bytes both date and time (no time zone) 4713 BC 294276 AD 1 microsecond
timestamp [ (p) ] with time zone 8 bytes both date and time, with time zone 4713 BC 294276 AD 1 microsecond
date 4 bytes date (no time of day) 4713 BC 5874897 AD 1 day
time [ (p) ] 8 bytes time of day (no date) 00:00:00 24:00:00 1 microsecond
time [ (p) ] with time zone 12 bytes time of day (no date), with time zone 00:00:00+1559 24:00:00-1559 1 microsecond
interval [ fields ] [ (p) ] 16 bytes time interval -178000000 years 178000000 years 1 microsecond

其中, interval类型可以为以下值

  1. YEAR
  2. MONTH
  3. DAY
  4. HOUR
  5. MINUTE
  6. SECOND
  7. YEAR TO MONTH
  8. DAY TO HOUR
  9. DAY TO MINUTE
  10. DAY TO SECOND
  11. HOUR TO MINUTE
  12. HOUR TO SECOND
  13. MINUTE TO SECOND

布尔类型

Name Storage Size Description
boolean 1 byte state of true or false

枚举类型

声明

  1. CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');

使用

  1. CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
  2. CREATE TABLE person (
  3. name text,
  4. current_mood mood
  5. );
  6. INSERT INTO person VALUES ('Moe', 'happy');
  7. SELECT * FROM person WHERE current_mood = 'happy';
  8. name | current_mood
  9. ------+--------------
  10. Moe | happy
  11. (1 row)

排序和比较

  1. INSERT INTO person VALUES ('Larry', 'sad');
  2. INSERT INTO person VALUES ('Curly', 'ok');
  3. SELECT * FROM person WHERE current_mood > 'sad';
  4. name | current_mood
  5. -------+--------------
  6. Moe | happy
  7. Curly | ok
  8. (2 rows)
  9. SELECT * FROM person WHERE current_mood > 'sad' ORDER BY current_mood;
  10. name | current_mood
  11. -------+--------------
  12. Curly | ok
  13. Moe | happy
  14. (2 rows)
  15. SELECT name
  16. FROM person
  17. WHERE current_mood = (SELECT MIN(current_mood) FROM person);
  18. name
  19. -------
  20. Larry
  21. (1 row)

地理位置类型

Name Storage Size Description Representation
point 16 bytes Point on a plane (x,y)
line 32 bytes Infinite line {A,B,C}
lseg 32 bytes Finite line segment ((x1,y1),(x2,y2))
box 32 bytes Rectangular box ((x1,y1),(x2,y2))
path 16+16n bytes Closed path (similar to polygon) ((x1,y1),...)
path 16+16n bytes Open path [(x1,y1),...]
polygon 40+16n bytes Polygon (similar to closed path) ((x1,y1),...)
circle 24 bytes Circle <(x,y),r> (center point and radius)

网络地址类型

Name Storage Size Description
cidr 7 or 19 bytes IPv4 and IPv6 networks
inet 7 or 19 bytes IPv4 and IPv6 hosts and networks
macaddr 6 bytes MAC addresses
macaddr8 8 bytes MAC addresses (EUI-64 format)

inet 和 cidr 的区别

二者最关键的区别在于, inet 允许IP地址在掩码区域外有非零值, 例如 "192.168.0.1/24", 这个值对于 cidr 是不允许的.

如果不喜欢 inet 或 cidr 输出的格式, 可以使用 host, text 和 abbrev 这些函数进行处理.

二进制串类型

使用0和1表示的字符串, sql示例

  1. CREATE TABLE test (a BIT(3), b BIT VARYING(5));
  2. INSERT INTO test VALUES (B'101', B'00');
  3. INSERT INTO test VALUES (B'10', B'101');
  4. ERROR: bit string length 2 does not match type bit(3)
  5. INSERT INTO test VALUES (B'10'::bit(3), B'101');
  6. SELECT * FROM test;
  7. a | b
  8. -----+-----
  9. 101 | 00
  10. 100 | 101

文本搜索类型

PostgreSQL provides two data types that are designed to support full text search, which is the activity of searching through a collection of natural-language documents to locate those that best match a query. The tsvector type represents a document in a form optimized for text search; the tsquery type similarly represents a text query. Chapter 12 provides a detailed explanation of this facility, and Section 9.13 summarizes the related functions and operators.

tsvector, tsquery

UUID类型

字段长16 byte(128-bit), 用于分布式系统可以提供更好的唯一性保证(相对于自增序列). 一个 UUID 是一组短横线分隔的十六进制小写数字,

格式为: 一组8位, 三组4位, 最后是一组12位, 一共32位组成128bit. 例如

  1. a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11

XML类型

  1. XMLPARSE ( { DOCUMENT | CONTENT } value)
  2. XMLPARSE (DOCUMENT '<?xml version="1.0"?><book><title>Manual</title><chapter>...</chapter></book>')
  3. XMLPARSE (CONTENT 'abc<foo>bar</foo><bar>foo</bar>')
  4. XMLSERIALIZE ( { DOCUMENT | CONTENT } value AS type )

JSON类型

数组类型

  1. CREATE TABLE sal_emp (
  2. name text,
  3. pay_by_quarter integer[],
  4. schedule text[][]
  5. );
  6. CREATE TABLE tictactoe (
  7. squares integer[3][3]
  8. );

增和查

  1. INSERT INTO sal_emp
  2. VALUES ('Bill',
  3. '{10000, 10000, 10000, 10000}',
  4. '{{"meeting", "lunch"}, {"training", "presentation"}}');
  5. INSERT INTO sal_emp
  6. VALUES ('Carol',
  7. '{20000, 25000, 25000, 25000}',
  8. '{{"breakfast", "consulting"}, {"meeting", "lunch"}}');
  9. The result of the previous two inserts looks like this:
  10. SELECT * FROM sal_emp;
  11. name | pay_by_quarter | schedule
  12. -------+---------------------------+-------------------------------------------
  13. Bill | {10000,10000,10000,10000} | {{meeting,lunch},{training,presentation}}
  14. Carol | {20000,25000,25000,25000} | {{breakfast,consulting},{meeting,lunch}}
  15. (2 rows)
  16. -- 使用 ARRAY
  17. INSERT INTO sal_emp
  18. VALUES ('Bill',
  19. ARRAY[10000, 10000, 10000, 10000],
  20. ARRAY[['meeting', 'lunch'], ['training', 'presentation']]);
  21. INSERT INTO sal_emp
  22. VALUES ('Carol',
  23. ARRAY[20000, 25000, 25000, 25000],
  24. ARRAY[['breakfast', 'consulting'], ['meeting', 'lunch']]);
  25. SELECT name FROM sal_emp WHERE pay_by_quarter[1] <> pay_by_quarter[2];
  26. name
  27. -------
  28. Carol
  29. (1 row)
  30. SELECT schedule[1:2][1:1] FROM sal_emp WHERE name = 'Bill';
  31. schedule
  32. ------------------------
  33. {{meeting},{training}}
  34. (1 row)
  35. SELECT schedule[1:2][2] FROM sal_emp WHERE name = 'Bill';
  36. schedule
  37. -------------------------------------------
  38. {{meeting,lunch},{training,presentation}}
  39. (1 row)

  1. UPDATE sal_emp SET pay_by_quarter = '{25000,25000,27000,27000}'
  2. WHERE name = 'Carol';
  3. -- 使用 ARRAY
  4. UPDATE sal_emp SET pay_by_quarter = ARRAY[25000,25000,27000,27000]
  5. WHERE name = 'Carol';

自定义类型, 组合类型

  1. CREATE TYPE complex AS (
  2. r double precision,
  3. i double precision
  4. );
  5. CREATE TYPE inventory_item AS (
  6. name text,
  7. supplier_id integer,
  8. price numeric
  9. );
  10. CREATE TABLE on_hand (
  11. item inventory_item,
  12. count integer
  13. );
  14. INSERT INTO on_hand VALUES (ROW('fuzzy dice', 42, 1.99), 1000);
  15. CREATE FUNCTION price_extension(inventory_item, integer) RETURNS numeric
  16. AS 'SELECT $1.price * $2' LANGUAGE SQL;
  17. SELECT price_extension(item, 10) FROM on_hand;
  18. CREATE TABLE inventory_item (
  19. name text,
  20. supplier_id integer REFERENCES suppliers,
  21. price numeric CHECK (price > 0)
  22. );

Table相关SQL

建表 CREATE TABLE

建表说明: https://www.postgresql.org/docs/14/sql-createtable.html

完整的建表语法

  1. CREATE [ { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ( [
  2. { column_name data_type [ COMPRESSION compression_method ] [ COLLATE collation ] [ column_constraint [ ... ] ]
  3. | table_constraint
  4. | LIKE source_table [ like_option ... ] }
  5. [, ... ]
  6. ] )
  7. [ INHERITS ( parent_table [, ... ] ) ]
  8. [ PARTITION BY { RANGE | LIST | HASH } ( { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [, ... ] ) ]
  9. [ USING method ]
  10. [ WITH ( storage_parameter [= value] [, ... ] ) | WITHOUT OIDS ]
  11. [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]
  12. [ TABLESPACE tablespace_name ]
  13. -- column_constraint 字段约束的格式
  14. [ CONSTRAINT constraint_name ]
  15. { NOT NULL |
  16. NULL |
  17. CHECK ( expression ) [ NO INHERIT ] |
  18. DEFAULT default_expr |
  19. GENERATED ALWAYS AS ( generation_expr ) STORED |
  20. GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ] |
  21. UNIQUE index_parameters |
  22. PRIMARY KEY index_parameters |
  23. REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]
  24. [ ON DELETE referential_action ] [ ON UPDATE referential_action ] }
  25. [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
  26. -- table_constraint 表约束的格式
  27. [ CONSTRAINT constraint_name ]
  28. { CHECK ( expression ) [ NO INHERIT ] |
  29. UNIQUE ( column_name [, ... ] ) index_parameters |
  30. PRIMARY KEY ( column_name [, ... ] ) index_parameters |
  31. EXCLUDE [ USING index_method ] ( exclude_element WITH operator [, ... ] ) index_parameters [ WHERE ( predicate ) ] |
  32. FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
  33. [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE referential_action ] [ ON UPDATE referential_action ] }
  34. [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]

还有OF type_namePARTITION OF parent_table两种, 比较少用.

TEMPORARY | TEMP

临时表, 在session结束后自动drop

UNLOGGED

对UNLOGGED表的写入不记入 write-ahead 日志, 所以比普通表快. 如果数据库崩溃(crash)或非常关机, UNLOGGED表会被自动truncate. UNLOGGED表不能replicated, 基于UNLOGGED表的索引也会是UNLOGGED的.

COMPRESSION

压缩仅用于变长字段类型, and is used only when the column's storage mode is main or extended

PARTITION BY { RANGE | LIST | HASH } ( { column_name | ( expression ) } [ opclass ] [, ...] )

用于对表进行分区. The table thus created is called a partitioned table. The parenthesized list of columns or expressions forms the partition key for the table. When using range or hash partitioning, the partition key can include multiple columns or expressions (up to 32, but this limit can be altered when building PostgreSQL), but for list partitioning, the partition key must consist of a single column or expression.

Range and list partitioning require a btree operator class, while hash partitioning requires a hash operator class. If no operator class is specified explicitly, the default operator class of the appropriate type will be used; if no default operator class exists, an error will be raised. When hash partitioning is used, the operator class used must implement support function 2 (see Section 38.16.3 for details).

表分区后, 会变成一系列子表, 原表本身变成空表. 向原表的写入, 会路由到对应的子表, 如果对应的分区不存在就会报错. 分区表不支持 EXCLUDE 约束, 但是在子表中可以定义.

NOT NULL, NULL, DEFAULT, UNIQUE, PRIMARY KEY

和MySQL用法一样

GENERATED ALWAYS AS ( generation_expr ) STORED

类似于view, 这种字段由其他字段(非generated)生成, 不能写只能读

GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ]

表示此字段为ID字段, 使用一个绑定的sequence自动赋值, 并且这个字段一定是NOT NULL. This clause creates the column as an identity column. It will have an implicit sequence attached to it and the column in new rows will automatically have values from the sequence assigned to it. Such a column is implicitly NOT NULL.

The clauses ALWAYS and BY DEFAULT determine how explicitly user-specified values are handled in INSERT and UPDATE commands.

TABLESPACE tablespace_name

表空间, 未指定则使用 default_tablespace, 如果是临时表, 则使用 temp_tablespaces.

建表示例

设置主键

  1. CREATE TABLE films (
  2. code char(5) CONSTRAINT firstkey PRIMARY KEY,
  3. title varchar(40) NOT NULL,
  4. did integer NOT NULL,
  5. date_prod date,
  6. kind varchar(10),
  7. len interval hour to minute
  8. );
  9. CREATE TABLE distributors (
  10. did integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
  11. name varchar(40) NOT NULL CHECK (name <> '')
  12. );
  13. CREATE TABLE films (
  14. code char(5),
  15. title varchar(40),
  16. did integer,
  17. date_prod date,
  18. kind varchar(10),
  19. len interval hour to minute,
  20. CONSTRAINT code_title PRIMARY KEY(code,title)
  21. );
  22. -- 下面两个是等价的
  23. CREATE TABLE distributors (
  24. did integer,
  25. name varchar(40),
  26. PRIMARY KEY(did)
  27. );
  28. CREATE TABLE distributors (
  29. did integer PRIMARY KEY,
  30. name varchar(40)
  31. );

二维数组字段

  1. CREATE TABLE array_int (
  2. vector int[][]
  3. );

唯一约束字段

  1. CREATE TABLE films (
  2. code char(5),
  3. title varchar(40),
  4. did integer,
  5. date_prod date,
  6. kind varchar(10),
  7. len interval hour to minute,
  8. CONSTRAINT production UNIQUE(date_prod)
  9. );
  10. CREATE TABLE distributors (
  11. did integer,
  12. name varchar(40) UNIQUE
  13. );

表达式约束字段

  1. CREATE TABLE distributors (
  2. did integer,
  3. name varchar(40),
  4. CONSTRAINT con1 CHECK (did > 100 AND name <> '')
  5. );

设置字段默认值

  1. CREATE TABLE distributors (
  2. name varchar(40) DEFAULT 'Luso Films',
  3. did integer DEFAULT nextval('distributors_serial'),
  4. modtime timestamp DEFAULT current_timestamp
  5. );

非空约束

  1. CREATE TABLE distributors (
  2. did integer CONSTRAINT no_null NOT NULL,
  3. name varchar(40) NOT NULL
  4. );

对表进行分区

  1. CREATE TABLE measurement (
  2. logdate date not null,
  3. peaktemp int,
  4. unitsales int
  5. ) PARTITION BY RANGE (logdate);
  6. -- 分区依据多个字段
  7. CREATE TABLE measurement_year_month (
  8. logdate date not null,
  9. peaktemp int,
  10. unitsales int
  11. ) PARTITION BY RANGE (EXTRACT(YEAR FROM logdate), EXTRACT(MONTH FROM logdate));
  12. -- 使用list分区
  13. CREATE TABLE cities (
  14. city_id bigserial not null,
  15. name text not null,
  16. population bigint
  17. ) PARTITION BY LIST (left(lower(name), 1));
  18. -- 使用hash分区
  19. CREATE TABLE orders (
  20. order_id bigint not null,
  21. cust_id bigint not null,
  22. status text
  23. ) PARTITION BY HASH (order_id);
  24. -- 使用区间分区
  25. CREATE TABLE measurement_y2016m07
  26. PARTITION OF measurement (
  27. unitsales DEFAULT 0
  28. ) FOR VALUES FROM ('2016-07-01') TO ('2016-08-01');

分别创建 表measurement_year_month 的各个分区子表

  1. CREATE TABLE measurement_ym_older
  2. PARTITION OF measurement_year_month
  3. FOR VALUES FROM (MINVALUE, MINVALUE) TO (2016, 11);
  4. CREATE TABLE measurement_ym_y2016m11
  5. PARTITION OF measurement_year_month
  6. FOR VALUES FROM (2016, 11) TO (2016, 12);
  7. CREATE TABLE measurement_ym_y2016m12
  8. PARTITION OF measurement_year_month
  9. FOR VALUES FROM (2016, 12) TO (2017, 01);
  10. CREATE TABLE measurement_ym_y2017m01
  11. PARTITION OF measurement_year_month
  12. FOR VALUES FROM (2017, 01) TO (2017, 02);

或者

  1. CREATE TABLE orders_p1 PARTITION OF orders
  2. FOR VALUES WITH (MODULUS 4, REMAINDER 0);
  3. CREATE TABLE orders_p2 PARTITION OF orders
  4. FOR VALUES WITH (MODULUS 4, REMAINDER 1);
  5. CREATE TABLE orders_p3 PARTITION OF orders
  6. FOR VALUES WITH (MODULUS 4, REMAINDER 2);
  7. CREATE TABLE orders_p4 PARTITION OF orders
  8. FOR VALUES WITH (MODULUS 4, REMAINDER 3);

对于以上的分区方式, 可以设置一个默认子分区

  1. CREATE TABLE cities_partdef
  2. PARTITION OF cities DEFAULT;

PostgreSQL 的字段类型和表操作笔记的更多相关文章

  1. PostgreSQL 修改字段类型从int到bigint

    由于现在pg的版本,修改int到bigint仍然需要rewrite表,会导致表阻塞,无法使用.但可以考虑其他方式来做.此问题是排查现网pg使用序列的情况时遇到的. 由于int的最大值只有21亿左右,而 ...

  2. Django ORM字段类型 单表增删改查 万能的双下划线

    1.ORM三种模型 模型之间的三种关系:一对一,一对多,多对多. 一对一:实质就是在主外键(author_id就是foreign key)的关系基础上,给外键加了一个UNIQUE=True的属性: 一 ...

  3. PostgreSQL 中字段类型varchar

    PostgreSql数据库中varchar类型与sql server中字段用法有差别,PostgreSql中如果字段设置为varchar类型长度为10,则无论存字母.数字或其它符号,长度最大为10个, ...

  4. SqlServer不允许更改字段类型(表中已有数据)

    工具-选项-设计器-阻止保存要求重新创建表的更改,√去掉.

  5. mysql与clickhouse的字段类型对应表

  6. Oracle-表的字段增加修改删除操作

    表结构修改 ALTER TABLE SCOTT.TEST RENAME TO TEST1--修改表名 ALTER TABLE SCOTT.TEST RENAME COLUMN NAME TO NAME ...

  7. Django学习笔记(7)——单表操作和多表操作

    单表操作 1,创建模型 创建名为book的APP,在book下的models.py中创建模型: from django.db import models # Create your models he ...

  8. 孤荷凌寒自学python第四十九天继续研究跨不同类型数据库的通用数据表操作函数

    孤荷凌寒自学python第四十九天继续研究跨不同类型数据库的通用数据表操作函数 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天继续建构自感觉用起来顺手些的自定义模块和类的代码. 不同类型 ...

  9. Access sql语句创建表及字段类型

    创建一张空表: Sql="Create TABLE [表名]" 创建一张有字段的表: Sql="Create TABLE [表名]([字段名1] MEMO NOT NUL ...

随机推荐

  1. 从零开始, 开发一个 Web Office 套件 (2): 富文本编辑器

    书接前文: 从零开始, 开发一个 Web Office 套件 (1): 富文本编辑器 这是一个系列博客, 最终目的是要做一个基于HTML Canvas 的, 类似于微软 Office 的 Web Of ...

  2. K8S配置多集群访问

    中文官档: http://docs.kubernetes.org.cn/823.html 背景:我们通过会有多个k8s集群,例如集群(cn-k8s)和集群(jp-k8s),那个就需要有一台服务器可以同 ...

  3. mongodb中oplogsize大小设置

    1 oplogsize大小配置: 2 mongodb副本集构建的高可用方案,最少需要三个节点,一个主节点master,一个从节点slave,一个选举仲裁节点arbiter.当主节点奔溃的时候,仲裁节点 ...

  4. cygwin -- 在windows平台上运行的unix模拟环境

    cygwin是一个在windows平台上运行的unix模拟环境,是cygnus solutions公司开发的自由软件(该公司开发了很多好东西,著名的还有eCos,不过现已被Redhat收购).它对于学 ...

  5. 企业CICD规模化落地浅析

    本次分享的题目是<企业CICD规模化落地>,因此我们不会侧重讲解CICD是什么以及怎样做CICD,而是你已经知道怎样"玩转"CICD了,要如何在一个比较大的企业中规模化 ...

  6. 人口信息普查系统-JavaWeb-二

    上次发表了人口普查系统的题目要求,今天和大家分享一下我的技术方案. 技术上用到的是html+jsp+JavaBean+servlet+JavaScript 其实现在的前端页面主流还是html,它可以实 ...

  7. Webpack之 webpack-dev-server 中的 contentBase配置及作用

    contentBase:主要是指定静态资源的根目录的.  

  8. 多源最短路-Floyd

    题目描述 时间限制:5.0s 内存限制:256.0MB 问题描述 给定\(n\)个结点两两之间的单向边的长度,求两两之间的最短路径. 输入格式 输入第一行包含一个整数\(n\),表示点数. 接下来\( ...

  9. v76.01 鸿蒙内核源码分析(共享内存) | 进程间最快通讯方式 | 百篇博客分析OpenHarmony源码

    百篇博客分析|本篇为:(共享内存篇) | 进程间最快通讯方式 进程通讯相关篇为: v26.08 鸿蒙内核源码分析(自旋锁) | 当立贞节牌坊的好同志 v27.05 鸿蒙内核源码分析(互斥锁) | 同样 ...

  10. golang 获取当月最后一天日期

    now := time.Now() year, month, day := now.Date() //fmt.Println(year, month, day) //2021 September 1 ...