Postgresql JPA incrementing field - sql

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.

Related

What different between SERIAL and INT Generated Always As Identity in PostgreSQL? [duplicate]

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

does db2 have identity insert on?

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.

SQL Oracle Determining Primary Key Values

In Oracle SQL what is the best way to create primary key values for an entity? I have been adding 100 for each different entity and incrementing new entities by 1, but I can see how this is not good because if I have over 100 inserts into a table I would reuse a primary key number. I have many tables with primary keys, how do I determine a way to make sure all of the values are unique and there is no chance of them overlapping with other primary key values?
An example of what I have been doing is as follows:
create table example (
foo_id number(5);
Constraint example_foo_id_pk Primary key (foo_id);
Insert Into example
Values(2000);
Insert Into example
Values(2010);
create table example2 (
foobar_id number(5);
Constraint example2_foobar_id_pk Primary key (foobar_id);
Insert Into example2
Values (2100);
Insert Into example2
Values (2110);
In Oracle people commonly use sequences to generate numbers. In an insert trigger, the next value of the sequence is queried and put in the primary key field. So you normally don't pass a value for that field yourself.
Something like this:
CREATE SEQUENCE seq_example;
CREATE OR REPLACE TRIGGER tib_example
BEFORE INSERT ON example
FOR EACH ROW
BEGIN
SELECT seq_example .NEXTVAL
INTO :new.foo_id
FROM dual;
END;
/
Then you can just insert a record without passing any value for the id, only for the other fields.
If you want the keys to be unique over multiple tables, you can use the same sequence for each of them, but usually this is not necessary at all. A foo and a bar can have the same numeric id if they are different entities.
If you want every entity to have a unique ID throughout your database, you might consider using GUIDs.
Try using a sequence..
CREATE SEQUENCE Seq_Foo
MINVALUE 1
MAXVALUE 99999999
START WITH 1
INCREMENT BY 1;
To use the sequence in an insert, use Seq_Foo.NextVal.
Starting with Oracle database 12C, you can use identity columns. Use something like
foobar_id number(5) GENERATED BY DEFAULT ON NULL AS IDENTITY
For older versions sequences are the recommended way, although some ORM tools offer using a table which stores the counter. Inserting via sequence can be done either with triggers or by directly inserting sequence.nnextval into your table. The latter may be useful if you need the generated ID for other purposes (like inserting into child tables).

SQL Server Management Studio Express crashes when I try to run an ALTER TABLE query to add a PK with auto increment

I have an existing table where I use existing column (type INT) as PK and manually increment its value with each row inserted. I wanted to change it to IDENTITY with auto increment. I found a thread here (http://stackoverflow.com/questions/4862385/sql-server-add-auto-increment-primary-key-to-existing-table) that seems to achieve exactly what I want. But every time I run the ALTER statement, Mgmt Studio crashes.
I had also tried to achieve my above goal by changing the column properties manually (Identity specification/Is Identity:yes) as in this thread (http://stackoverflow.com/questions/3876785/sql-server-cant-insert-null-into-primary-key-field). But every time I close the table after changing properties, I get an error
'Pix' table
Unable to modify table.
Cannot insert the value NULL into column 'picID', table 'photo.dbo.Tmp_Pix'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Not sure what's going on.
You cannot change an existing column to become an IDENTITY column.
What you need to do is:
create a new column with INT IDENTITY
drop the primary key constraint
drop the old column
add the primary key constraint on the new column
The trouble might be - if you already have data in that table - that the new identity values don't necessarily match the old values in your manual ID column.
If you need to preserve those, then it gets even more involved:
create a new table with the proper structure, and make sure that the ID column is INT IDENTITY
turn on IDENTITY_INSERT for that table
insert all the rows from the old table into the new one (and in the process, insert the old ID values into the new ID IDENTITY column)
turn off IDENTITY_INSERT for that table
drop the old table
possibly rename the new table

Is there a smart way to append a number to an PK identity column in a Relational database w/o total catastrophe?

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.