How to re-number T-SQL's system auto-increment Identity column? - sql

I have an auto-increment primary key in a SQL table lets say table look like this:
CREATE TABLE [Table] (--Identifier contains a space and uses a reserved keyword.
[ID] [int] IDENTITY(1,1) NOT NULL ,
[Name] [varchar](50) NULL,
CONSTRAINT [PK__Table] PRIMARY KEY CLUSTERED ([ID] ASC)
);
ID | Name|
1 John
2 Jack
3 Bill
4 Joe
Then I delete row 2 Jack:
ID | Name|
1 John
3 Bill
4 Joe
And what I want to achieve is to change id column so the table will look like this
ID | Name|
1 John
2 Bill
3 Joe
Is there a way to do it?

I will never do that but you can:
create a new autoincrement primary key named ID2
delete ID column
rename ID2 column as ID

Quick and dirty way to do it is, (my way) -->
select * into yournewtable from youroldtable order by yourIdentityColumn;
Then, open up yournewtable's design, make sure yourIdentityColumn is Identity(1,1).
Then, drop youroldtable.
Then, rename yournewtable to youroldtable! ta-da!

Set identity_insert Table off;
Update Table set ID = 3 where ID = 4;
...
Set identity_insert Table on;
Where Table name is Table

Related

how to add primary key column without truncating table in oracle

We have received a requirement where we need to add a new column to primary key where table is having records:
alter table customer add (bill_to number(9,0),
CONSTRAINT CUSTOMER_PK PRIMARY KEY (bill_to));
In this case after it adds the new column to the table by default null values will be stored if table is having records, technically we cannot make this column a primary key, either table shouldn't have the records or we have to truncate the table, but we cannot do it in production,
is there any other way to deal this? please suggest.
You can do it in 2 statements by first adding an IDENTITY column and second making it the PRIMARY KEY:
So, if you have the table:
CREATE TABLE customer ( value ) AS
SELECT 'A' FROM DUAL CONNECT BY LEVEL <= 3 UNION ALL
SELECT 'B' FROM DUAL CONNECT BY LEVEL <= 2;
Then you can:
ALTER TABLE customer ADD (
bill_to NUMBER(9,0)
GENERATED ALWAYS AS IDENTITY
);
ALTER TABLE customer ADD CONSTRAINT CUSTOMER_PK PRIMARY KEY ( bill_to );
And the table becomes:
VALUE | BILL_TO
:---- | ------:
A | 1
A | 2
A | 3
B | 4
B | 5
db<>fiddle here
You can not do it in a single statement.
You can achieve it using the three-step process as follows:
ALTER TABLE CUSTOMER ADD BILL_TO NUMBER(9, 0);
UPDATE CUSTOMER
SET BILL_TO = SEQ OR ANYOTHER LOGIC FOR UNIQUE VALUE FOR EACH ROW;
ALTER TABLE CUSTOMER ADD CONSTRAINT CUSTOMER_PK PRIMARY KEY ( BILL_TO );

How to update unique table row numbers before inserting new row at existing position

SQL table:
id | name
----+--------
1 | apple
2 | orange
3 | apricot
The id is primary key, unique, could be SERIES. The goal is to insert new row where id equals 2 and shift existing row numbers below, that is 2 and 3, to 3 and 4 position.
I have tried shift rows before inserting new row:
"UPDATE some_table SET id = id + 1 WHERE id >= id"
but an error occurred:
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "some_table_pkey"
Detail: Key (id)=(3) already exists.
Is there some effective way to do such an operation?
The table should look like this after update:
id | name
----+--------
1 | apple
2 | cherry
3 | orange
4 | apricot
While I think the attempt is futile, you can achieve that by marking the primary key constraint as deferrable:
CREATE TABLE some_table
(
id int,
name text
);
alter table some_table
add constraint pk_some_table
primary key (id)
deferrable initially immediate; --<< HERE
In that case the PK constraint is evaluated at per statement, not per row.
Online example: https://rextester.com/JSIV60771
update Names
set id=id+1
where id in
(select id from Names where id>=2 order by id desc);
Here first you can update the id's and then you can insert
insert into Names (id,name) values(2,'cheery')

How to insert an index for each row in existing table

I want to add a column named 'index' in my existing SQL table, my_table.
How to do it?
Original my_table:
name sex age
Ben M 23
May F 20
Sam M 22
Desired my_table:
name sex age id
Ben M 23 1
May F 20 2
Sam M 22 3
INDEX is a resrve word so it is not best practice to use that to create index but you use that in naming below way
create table mytable( id int,name varchar(100) );
ALTER TABLE [mytable] DROP COLUMN ID
ALTER TABLE [mytable] ADD ID INT IDENTITY(1,1)
It is possible to create like that:
ALTER TABLE dbo.my_table
ADD [index] INT
However, as said #Zaynul Abadin Tuhin, it is not best practice.
If you want to create an identification column then just use the following code to create unique column for each row:
ALTER TABLE dbo.my_table
ADD ID INT IDENTITY
CONSTRAINT PK_my_table PRIMARY KEY CLUSTERED
OUTPUT:
Name Age ID
Ben M 23 1
May F 20 2
Sam M 22 3

How to Insert Primary Value (PK) to Related Table (FK)

I'm having trouble from Inserting 1 Primary Value (Increment) of TABLE to another TABLE (Foreign Key)
Table 1 has the Primary key of Student Number; if i enter values for last and first name from TABLE 1 then the student number will automatically giving it's own value because of Increment, and else if i entered from TABLE 2, I want the value of Student Number from TABLE i will increment even the value of Last and First name if TABLE 1 is NULL
Table 1
(PK)Student_# | Last_Name | First_Name
...........1...........|........a..........|..........b.......
...........2...........|........c..........|..........b.......
Table 2
(FK)Student_# | Year_Level | Section
...........NULL................|..........2nd Year......|.....C1 .........
...........NULL................|..........3rd Year......|.....D1 .........
Needed
(FK)Student_# | Year_Level | Section
..............1...................|..........2nd Year......|.....C1 .........
..............2...................|..........3rd Year......|.....D1 .........
It sounds to me that you need a primary key with an identity seed on table2 and also a foreign key to the student table:
(PK/Identity) Table2ID | (FK)Student_# | Year_Level | Section
This way you can insert the student_# when you insert the record into table 2 and also be able to give each row in table2 a unique identifier
CREATE TABLE Table2
(
Table2ID INT IDENTITY(1,1) PRIMARY KEY
,Student_# INT NOT NULL FOREIGN KEY REFERENCES Table1(Student_#)
,Year_Level NVARCHAR(255) --Use whatever data type you need
,Section NVARCHAR(255) --Use whatever data type you need
)
I have assumed you are using sql server as you have not specified in your question. You may need to change this query for a different RDBMS.

Change foreign key using SQL

I have a table like this:
ID Name Email Referred_by
-------------------------------------------
1 John john#foo.com NULL
2 Sam sam#foo.com john#foo.com
3 Sally sally#foo.com sam#foo.com
..... more rows .....
And I would like to change it to:
ID Name Email Referred_by
-------------------------------------------
1 John john#foo.com NULL
2 Sam sam#foo.com 1
3 Sally sally#foo.com 2
..... more rows .....
Can I make this change using SQL?
This should do the trick:
UPDATE my_table a
set a.referred_by = (
SELECT b.id
FROM my_table b
WHERE b.email = a.referred_by
);
Many DBMS' will allow this by the use of DDL (definition) statements rather than DML (manipulation). Assuming that id is an integral type and referred_by is (currently) a textual column, you can do something like:
alter the table to add a new column ref2 (nullable) of the same type as id.
set up a foreign key constraint between that ref2 and id.
populate the ref2 column for all the rows.
drop the original constraint.
alter the table to remove column referred_by.
alter the table to rename column ref2 to referred_by.