Add a column ID with a unique value for each row - sql

I have an existing table with existing data and I want to add new column (named ID) with auto-increment and I want to add a unique value for each row.
Is there an other way than fetching all data and do an update for each row to set this value ?

If you need it in a SELECT:
SELECT *, ROW_NUMBER() OVER(ORDER BY ...A ORDER VALUE) as id
FROM yourTable
If you need it in your table:
ALTER TABLE yourTable ADD id int identity(1,1)
Here is a demo for the output of the ALTER TABLE:
CREATE TABLE #temp(name nvarchar(50))
INSERT INTO #temp(name) VALUES(N'Kai'),(N'Bernd'),(N'Flo'),(N'Pete')
SELECT * FROM #temp
-- This is what you need to do
ALTER TABLE #temp
ADD id int identity(1,1) -- This will add and fill the new column
SELECT * FROM #temp
DROP TABLE #temp

Related

How to insert a query into SQLite with an autoincrementing value for each row

Suppose I am inserting the following queryset into a new table in SQLite:
CREATE TABLE queryset_cache AS
SELECT ROW_NUMBER() over () AS rowid, * FROM mytable ORDER BY product;
Is it possible to either:
Set the rowid as auto-incrementing PK in sqlite from the insert, or;
Exclude the rowid and have SQLite auto-add in an autoincrementing primary key for each inserted record.
How would this be done?
Currently, without that when I do the insert, the rowid is not indexed.
rowid is already there. You can just do:
CREATE TABLE queryset_cache AS
SELECT t.*
FROM mytable t
ORDER BY product;
You will see it if you do:
SELECT rowid, t.*
FROM queryset_cache;
Here is a db<>fiddle
Auo increment should solve this. Documentation here:
https://www.sqlite.org/autoinc.html
Create source table:
create table sourceTable (oldID integer, data TEXT);
Add source data:
insert into sourceTable values(7, "x");
insert into sourceTable values(8, "y");
insert into sourceTable values(9, "z");
Create target table with auto-increment:
create table target(newID INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT);
Move data from source to target:
insert into target select null, data from sourceTable
If we have a table like:
create table employee (empID integer, name text , address text);
insert data into this table.
create a table in which you want to insert employee table data:
create table newEmployee (newempID integer PRIMARY KEY, name text , address text);
copy data to newEmployee table:
insert into newEmployee select * from employee
(select * from employee) to copy all the columns

dublicate entries and alocate to another user

I have a question: I would like to duplicate all the data in the table PlanData where userID='38' and change then the userID of the duplicated data into userID='39'. So UserID is one of many many cols in the table.
How would I be able to do that?
Thanks
Try below -
insert into PlanData(userid, col2,col3)
select 39 as userid,col2,col3 from PlanData where userID='38'
If you don't want to hardcode the column names then you could use a temporary table as a first step.
The example snippet below also uses a temp table for PlanData, for testing reasons.
-- Test table
IF OBJECT_ID('tempdb..#PlanData') IS NOT NULL DROP TABLE #PlanData;
CREATE TABLE #PlanData (ID INT PRIMARY KEY IDENTITY(1,1), userID INT, Col1 VARCHAR(30));
-- Sample Data
insert into #PlanData (userID, Col1) values
(36,'A'),(36,'B'),(36,'C'),
(38,'X'),(38,'Y'),(38,'Z');
-- Create a temporary table with data from the original user
IF OBJECT_ID('tempdb..#tmpPlanData') IS NOT NULL DROP TABLE #tmpPlanData;
SELECT * INTO #tmpPlanData FROM #PlanData WHERE 0=1
UNION ALL
SELECT * FROM #PlanData WHERE userID = 38;
-- Remove the identity column from the temp table
-- This assumes that the ID column is the first column in the table
ALTER TABLE #tmpPlanData DROP COLUMN ID;
-- Set the userId to the new userId in the temporary table
UPDATE #tmpPlanData SET userID = 39;
-- Insert all from the temporary table into the destination table
INSERT INTO #PlanData
SELECT * FROM #tmpPlanData;
-- Check the inserts
SELECT * FROM #PlanData
WHERE userID = 39;

reset number order in db2sql

how to reset the existing data order number ? i tried alter table tb_shk_user alter column autonum restart with 1, it works only for new data insert the number will start from 1 the number but will duplicated with existing 1.
autonum column attribute
AUTONUM INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1) primary key
or this :
--Save data of your table into temporary table
create table tmptable as
(
select * from tb_shk_user
)
with data;
--Remove all rows into your table
delete from tb_shk_user ;
--Insert into your table all rows with renumber for autonum, be carefull all columns mus be in select except autonum
insert into tb_shk_user overriding system value
select rownumber() over(order by autonum) as newautonum, username, mobilno
from tmptable;
-- Reposition of autoincrement on max + 1
-- Example if 47896 is the max + 1 of autonum after preceding insert
alter table tb_shk_user alter column autonum restart with 47896;
I suppose you want restart for have a good series of id, then you cando it
--Temprary table with key autonum and new num ordered
create table tmptable as (
select autonum, rownumber() over(order by autonum) as newautonum
from tb_shk_user
) with data;
--Update your table with new num
update tb_shk_user f1 overriding system value
set f1.autonum=
(
select f2.newautonum from tmptable f2
where f1.autonum=f2.autonum
)
where exists
(
select * from tmptable f2
where f1.autonum=f2.autonum
);
-- Reposition of autoincrement on max + 1
-- Example if 47896 is the max + 1 of autonum after preceding update
alter table tb_shk_user alter column autonum restart with 47896;

Insert into first row when the table has a primary key set

I spent all day creating then manually inserting into some tables I created today that look like this:
ID - Int (Primary Key set to Auto Increment)
Value - Varchar
But then I realized I had forgotten to insert a value of "--" into the first row of each table.
Is it possible to maybe add 1 to the ID no for each of the values currently in the table then insert the "--" value into the first row?
One of the ways to fix it is to update the record with the ID=1 to '--':
update yourTable set Value = '--' where id = 1
Then you will be required to re-insert the first record into the table:
INSERT INTO yourTable (Value)
VALUES('the value that was originally inserted as 1')
However, if the order of the already inserted records is important then you can insert the '--' value as the ID = 0. In this case you need to disable the IDENTITY column using the SET IDENTITY_INSERT:
SET IDENTITY_INSERT yourTable ON
INSERT INTO yourTable (ID, Value)
VALUES(0, '--')
SET IDENTITY_INSERT yourTable OFF
This way the order of inserted records will be preserved and the '--' will be inserted with the ID of 0
BTW, for mySQL you can insert into the IDENTITY column by default
Because Your ID column auto increment (IDENTITY), when you insert, you mustn't insert ID column. To insert your table, you just insert other columns.
Code insert like this:
INSERT INTO Your_Table (ColA, ColB, ...) -- `except identity colums`
VALUES (A, B, ...)
INSERT INTO Your_Table
VALUES (A, B, ...) -- except identity colums
INSERT INTO Your_Table
SELECT ColA, ColB, ... FROM Other_Table -- except identity colums
If Your_Table empty:
INSERT INTO Your_Table (Value)
VALUES ('--')
INSERT INTO Your_Table
SELECT '--'
If not:
UPDATE Your_Table
SET Value = '--'
WHERE ID = 1
------------------------ More Infor -------------------------------------------
If you want to first row have ID = 1. You can set ID column have IDENTITY(1,1). Like this:
CREATE TABLE Your_Table
(
ID INT IDENTITY(1, 1) PRIMARY KEY,
Value VARCHAR(50) NULL
)
Or, After you create Your_Table, you can set right-click Your_Table, select Design, select ID column. Look Column Properties below, expand Identity Specification, Double click (Is identity), then set value Identity Increment and Identity Seed

Loop through rows and add a number for a column for each of them automatically in SQL Server

I have got an over 500 rows table with a column called ID which is of datetype INT. Currently the values are all NULL.
What I want to achieve is to populate the ID column with an incremental number for each row, say 1, 2, 3, 4, ..., 500 etc.
Please give me a help with any idea how to achieve this by SQL script.
using ROW_NUMBER in a CTE is one way, but here's an alternative; Create a new id1 column as int identity(1,1), then copy over to id, then drop id1:
-- sample table
create table myTable(id int, value varchar(100));
-- populate 10 rows with just the value column
insert into myTable(value)
select top 10 'some data'
from sys.messages;
go
-- now populate id with sequential integers
alter table myTable add id1 int identity(1,1)
go
update myTable set id=id1;
go
alter table myTable drop column id1;
go
select * from myTable
Result:
id value
----------- -------------
1 some data
2 some data
3 some data
4 some data
5 some data
6 some data
7 some data
8 some data
9 some data
10 some data
While you could also drop and recreate ID as an identity, it would lose its ordinal position, hence the temporary id1 column.
#create one temporary table
CREATE TABLE Tmp
(
ID int NOT NULL
IDENTITY(1, 1),
field(s) datatype NULL
)
#suppose your old table name is tbl,now pull
#Id will be auto-increment here
#dont select Id here as it is Null
INSERT INTO Tmp (field(s) )
SELECT
field(s)
FROM tbl
#drop current table
DROP TABLE tbl
#rename temp table to current one
Exec sp_rename 'Tmp', 'tbl'
#drop your temp table
#write alter command to set identitry to Id of current table
good luck