English 中文(简体)
修复Postgres序列生成的数字中的孔/间隙
原标题:Fixing holes/gaps in numbers generated by Postgres sequence

I have a postgres database that uses sequences extensively to generate primary keys of tables. After a lot of usage of this database i.e. Adding/Update/Delete operation the columns that uses sequences for primary keys now have a lot holes/gaps in them and the sequence value itself is very high.

我的问题是:有什么方法可以弥补主键中的这些空白吗?哪一个应该降低该列中数字的最大值,然后重置序列?

注意:这些列中的许多列也被其他列引用为ForeignKeys。

问题回答

如果您觉得需要填补自动生成的Posgresql序列号中的空白,我觉得您需要在表中添加另一个字段,比如在代码或触发器中以编程方式递增的某种“数字”。

解决这个问题是可能的,但数据库(尤其是IO)的成本很高,而且保证会再次出现。我不会担心这个问题。如果您接近4B,请将主键和外键升级为BIGSERIALBIGINT。如果你接近2^64…嗯。。。我很想了解更多关于你的申请

Postgres允许你更新PKs,尽管很多人认为这是一种糟糕的做法。因此,您可以锁定表,并UPDATE。(您可以通过各种方式创建<code>oldkey、newkey</code>表,例如窗口函数。)所有FK关系都必须标记为级联。然后您可以重置id序列的当前值。

就我个人而言,我只会使用BIGSERIAL。如果你有所以很多更新和删除,即使这样你也可能会用完,也许有一些基于时间戳和id的复合PK会对你有所帮助。





相关问题
摘录数据

我如何将Excel板的数据输入我的Django应用? I m将PosgreSQL数据库作为数据库。

Postgres dump of only parts of tables for a dev snapshot

On production our database is a few hundred gigabytes in size. For development and testing, we need to create snapshots of this database that are functionally equivalent, but which are only 10 or 20 ...

How to join attributes in sql select statement?

I want to join few attributes in select statement as one for example select id, (name + + surname + + age) as info from users this doesn t work, how to do it? I m using postgreSQL.

What text encoding to use?

I need to setup my PostgreSQL DB s text encoding to handle non-American English characters that you d find showing up in languages such as German, Spanish, and French. What character encoding should ...

SQL LIKE condition to check for integer?

I am using a set of SQL LIKE conditions to go through the alphabet and list all items beginning with the appropriate letter, e.g. to get all books where the title starts with the letter "A": SELECT * ...

热门标签