GENERATED { ALWAYS | 的限制是多少? BY DEFAULT } 作为 PostgreSQL 中的身份?

What is the limit of GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY in PostgreSQL?

PostgreSQL中有smallserialserialbigserial数值数据类型,分别对32767、2147483647和9223372036854775807有明显的限制。

但是GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY呢,有什么限制吗?或者它们可能是根据提供的数据类型计算的 (SMALLINT, INT, BIGINT)?

是的,它取决于列的数据类型并且可以使用 COLUMNS 元数据进行验证:

CREATE TABLE t1(id SMALLINT GENERATED ALWAYS AS IDENTITY);
CREATE TABLE t2(id INT GENERATED ALWAYS AS IDENTITY);
CREATE TABLE t3(id BIGINT GENERATED ALWAYS AS IDENTITY);

SELECT table_name, column_name, data_type,
       is_identity, identity_minimum, identity_maximum, *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME IN('t1','t2','t3');

db<>fiddle demo

输出:

There are smallserial, serial and bigserial numeric data types in PostgreSQL, ...

这些并不是真正的数据类型The manual:

The data types smallserial, serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns

实际使用的数据类型分别是smallintintbigint

参见:

  • How to convert primary key from integer to serial?
  • Safely rename tables using serial primary key columns

所有 serial 类型都从拥有的 SEQUENCE 中抽取号码,该号码基于 bigintThe manual:

Sequences are based on bigint arithmetic, so the range cannot exceed the range of an eight-byte integer (-9223372036854775808 to 9223372036854775807).

IDENTITY 列做同样的事情,只有 SEQUENCE 排他地 绑定到拥有的列,这避免了序列“类型”表现出的一些奇怪之处.

参见:

  • Auto increment table column