Postgres Integer类型的下限超出范围?

发布于 2025-02-13 23:52:01 字数 683 浏览 0 评论 0 原文

per postgres 整数类型是在 -2147483648 +2147483647
我认为这些边界是包容性的,但是如果我尝试:

select -2147483648 = -2147483648::int4

<代码>整数超出范围错误。

上界似乎正确地施放了:


# select 2147483647 = 2147483647::int4;
 ?column? 
----------
 t
(1 row)

如果我增加下限,则它的工作原理也很好:

# select -2147483647 = -2147483647::int4;
 ?column? 
----------
 t
(1 row)

将相同的结果应用于 smallint 。 我在这里缺少一些明显的东西,还是在Postgres数字类型中排除了下界?

Per Postgres documentation, an integer type is defined between -2147483648 and +2147483647.
I thought that these boundaries were inclusive, but if I try:

select -2147483648 = -2147483648::int4

an Integer out of range error is raised.

The upper bound seems to be casted properly:


# select 2147483647 = 2147483647::int4;
 ?column? 
----------
 t
(1 row)

And if I increase the lower bound by one it works fine as well:

# select -2147483647 = -2147483647::int4;
 ?column? 
----------
 t
(1 row)

The same result is applied to smallint.
Is there something obvious that I'm missing here, or are lower bounds excluded for Postgres numeric types?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

得不到的就毁灭 2025-02-20 23:52:01

tldr

这很棘手。对于 smallint bigint ,下界的同样的铸件似乎失败了:

SELECT -32768::int2; -- fails
SELECT -2147483648::int4; -- fails
SELECT -9223372036854775808::int8; -- fails

但外观在欺骗。这是真正发生的事情:

SELECT - (2147483648::int4);

- 被视为“ Unary sionus” 运算符,仅在 之后才踢 :: “ postgresql style typecast” )。而且由于 Integer int4 )的范围是
-2147483648 to +2147483647 正如您准确引用的那样,该表达式在:

SELECT 2147483648::int4;

db&lt;&gt; fiddle

&

SELECT '-2147483648'::int4;
SELECT int '-2147483648';

am高效,因为那只是一个演员,不是演员 +否定操作。

您甚至可以:

SELECT (-2147483648)::int4;

只是为了推翻操作员的优先级。但是最后一个看起来很尴尬。而且效率略低。 :)

相关:

TLDR: operator precedence.

This is tricky at first sight. The same cast of the lower bound seemingly fails for smallint and bigint, too:

SELECT -32768::int2; -- fails
SELECT -2147483648::int4; -- fails
SELECT -9223372036854775808::int8; -- fails

But looks are deceiving. This is what really happens:

SELECT - (2147483648::int4);

- is taken to be "unary minus" operator, which only kicks in after :: (the "PostgreSQL-style typecast"). And since the range of integer (int4) is
-2147483648 to +2147483647 as you quoted accurately, the expression fails at:

SELECT 2147483648::int4;

db<>fiddle here

Use one of these instead:

SELECT '-2147483648'::int4;
SELECT int '-2147483648';

Also ever so slightly more efficient, since that's just a cast, not a cast + negation operation.

You could even:

SELECT (-2147483648)::int4;

Just to overrule operator precedence. But the last one looks awkward. And it's slightly less efficient. :)

Related:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文