Filling incremental unqiue values for a newly created PK - sql

I currently have a table with many rows, but no PK at all. I now require to have a unique, non-null, > 0 PK for every row.
I'm created the column for PK, but how I can I quickly fill in the column with an incremental value starting from 1?
Any method, a single SQL line, or a SQL line to be executed as many times as are rows are good enough for me.

Something like
update sometable set newkeyfield = Row_Number() Over();
should do not a DB2 bloke, but should be close.

Try using a DB2 Sequence object. They are designed for creating unique sequences of numbers. Pick your data type.
CREATE SEQUENCE mySeq as int;
You retrieve and increment the sequence in one step, using a sequence reference
NEXT VALUE FOR mySeq
You expression can use this in an INSERT, UPDATE, or MERGE, or most places you can use an expression.

Related

Adding a computed column that uses MAX

I need to create a sequential number column for record number proposes
I am OK with losing sequence if I delete a row from the middle of the table
For example
1
2
3
If I delete 2, I am ok with new column been 4.
I tried to alter my table to
alter table [dbo].[mytable]
add [record_seq] as (MAX(record_seq) + 1)
but I am getting An aggregate may not appear in a computed column expression or check constraint.
Which is a bit confusing? do I need to specify an initial value? is there a better way?
If you're looking to allocate a sequence number even in cases where the table doesn't get a record inserted, I would handle it in the process responsible for performing those inserts. Create another table, in this table keep track of the max identity value of that sequence. Each time you want to perform an insert, reserve the sequence number you want by updating that table first. If you rely on selecting the max existing value, you could be at risk of multiple sessions getting the same "new" sequence number before inserting. Even if the insert fails, you will have incremented that control table so nothing else uses that value that has been reserved.
Its not supported in MsSql. You can use identity column:
ALTER TABLE [dbo].[mytable]
ADD [record_seq] INT IDENTITY
Or use trigger to update your seq column after insert and/or delete

In SQL, how to populate number in sequence in column without alter the table structure?

populating number in a sequence for a column without altering table structure--need a query
if you don't want to change or alter the database table structure, you have limited solutions actually.
First option might be using a sequence object
create sequence mySequence increment by 1;
After you have a sequence object, you can read from this sequence whenever you need this field value
select mySequence.nextval from dummy;
Unfortunately, each read will increment the current value of the sequence.
This means if you read but did not insert the value into the table, next time you insert a new row there will be a gap in your table column.
Or if you insert two rows from two different executions, one might read the sequence first but insert value later than the other thread; then the sequence will be like 11,12,14,13,15
Second option is creating a database table trigger AFTER INSERT statement.
Then you can the max value from table column (or can store in a separate table) or from sequence, and update the column field with this sequence data

Unique sequence for a column in oracle table

I am trying to load a table where i have a PK column called E_id. I want to generate a unique ID for this column every time a row is loaded into this table at informatica level. But i want this e_id column to generate a unique value at table level. Can i achieve this by writing a query to this column at table create script itself?
Currently i tried this method of defaulting the value with this
e_id NUMBER DEFAULT TO_NUMBER(TO_CHAR(SYSTIMESTAMP, 'YYYYMMDDHH24MISSFF9')) NOT NULL
Although at times i am getting the same value for two records.
Can someone help how to go about this?
TIA.
one of the most common way to do this is using sequences
1 create sequence
2 before insert row trigger that will populate value into the pk column
create sequence GSEQUENCE
minvalue 1000
maxvalue 99999999999999999
start with 93581
increment by 1
cache 20;
CREATE OR REPLACE TRIGGER BI_DOCUMENTS
BEFORE INSERT
on DOCUMENTS
for each row
declare numrows INTEGER;
begin
select gsequence.nextval
into :new.id_DOCUMENT
from dual;
end;
/
If you are using 12c the easiest way is to use an IDENTITY column. Oracle will automatically generate a unique value for the column whenever you insert a record.
In prior versions you can define a sequence and generate it via a trigger or reference it directly in the insert statement.
You mention Informatica. Its a long time since I used it but I seem to remember there being a simple way to generate a unique ID using Informatica too.
You can use Globally Unique ID (GUID) which is unique for all practice purpose. Lot of systems use GUID to generate unique id.
select sys_guid() from dual
Mote into here
While GUID gives truly random unique ids, you can always use Oracle sequence if you need sequential unique values.
Oracle doesn't have "auto increment" columns, but you can achive similar results by a trigger.
EDIT: You can refer this link too How to generate a GUID in Oracle?

non-identity column auto increment

I'm working on a project to consolidate data (from 2 different DBs). I have created a table that contains a few columns:
MAPPING_ID int
ContentID int
ContentValue varchar(200)
For Example, when I do my 1st set of inserts against the original data source everything is good.
Mapping_ID: 53
ContentID: 53
ContentValue: Original Data 1
Mapping_ID: 54
ContentID: 54
ContentValue: Original Data 2
But when I do my second set of inserts against the another source (the data I'm trying to merge) I would like the Mapping_ID column to continue to the next number (i.e. 55,56,57...)
I looked at the row_number function but that starts at 1. Is there a way to start it at 55?
I suppose I could make that Mapping_ID column an Identity field, but turn it off during the first insert and then seed it with the max value (54) and then turn it on during the second insert.
Is there another way to accomplish this?
In SQL Server 2012+, you may use SEQUENCE objects to populate non-identity columns with autoincrement values. Plus you may use same SEQUENCE for different tables to make numeration pass-through and obtain values from sequences in SELECT and UPDATE queries.
First, create SEQUENCE:
CREATE SEQUENCE SchemaName.SequenceName
START WITH 1
INCREMENT BY 1 ;
Then, create DEFAULT constraint with values from sequence on required column:
ALTER TABLE tableName ADD CONSTRAINT constraint_unique_name DEFAULT NEXT VALUE FOR SchemaName.SequenceName FOR Mapping_ID;
There's actually a brand new way to do this kind of thing as of SQL Server 2012: the sequence object. I'm sorry I can't script out a procedure for you as I'm working in the MySQL world at present, but it's super easy to implement. The basic idea is you're maintaining a separate database object with its own seed and increment amount, but there are some caveats to bear in mind regarding their difference from traditional identity values (e.g. you can overwrite them), so make sure you do some research.
Here are a couple of articles to get you started. If you have trouble, hit me back and I'll try to work through the code with you.
https://msdn.microsoft.com/en-us/library/ff878091.aspx
https://msdn.microsoft.com/en-us/library/ff878370.aspx
Good luck!
To get row_number() to start at 55, you could just add 54 (or whatever number) to your row_number() calculation:
(row_number() over (partition by Y order by X)) + 54

How to update unique values in SQL using a PostgreSQL sequence?

In SQL, how do update a table, setting a column to a different value for each row?
I want to update some rows in a PostgreSQL database, setting one column to a number from a sequence, where that column has a unique constraint. I hoped that I could just use:
update person set unique_number = (select nextval('number_sequence') );
but it seems that nextval is only called once, so the update uses the same number for every row, and I get a 'duplicate key violates unique constraint' error. What should I do instead?
Don't use a subselect, rather use the nextval function directly, like this:
update person set unique_number = nextval('number_sequence');
I consider pg's sequences a hack and signs that incremental integers aren't the best way to key rows. Although pgsql didn't get native support for UUIDs until 8.3
http://www.postgresql.org/docs/8.3/interactive/datatype-uuid.html
The benefits of UUID is that the combination are nearly infinite, unlike a random number which will hit a collision one day.