I have table with identity, seed 1 auto increment 1. In that table I have rows with primary key 1,2,4,5 (3 is missing, I deleted it), now I want to insert values in that table but with ID of 3, but I can't find it how in db2...
Any help? Thanks in advance.
The answer depends on how the column is defined. If it is GENERATED BY DEFAULT AS IDENTITY, then you can simply provide an explicit value for it in the INSERT statement. If the column is GENERATED ALWAYS, you could temporarily restart the identity sequence from the value you need, perform the insert, then restart it again with the maximum value + 1. The latter will only work if there is no concurrent insert activity on the table, of course.
Having said all that, I think that if you really require a gapless identity sequence you should not be using autogeneration in the first place.
Related
To have an integer auto-numbering primary key on a table, you can use SERIAL
But I noticed the table information_schema.columns has a number of identity_ fields, and indeed, you could create a column with a GENERATED specifier...
What's the difference? Were they introduced with different PostgreSQL versions? Is one preferred over the other?
serial is the "old" implementation of auto-generated unique values that has been part of Postgres for ages. However that is not part of the SQL standard.
To be more compliant with the SQL standard, Postgres 10 introduced the syntax using generated as identity.
The underlying implementation is still based on a sequence, the definition now complies with the SQL standard. One thing that this new syntax allows is to prevent an accidental override of the value.
Consider the following tables:
create table t1 (id serial primary key);
create table t2 (id integer primary key generated always as identity);
Now when you run:
insert into t1 (id) values (1);
The underlying sequence and the values in the table are not in sync any more. If you run another
insert into t1 default_values;
You will get an error because the sequence was not advanced by the first insert, and now tries to insert the value 1 again.
With the second table however,
insert into t2 (id) values (1);
Results in:
ERROR: cannot insert into column "id"
Detail: Column "id" is an identity column defined as GENERATED ALWAYS.
So you can't accidentally "forget" the sequence usage. You can still force this, using the override system value option:
insert into t2 (id) overriding system value values (1);
which still leaves you with a sequence that is out-of-sync with the values in the table, but at least you were made aware of that.
identity columns also have another advantage: they also minimize the grants you need to give to a role in order to allow inserts.
While a table using a serial column requires the INSERT privilege on the table and the USAGE privilege on the underlying sequence this is not needed for tables using an identity columns. Granting the INSERT privilege is enough.
It is recommended to use the new identity syntax rather than serial
I have application using JPA and Postgresql. I have exisiting database, and I need to add a field to exsiting table, which should be auto incremented. I need to provide that values for new record will be always greater than the previous record. Also I need to add values for the record that exists...
I've thought that id field will suite my requirements, but it doesn't... I have a primary key which is generated by sequence in PostgreSQL, but values aren't always greater. Application is used by many concurrent clients.
The following SQL will create a sequence, alter the table and use the sequence to generate and set the default value in the new column:
CREATE SEQUENCE myid_seq;
ALTER TABLE mytable ADD COLUMN myid bigint NOT NULL DEFAULT nextval('myid_seq');
So the number will be set by the database when a new row is inserted. (i.e. no problem if you have many concurrent insert).
Existing rows will be updated with a unique value for myid.
You can add a unicity constraint if you need it.
I am trying to auto increment my primary key, by 0.1 each time. Starting from 0.1. Is this possible?
CREATE TABLE NewTable
(
ID BigInt IDENTITY NOT NULL,
CONSTRAINT PK_ID PRIMARY KEY (ID),
)
No. BigInt is a 8 byte integer value.
Note: Assuming as Microsoft SQL Server.
No, even if you changed the data type of the field, the identity increment 'must be a non-zero integral number containing 18 digits or less'
(Presuming this is sql server)
In SQL Server, the Identity column cannot contain decimal values in its seed or increment.
Why would you need to do this -- for presentation purposes? If so, don't. If needed, one option is to create a trigger. You could also consider using a Computed column instead -- make it 1/10 the value of the Id (your Identity field seeded and incremented at 1 -- Identity(1,1)).
Again, not sure why you'd need to do this though.
Some solution would be a view:
CREATE VIEW v_NewTable AS
SELECT ID/10
FROM NewTable
It's far from the ideal situation, but I need to fix a database by appending the number "1" to the PK Identiy column which has FK relations to four other tables. I'm basically making a four digit number a five digit number. I need to maintain the relations. I could store the number in a var, do a Set query and append the 1, and do that for each table...
Is there a better way of doing this?
You say you are using an identity data type for your primary key so before you update the numbers you will have to SET IDENTITY_INSERT ON (documentation here) and then turn it off again after the update.
As long as you have cascading updates set for your relations the other tables should be updated automatically.
EDIT: As it's not possible to change an identity value I guess you have to export the data, set the new identity values (+10000) and then import your data again.
Anyone have a better suggestion...
Consider adding another field to the PK instead of extending the length of the PK field. Your new field will have to cascade to the related tables, like a field length increase would, but you get to retain your original PK values.
My suggestion is:
Stop writing to the tables.
Copy the tables to new tables with the new PK.
Rename the old tables to backup names.
Rename the new tables to the original table name.
Count the rows in all the tables and double check your work.
Continue using the tables.
Changing a PK after the fact is not fun.
If the column in question has an identity property on it, it gets complicated. This is more-or-less how I'd do it:
Back up your database.
Put it in single user mode. You don't need anybody mucking around whilst you do the surgery.
Execute the ALTER TABLE statements necessary to
disable the primary key constraint on the table in question
disable all triggers on the table in question
disable all foreign key constraints referencing the table in question.
Clone your table, giving it a new name and a column-for-column identical definitions. Don't bother with any triggers, indices, foreign keys or other constraints. Omit the identity property from the table's definition.
Create a new 'map' table that will map your old id values to the new value:
create table dbo.pk_map
(
old_id int not null primary key clustered ,
new_id int not null unique nonclustered ,
)
Populate the map table:
insert dbo.pk_map
select old_id = old.id ,
new_id = f( old.id ) // f(x) is the desired transform
from dbo.tableInQuestion old
Populate your new table, giving the primary key column the new value:
insert dbo.tableInQuestion_NEW
select id = map.id ,
...
from dbo.tableInQuestion old
join dbo.pk_map map on map.old_id = old.id
Truncate the original table: TRUNCATE dbo.tableInQuestion. This should work—safely—since you've disabled all the triggers and foreign key constraints.
Execute SET IDENTITY_INSERT dbo.tableInQuestion ON.
Reload the original table:
insert dbo.tableInQuestion
select *
from dbo.tableInQuestion_NEW
Execute SET IDENTITY_INSERT dbo.tableInQuestion OFF
Execute drop table dbo.tableInQuestion_NEW. We're all done with it.
Execute DBCC CHECKIDENT( dbo.tableInQuestion , reseed ) to get the identity counter back in sync with the data in the table.
Now, use the map table to propagate the changed primary key column down the line. Depending on your E-R model, this can get complicated as foreign keys referencing the updated column may themselves be part of a composite primary key.
When you're all done, start re-enabling the constraints and triggers you disabled. Make sure you do this using the WITH CHECK option. Fix any problems thus uncovered.
Finally, drop the map table, and clear the single user flag and bring your system(s) back online.
Piece of cake! (or something.)
Consider this approach:
Reset the identity seed to the 10000 + the current seed.
Set identity insert on
Insert into the table from the values in the table and add 10000 to the identity column on the way.
EX:
Set identity insert on
Insert Table(identity, column1, eolumn2)
select identity + 10000, column1, column2
From Table
Where identity < origional max identity value
After the insert you know the identity is exactly 10000 more than the origional.
Update the foreign keys by addding 10000.
I've an identity column which has multiple deletes now it is not working because it reaches the max limit of the INT data type,
how can I insert records in the place of deleted ones without truncating all the data?
You cannot "recycle" unused IDENTITY values - if you've reached the end of the INT data range, you need to change your ID column to BIGINT.
ALTER TABLE dbo.YourTable
ALTER COLUMN YourIDColumn BIGINT
The IDENTITY property will be preserved - now you have a lot of additional ID values available for the next couple months/years to come!
Excuse the obvious...
Did you start at 1, increment of 1? If so, change the identity to -1, -1. It requires a table rebuild but it's easier than changing to bigint. And gives you another 2 billion IDs.
Then plan your bigint migration...
That seems like a lot of work; why not just change the primary key on the table (and any related tables) from an int to a bigint?
An int will give you a max value of 2,147,483,647.
A bigint will give you a max value of 9,223,372,036,854,775,807.