Postgres:整数超出范围。为什么会发生此错误?

Eug*_*kov 1 sql postgresql type-conversion

我有两个查询。我希望两者都插入相同的值:429496729600,但是其中一个由于错误而失败:

db=> update order_detail set amount = 400*1024*1024*1024 where id = 11;
ERROR:  integer out of range
db=> update order_detail set amount = 429496729600 where id = 11;
UPDATE 1
Run Code Online (Sandbox Code Playgroud)

为什么第一次查询会发生错误?

UPD
忘记指定amountis bigint

400*1024*1024*1024 == 429496729600  
Run Code Online (Sandbox Code Playgroud)

JGH*_*JGH 6

要强制乘法输出bigint而不是int,可以将1强制转换为bigint并乘以

select cast(1 as bigint)*400*1024*1024*1024;
   ?column?
--------------
 429496729600
Run Code Online (Sandbox Code Playgroud)


D-S*_*hih 5

int 最大值为 2 31 -1,第一个更新值大于它,因此会导致错误。

INT-2147483648 至 +2147483647

您可以尝试让列amount键入BIGINT

BIGINT-9223372036854775808 至 9223372036854775807

ALTER TABLE order_detail ALTER COLUMN amount TYPE BIGINT;
Run Code Online (Sandbox Code Playgroud)

数据类型


编辑

我们可以用pg_typeof它来检查一下。

查询#1

postgresql会因为值大于 int 范围而让429496729600be 。BIGINT

SELECT pg_typeof(429496729600 );

| pg_typeof |
| --------- |
| bigint    |
Run Code Online (Sandbox Code Playgroud)

查询#2

当您进行数字乘法时,将转换为int.

SELECT pg_typeof( 1*15*1  );

| pg_typeof |
| --------- |
| integer   |
Run Code Online (Sandbox Code Playgroud)

在 DB Fiddle 上查看

询问

您可以使用400*1024*1024*1024:: BIGINTletint转换为bigint.

SELECT 400*1024*1024*1024 :: BIGINT;

| ?column?     |
| ------------ |
| 429496729600 |
Run Code Online (Sandbox Code Playgroud)

在 DB Fiddle 上查看