前言
一、数字类型
(1)整数类型
(2)精度类型
(3)浮点类型
(4)serial类型
1.1.数字类型列表
类型名称 | 存储长度 | 描述 | 范围 |
---|---|---|---|
smallint | 2字节 | 小范围整数类型 | -32768到+32768 |
integer | 4字节 | 整数类型 | -2 147 483 648到+2 147 483 647 |
bigint | 8字节 | 大范围整数类型 | -9 223 372 036 854 775 808到+9 223 372 036 854 775 807 |
decimal | 可变 | 用户指定精度 | 小数点前131072位;小数点后16383位 |
numeric | 可变 | 用户指定精度 | 小数点前131072位;小数点后16383位 |
real | 4字节 | 变长,不精确 | 6位十进制精度 |
double precision | 8字节 | 变长,不精确 | 15位十进制精度 |
smallserial | 2字节 | smallint自增序列 | 1到32767 |
serial | 4字节 | integer自增序列 | 1到2 147 483 647 |
bigserial | 8字节 | bigint自增序列 | 1到9 223 372 036 854 775 807 |
整数类型smallint、integer、bigint
smallint等价于int2:存储2字节整数
integer等价于int4:存储4字节整数
bigint等价于int8:存储8字节整数
定义一张使用integer类型的表
psql -U lhc -h 10.206.132.17 -p 5432 -d lhcdb
create table lhc.test_integer (id1 integer,id2 int4);
精度类型decimal和numeric
decimal和numeric是等效的,可以存储指定精度的多位数据。
numeric(precision,scale)
precision:指的是numeric数字里的全部位数,scale是指小数部分的数字位数。
precision必须为正整数,scale可以是0或整数
注意:由于numeric类型上的算术运算相比整数类型的性能低。
例如:
18.222的precision为5,而scale为3。
real和double precision是指浮点数据类型。
real支持4字节
double precision支持8字节
自增serial类型:smallserial、serial、bigserial
创建一张测试表:
create table lhc.test_serial(id serial,flag text);
\d lhc.test_serial
postgres@10.206.132.17:5432=#\d lhc.test_serial
Table "lhc.test_serial"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------------------------------------------
id | integer | | not null | nextval('lhc.test_serial_id_seq'::regclass)
flag | text | | |
insert into lhc.test_serial(flag) values ('a');
insert into lhc.test_serial(flag) values ('b');
insert into lhc.test_serial(flag) values ('c');
select * from lhc.test_serial;
postgres@10.206.132.17:5432=#select * from lhc.test_serial;
id | flag
----+------
1 | a
2 | b
3 | c
(3 rows)
1.2.数字类型操作符和数学函数
加减乘除
postgres@[local:/data/postgresql/pgdata]:5432=#select 1+2,2*3,4/2,8%3;
?column? | ?column? | ?column? | ?column?
----------+----------+----------+----------
3 | 6 | 2 | 2
(1 row)
按模取余
postgres@[local:/data/postgresql/pgdata]:5432=#select mod(8,3);
mod
-----
2
(1 row)
四舍五入函数
postgres@[local:/data/postgresql/pgdata]:5432=#select round(10.2),round(10.9);
round | round
-------+-------
10 | 11
(1 row)
返回大于或等于给出参数的最小整数
postgres@[local:/data/postgresql/pgdata]:5432=#select ceil(3.6),ceil(-3.6);
ceil | ceil
------+------
4 | -3
(1 row)
返回大于或等于给出参数的最大整数
postgres@[local:/data/postgresql/pgdata]:5432=#select floor(3.6),floor(-3.6);
floor | floor
-------+-------
3 | -4
(1 row)