Shift (update) unique column values in PostgreSQL

后端 未结 2 1974
星月不相逢
星月不相逢 2021-01-13 06:40

Using MS SQL Server, the following works fine:

CREATE TABLE #temptable(mykey int primary key)

INSERT INTO #temptable VALUES (1)
INSERT INTO #temptable VALUE         


        
相关标签:
2条回答
  • 2021-01-13 06:53

    This is indeed a bit confusing as all other constraints are evaluated on a statement level, only PK/unique constraint are evaluated on a per row level during DML operations.

    But you can work around that by declaring the primary key constraint as deferrable:

    create table tbl_test 
    (
      testkey   INTEGER,
      constraint pk_tbl_test primary key (testkey) deferrable initially immediate
    );
    
    insert into tbl_test values (1), (2);
    
    set constraints all deferred;
    
    update tbl_test
       set testkey = testkey +1;
    

    Deferred constraints do have some overhead, so by defining it as initially immediate this overhead is kept to a minimum. You can the defer the constraint evaluation when you need it by using set constraint.


    The real question however is: why would you need to do this on a primary key value? The PK values has no meaning whatsoever, so it seems rather unnecessary to increment all values (regardless of the DBMS being used)

    0 讨论(0)
  • 2021-01-13 06:55

    Solution without altering constraint as deferrable initially immediate

    UPDATE tbl_test t1 
    SET    testkey = t2.testkey + 1 
    FROM   (SELECT testkey 
        FROM   tbl_test 
        ORDER  BY testkey DESC) t2 
    WHERE  t1.testkey = t2.testkey 
    

    Online example: http://rextester.com/edit/GMJ48099

    0 讨论(0)
提交回复
热议问题