重置 postgres 中的自动增量计数器

发布于 2024-10-24 17:12:13 字数 316 浏览 2 评论 0原文

我想强制表的自动增量字段为某个值,我尝试这样做:

ALTER TABLE product AUTO_INCREMENT = 1453

并且

ALTER SEQUENCE product  RESTART WITH 1453;
ERROR:  relation "your_sequence_name" does not exist

我有一个表 product ,其中包含 Idname字段

I would like to force the auto increment field of a table to some value, I tried with this:

ALTER TABLE product AUTO_INCREMENT = 1453

AND

ALTER SEQUENCE product  RESTART WITH 1453;
ERROR:  relation "your_sequence_name" does not exist

I have a table product with Id and name field

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

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

发布评论

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

评论(18

蘑菇王子 2024-10-31 17:12:13

如果您创建了带有 id 列的表 product,则序列不会简单地称为 product,而是 product_id_seq > (即 ${table}_${column}_seq)。

这是您需要的 ALTER SEQUENCE 命令:

ALTER SEQUENCE product_id_seq RESTART WITH 1453

您可以使用 psql 中的 \ds 命令查看数据库中的序列。如果您执行 \d Product 并查看列的默认约束,则 nextval(...) 调用也将指定序列名称。

If you created the table product with an id column, then the sequence is not simply called product, but rather product_id_seq (that is, ${table}_${column}_seq).

This is the ALTER SEQUENCE command you need:

ALTER SEQUENCE product_id_seq RESTART WITH 1453

You can see the sequences in your database using the \ds command in psql. If you do \d product and look at the default constraint for your column, the nextval(...) call will specify the sequence name too.

椵侞 2024-10-31 17:12:13

以下命令会自动为您执行此操作:这还将删除表中的所有数据。所以要小心。

TRUNCATE TABLE someTable RESTART IDENTITY;

The following command does this automatically for you: This will also delete all the data in the table. So be careful.

TRUNCATE TABLE someTable RESTART IDENTITY;
过去的过去 2024-10-31 17:12:13

这是您正在查找的命令,假设您的产品表序列是product_id_seq:

ALTER SEQUENCE product_id_seq RESTART WITH 1453;

Here is the command that you are looking for, assuming your sequence for the product table is product_id_seq:

ALTER SEQUENCE product_id_seq RESTART WITH 1453;
早茶月光 2024-10-31 17:12:13

设置序列计数器:

setval('product_id_seq', 1453);

如果您不知道序列名称,请使用 pg_get_serial_sequence 函数:

select pg_get_serial_sequence('product', 'id');
 pg_get_serial_sequence 
------------------------
 public.product_id_seq

参数是表名和列名。

或者只需在 psql 提示符下发出 \d Product 即可:

=> \d product
                         Table "public.product"
 Column |  Type   |                      Modifiers                       
--------+---------+------------------------------------------------------
 id     | integer | not null default nextval('product_id_seq'::regclass)
 name   | text    | 

To set the sequence counter:

setval('product_id_seq', 1453);

If you don't know the sequence name use the pg_get_serial_sequence function:

select pg_get_serial_sequence('product', 'id');
 pg_get_serial_sequence 
------------------------
 public.product_id_seq

The parameters are the table name and the column name.

Or just issue a \d product at the psql prompt:

=> \d product
                         Table "public.product"
 Column |  Type   |                      Modifiers                       
--------+---------+------------------------------------------------------
 id     | integer | not null default nextval('product_id_seq'::regclass)
 name   | text    | 
仲春光 2024-10-31 17:12:13
-- Change the starting value of the sequence

ALTER SEQUENCE project_id_seq RESTART 3000;

相同但动态:

SELECT SETVAL('project_id_seq', (SELECT MAX(id) FROM project));

SELECT 的使用很奇怪,但它有效。

来源:
https://kylewbanks.com/blog/Adding-or -Modifying-a-PostgreSQL-Sequence-Auto-Increment

编辑:按照评论中的建议删除了 +1

-- Change the starting value of the sequence

ALTER SEQUENCE project_id_seq RESTART 3000;

Same but dynamic :

SELECT SETVAL('project_id_seq', (SELECT MAX(id) FROM project));

The use of a SELECT is weird but it works.

Source:
https://kylewbanks.com/blog/Adding-or-Modifying-a-PostgreSQL-Sequence-Auto-Increment

Edit: removed +1 as suggested in the comments

鲜肉鲜肉永远不皱 2024-10-31 17:12:13

要将其设置为下一个最高值,您可以使用:

SELECT SETVAL(pg_get_serial_sequence('table_name', 'column_name'), (SELECT MAX(column_name) FROM table_name));

To set it to the next highest value you can use:

SELECT SETVAL(pg_get_serial_sequence('table_name', 'column_name'), (SELECT MAX(column_name) FROM table_name));
我的痛♀有谁懂 2024-10-31 17:12:13

如果您有一个包含 IDENTITY 列的表,并且想要为其重置下一个值,可以使用以下命令:

ALTER TABLE <table name> 
    ALTER COLUMN <column name> 
        RESTART WITH <new value to restart with>;

If you have a table with an IDENTITY column that you want to reset the next value for you can use the following command:

ALTER TABLE <table name> 
    ALTER COLUMN <column name> 
        RESTART WITH <new value to restart with>;
暖阳 2024-10-31 17:12:13

为了访问者的方便而从评论转换

从该消息中并不清楚正确的语法是什么。这是:

ALTER SEQUENCE product_id_seq RESTART WITH 1453;

Converted from comment for the sake of visitor's convenience

It's not clear from this message what the correct syntax is. It is:

ALTER SEQUENCE product_id_seq RESTART WITH 1453;
影子是时光的心 2024-10-31 17:12:13

2021 年,Postgres 11.12

ALTER SEQUENCE 对我不起作用,它以某种方式将其重置为 null
对我有用的是:

SELECT setval('<table>_<column>_seq', 5);

Year 2021, Postgres 11.12

ALTER SEQUENCE did not worked for me, it resets it to null somehow.
What worked for me is:

SELECT setval('<table>_<column>_seq', 5);
蓝海 2024-10-31 17:12:13

如果您想从 GUI 重置自动增量,请按照以下步骤操作。

  1. 转到您的数据库
  2. 点击
  3. 表格列表页面中的公共,您可以看到TABS,例如“表格”、“视图”、“序列”那。
  4. 单击序列
  5. 当您单击“序列”时,您可以看到所有序列列表,单击任何您想要重置的序列,
  6. 然后您可以看到多个选择,例如“更改” '、'设置值'、'重新启动'、'重置'等...
  7. 然后单击重置,然后添加一个新行。

if you want to Reset auto increment from GUI, then follow this steps.

  1. Go to your Database
  2. Click on Public
  3. in the tables Listing page you can see TABS like 'Tables', 'Views', 'Sequences' like that.
  4. Click on Sequences
  5. when you click on 'Sequences' you can see all the Sequences Listing, click on any that you want to Reset
  6. After that you can see multiple choice like 'Alter', 'Set Value', 'Restart', 'Reset' etc...
  7. then click on Reset, then add one New Row.
娇纵 2024-10-31 17:12:13

要重置自动增量,您必须使用以下查询获取序列名称。

语法:

SELECT pg_get_serial_sequence(‘tablename’, ‘ columnname‘);

示例:

SELECT pg_get_serial_sequence('demo', 'autoid');

查询将返回 autoid 的序列名称为 "Demo_autoid_seq"
然后使用以下查询重置 autoid

语法:

ALTER SEQUENCE sequenceName RESTART WITH value;

示例:

ALTER SEQUENCE "Demo_autoid_seq" RESTART WITH 1453;

To reset the auto increment you have to get your sequence name by using following query.

Syntax:

SELECT pg_get_serial_sequence(‘tablename’, ‘ columnname‘);

Example:

SELECT pg_get_serial_sequence('demo', 'autoid');

The query will return the sequence name of autoid as "Demo_autoid_seq"
Then use the following query to reset the autoid

Syntax:

ALTER SEQUENCE sequenceName RESTART WITH value;

Example:

ALTER SEQUENCE "Demo_autoid_seq" RESTART WITH 1453;
荭秂 2024-10-31 17:12:13

要获取序列ID,请使用

SELECT pg_get_serial_sequence('tableName', 'ColumnName');

这将为您提供序列ID,如tableName_ColumnName_seq

要获取最后一个种子号,请使用

select currval(pg_get_serial_sequence('tableName', 'ColumnName'));

或者如果您知道序列ID已经直接使用它。

select currval(tableName_ColumnName_seq);

它将为您提供最后的种子号码

重置种子号码使用

ALTER SEQUENCE tableName_ColumnName_seq RESTART WITH 45

To get sequence id use

SELECT pg_get_serial_sequence('tableName', 'ColumnName');

This will gives you sequesce id as tableName_ColumnName_seq

To Get Last seed number use

select currval(pg_get_serial_sequence('tableName', 'ColumnName'));

or if you know sequence id already use it directly.

select currval(tableName_ColumnName_seq);

It will gives you last seed number

To Reset seed number use

ALTER SEQUENCE tableName_ColumnName_seq RESTART WITH 45
笑红尘 2024-10-31 17:12:13

使用此查询检查架构和表的序列键是什么,

SELECT pg_get_serial_sequence('"SchemaName"."TableName"', 'KeyColumnName'); // output: "SequenceKey"

使用此查询将增量值一一增加,

SELECT nextval('"SchemaName"."SequenceKey"'::regclass); // output 110

当插入到表时,下一个增量值将用作键(111 )。

使用此查询将特定值设置为增量值

SELECT setval('"SchemaName"."SequenceKey"', 120);

插入表时,下一个增量值将用作键(121)。

Use this query to check what is the Sequence Key with Schema and Table,

SELECT pg_get_serial_sequence('"SchemaName"."TableName"', 'KeyColumnName'); // output: "SequenceKey"

Use this query increase increment value one by one,

SELECT nextval('"SchemaName"."SequenceKey"'::regclass); // output 110

When inserting to table next incremented value will be used as the key (111).

Use this query to set specific value as the incremented value

SELECT setval('"SchemaName"."SequenceKey"', 120);

When inserting to table next incremented value will be used as the key (121).

原野 2024-10-31 17:12:13

我不确定以上所有答案,
如果我没有序列名称怎么办?
如果我不想截断我的表怎么办?

下面的查询帮助我在不影响现有数据的情况下做到了这一点。

ALTER TABLE <<table_name>>
    ALTER COLUMN <<primary_key_column_name>> RESTART SET START 4044;

I am not sure about all of the above answers,
What if I don't have a sequence name?
What if I don't want to truncate my table?

Below query helped me to do that without affecting the existing data.

ALTER TABLE <<table_name>>
    ALTER COLUMN <<primary_key_column_name>> RESTART SET START 4044;
季末如歌 2024-10-31 17:12:13
ALTER SEQUENCE public."Table_Id_seq"
RESTART 50;

这个查询对我有用。 PostgreSQL 版本 14

ALTER SEQUENCE public."Table_Id_seq"
RESTART 50;

this query worked for me. Postgresql version 14

呆头 2024-10-31 17:12:13

如果表像

bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 0)

0-9范围内插入一些记录后,会导致下一次insert发生冲突,因此要重置START:

ALTER TABLE ... ALTER COLUMN ... RESTART WITH 10;

If table is like

bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 0)

After inserting some records in the range of 0-9, will cause conflict for next insert, so to reset the START:

ALTER TABLE ... ALTER COLUMN ... RESTART WITH 10;
那请放手 2024-10-31 17:12:13

节点脚本:修复所有表标识:自动增量/nextval,基于上次插入的值。

const pg = require('pg');
const { Client } = pg;

const updateTables = async () => {

  const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'my-database',
    password: 'postgres',
    port: 5432,
  });

  await client.connect();

  console.log('Connected');

  const execQuery = async (queryStr, params = []) => {
    return new Promise((resolve, reject) => {
      client.query(queryStr, params, (error, results) => {
        if (error) {
          reject(error);
        } else {
          resolve(results);
        }
      })
    })
  }

  const tablesRes = await execQuery(`
    SELECT table_name
    FROM information_schema.tables
    WHERE table_type='BASE TABLE'
    AND table_schema='public';
  `)

  const tables = tablesRes.rows.map(row => row.table_name);

  tables.map(async tableName => {
    let lastId;
    try {
      const res = await execQuery(`SELECT id from "${tableName}" ORDER BY id DESC LIMIT 1`);
      lastId = res.rows[0].id;
    } catch (e) {}

    if (lastId) {
      const nextId = lastId + 1;
      const queryStr = `ALTER SEQUENCE ${tableName}_id_seq RESTART WITH ${nextId}`;
      await execQuery(queryStr);
      console.log(tableName, queryStr);
    }
  })

};

updateTables();

Node script: Fix all tables identity: auto-increment / nextval, based on last inserted it.

const pg = require('pg');
const { Client } = pg;

const updateTables = async () => {

  const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'my-database',
    password: 'postgres',
    port: 5432,
  });

  await client.connect();

  console.log('Connected');

  const execQuery = async (queryStr, params = []) => {
    return new Promise((resolve, reject) => {
      client.query(queryStr, params, (error, results) => {
        if (error) {
          reject(error);
        } else {
          resolve(results);
        }
      })
    })
  }

  const tablesRes = await execQuery(`
    SELECT table_name
    FROM information_schema.tables
    WHERE table_type='BASE TABLE'
    AND table_schema='public';
  `)

  const tables = tablesRes.rows.map(row => row.table_name);

  tables.map(async tableName => {
    let lastId;
    try {
      const res = await execQuery(`SELECT id from "${tableName}" ORDER BY id DESC LIMIT 1`);
      lastId = res.rows[0].id;
    } catch (e) {}

    if (lastId) {
      const nextId = lastId + 1;
      const queryStr = `ALTER SEQUENCE ${tableName}_id_seq RESTART WITH ${nextId}`;
      await execQuery(queryStr);
      console.log(tableName, queryStr);
    }
  })

};

updateTables();
明明#如月 2024-10-31 17:12:13

请注意,如果表名带有“_”,它将在序列名称中删除。

例如表名:user_tokens 列:id
序列名称:usertokens_id_seq

Note that if you have table name with '_', it is removed in sequence name.

For example, table name: user_tokens column: id
Sequence name: usertokens_id_seq

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