PostgreSQL sum typecasting as a bigint

解决PostgreSQL求和溢出问题
本文介绍如何在PostgreSQL中避免整数求和时出现的溢出错误。通过将列类型转换为bigint或者直接在求和函数中进行类型转换,可以有效解决此问题。此外,还解释了PostgreSQL在超出bigint范围时会自动使用numeric类型。

https://stackoverflow.com/questions/20203081/postgresql-sum-typecasting-as-a-bigint

Question: 

  I am doing the sum() of an integer column and I want to typecast the result to be a bigint - to avoid an error. However when I try to use sum(myvalue)::bigint it still gives me an out of range error.

  Is there anything that I can do to the query to get this to work? Or do I have to change the column type to a bigint?

 

------------------

Answer:

  Try sum(myvalue::bigint)

 

 

The result is obviously bigger than what bigint could hold:

 

-9223372036854775808 to +9223372036854775807

 

Postgres returns numeric in such a case. You shouldn't have to do anything, it should just work without explicit cast.

 

If it doesn't, you can cast the base type to bigint, thereby forcing the result to be numeric in any case.

 

SELECT sum(myvalue::int8) ...

 

转载于:https://www.cnblogs.com/oxspirt/p/7411751.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值