[英]Re-use the deleted sequences of primary keys (BIGSERIAL) - No UUID to save storage
I am using BIGSERIAL
as a Primary key and I want to make use of the deleted row's ids.我使用BIGSERIAL
作为主键,我想使用已删除行的 ID。
Example of the table that I want re-use the deleted ids from the deleted rows:我想重新使用已删除行中已删除 ID 的表示例:
DELETE FROM my_table WHERE id=3;
INSERT INTO my_table(column_x) VALUES(xxxxx)
my_table我的表
| id|column_x| | id|column_x| | id|column_x|
|---|--------| |---|--------| |---|--------|
| 1 | xxxxxx | | 1 | xxxxxx | | 1 | xxxxxx |
| 2 | xxxxxx | | 2 | xxxxxx | | 2 | xxxxxx |
| 3 | xxxxxx | >>> | 4 | xxxxxx | >>> | 4 | xxxxxx |
| 4 | xxxxxx | | 5 | xxxxxx | | 5 | xxxxxx |
| 5 | xxxxxx | | 3 | xxxxxx |
The third table from the right inserted a new row with the id=3 in which was deleted in the table in the middle, and by doing so.右数第三张表在中间的表中插入了一个id=3的新行,并通过这样做。 I want to make use of those skipped sequences.我想利用那些跳过的序列。
I made a few attempts by using ALTER SEQUENCE
source我使用ALTER SEQUENCE
source做了几次尝试
My current solution:我目前的解决方案:
INSERT INTO my_table(id, column_x)
VALUES(deleted_index, xxxx);
Expected solution:预期的解决方案:
INSERT INTO my_table(column)
VALUES(xxxx);
In other words, altering the sequence for the index my_table.id so it re-uses the deleted sequences and move on to nextval
换句话说,更改索引 my_table.id 的序列,以便它重新使用已删除的序列并转到nextval
dot not understand the purpose of this, but there is the code, surprisingly it works fine:不明白这样做的目的,但是有代码,令人惊讶的是它工作正常:
WITH selectvalues AS (
SELECT * FROM my_table
),
deletevalue AS (
DELETE FROM my_table del
USING selectvalues sel
WHERE del.id = sel.id
RETURNING del.*
),
insertval AS(
INSERT INTO my_table
SELECT * FROM deletevalue
RETURNING * )
SELECT * FROM insertval
Do you really think you will exhaust all 9223372036854775807 positive bigint
numbers?你真的认为你会用尽所有 9223372036854775807 个正bigint
数吗? Any attempt to "fill the gaps" will complicate matters and be bad for performance.任何“填补空白”的尝试都会使事情复杂化并且不利于绩效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.