How to insert an index for each row in existing table - sql

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

Related

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')

Add row to table while incrementing primary key

Say I have a table that looks like:
ID Name Age Co
1 Adls 15 US
2 sldkl 14 FR
3 sldke 16 UK
4 sldee 17 IN
I want to add values to the table and have the ID incremented. ID is the primary key, and I set is Identity under column properties to 'Yes' and identity increment to 1.
So basically, I am doing:
Insert Into TableName(Name, Age, Co)
Values(slkdje, 19, CH)
(sldjklse, 20, AU)
(slfjke, 12, PK)
But, I am getting errors that the primary key is null, and therefore this operation in invalid. How would I add the values, but get the primary key values to increment?
here is a great example for what you want here
here is also a sql query that is copy and paste that will show my example.
create table #temp(
ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
)
insert into #temp(LastName) values('billy'),('bob')
select * from #temp
drop table #temp;
hope this helps dude.

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

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

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.