DECIMAL[(M[, D])]代表一个精确值,它所存储的数值范围是-(1E+M -1)/(1E+D)到
(1E+M -1)/(1E+D)。
在DECIMAL[(M[, D])]数据类型中,M 是总位数,
支持的最大长度为65;
D 是小数
点后面的位数,支持的最大长度为30。
在不需要过高的数字精度的场景中,
DECIMAL 中的M 可以定义为M≤18,
这样可
以获得更好的查询性能。
DECIMAL 用来存储那些严格要求数字精度的数据,例如货币数据,在这种情况下
需要指定精度:
salary DECIMAL(5,2)
在DECIMAL(5,2)中,
5 表示总位数
(整数位和小数位的位数总和)
,
2 是小数位数。
可以存储在salary 列的最小值是-999.99,最大值是999.99。
DECIMAL 值的最大范围受限于给定的精度和小数范围。超过小数范围时,会按四
舍五入的原则截断为设定小数位数。
在定义DECIMAL 数据列时,
如果M 和D 同时省略,
则M 取值为10,
D 取值为0,
即DECIMAL(10,0),如果只指定M 值,省略D 值,那么插入一个非整数值的数字
时,将按照四舍五入的原则截取到整数位。
示例1:定义的列数据类型为DECIMAL(18,5)。
示例中用到的表及数据:
CREATE TABLE products(productnum DECIMAL(18,5));
GBase UP 产品手册 5 数据库管理指南
文档版本04(2021-04-21) 南大通用数据技术股份有限公司 347
INSERT INTO products(productnum) VALUES(19000.44365);
gbase> DESC products;
+------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+-------+
| productnum | decimal(18,5) | YES | | NULL | |
+------------+---------------+------+-----+---------+-------+
1 row in set
gbase> SELECT productnum FROM products;
+-------------+
| productnum |
+-------------+
| 19000.44365 |
+-------------+
1 row in set
示例2:定义的列数据类型为DECIMAL,M 和D 均省略,那么M 默认值为
10,D 默认值为0。
gbase> CREATE TABLE products(productnum DECIMAL);
Query OK, 0 rows affected
gbase> DESC products;
+------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+-------+
| productnum | decimal(10,0) | YES | | NULL | |
+------------+---------------+------+-----+---------+-------+
1 row in set
示例3:定义列数据类型为DECIMAL(M,D),插入的数据超出总位数M 时,
报告错误信息;超出精度D 时,则小数部分四舍五入。
gbase> CREATE TABLE products(productnum DECIMAL(8,3));
Query OK, 0 rows affected
gbase> INSERT INTO products(productnum) VALUES(191220.443);
ERROR 1264 (22003): Out of range value for column 'productnum' at row 1
gbase> INSERT INTO products(productnum) VALUES(19122.4436);
Query OK, 1 row affected, 1 warning
gbase> SELECT productnum FROM products;
+------------+
GBase UP 产品手册 5 数据库管理指南
文档版本04(2021-04-21) 南大通用数据技术股份有限公司 348
| productnum |
+------------+
| 19122.444 |
+------------+
1 row in set