How to insert an increment value via SQL - sql

I have a column in my database. How do i insert an incremented number via an insert so it fills it every row?

Use Identity column
Suppose you want Column Id to be incremented automatically a row is inderted define it as identity
ID INT IDENTITY (1,1)
First 1 is starting value second 1 is seeding it means increment by which integer
in this case the value will start at 1 and increment by 1 every time u insert a new row.
Please let me know if any further help needed

You may go to the designer of the table add a new Column and then go to the properties tab for the column and set
Identity Specification
IsIdentity :Yes
Identity Increment : 1
Identity Seed : 1
Identity Increment sets the number that will be added each time you insert a row. If it was 10 then you would have ids like 10, 20, 30.
Identity Seed is an offset you may need to add (which is the first number to appear) If it was 10 then your first Id would be 10.

Set identity seed for the column you want to increment the value
Alter Table Names Add Id_new Int Identity(1, 1) Go
Alter Table Names Drop Column ID Go
Exec sp_rename 'Names.Id_new', 'ID', 'Column'

When creating a new table, set the Data Type field to int and de-select Allow Nulls for that column.
Then, in column Properties, expand Identity Specification and change (Is Identity) to Yes.
By default the Identity Increment should be set to 1.

Make that column identity while creating the table which will auto increment that column for each row. You don't have to do explicit insert.

Create auto increment for that column for example
CREATE TABLE table_name
(
id int NOT NULL IDENTITY (1, 1),
name varchar(50) NULL
) ON [PRIMARY]
In the above example column id is auto increment. After each insert its value will increment by 1.
If you want to change that increment number later, please check
Reset AutoIncrement in SQL Server after Delete

Related

H2 maintain use-count column of a row automatically with computed column expression

How would I define a computedColumnExpression in H2 that increments a field of the row with each update of the row and starts at zero.
Well, by definition the computedColumnExpression is run every time an update occurs. But
how can the previous value of the usecount field of the updated row be referenced and
how is the initial insert handled?
I would start with a column definition like
"usecount" INT4 (1+(SELECT IFNULL("usecount",0) from "data" WHERE ID=XXXX))
but what should I use for the XXXX ?
I looked at triggers and thought to just update newRow in the fire method, but this does not seem to have any effect.
Given the first answer and my unsuccessful attempt I need to mention that the table already exist and I need the table definition to be an ALTER TABLE "data" ADD COLUMN. I would not have thought that it makes a difference.-(
You can use a declaration like this:
create table foo (pk int primary key,
usecount int as usecount + 1);
... where the rightmost usecount references the previous value. When you insert the row just insert a 0 value:
insert into foo values (42, 0);
... which will automatically increment the value to 1.
If you already have the table, you can add the column in two steps:
alter table foo add column usecount int default 0;
alter table foo alter column usecount int as usecount + 1;

SERIAL datatype in Postgres

The use of SERIAL datatype is to auto increment the value, so there is no need to specify the value during insertion of values. If we create a
table and insert value to that table, by default values starts from 1 for SERIAL column datatype. But Instead of 1 is there any way to start the value from 100 and increment by 10 as default value?
Serial is just syntactic sugaring on top of an int column that takes its value from a sequence. While you can't control a serial column's definitions directly, you could use an explicit sequence definition instead:
CREATE SEQUENCE tablename_colname_seq INCREMENT BY 10 START WITH 100; -- Here!
CREATE TABLE tablename (
colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
You can alter your existing sequence(not matter whether its serial or what) like below
ALTER SEQUENCE mytbl_id_seq INCREMENT 10 RESTART with 100
When creating a table
create table mytbl (id serial,val int)
a sequence will automatically creates i.e
CREATE SEQUENCE mytbl_id_seq
INCREMENT 1
START 1
so you can alter this with your desired values i.e
ALTER SEQUENCE mytbl_id_seq
INCREMENT 10
RESTART with 100
sqlfiddle-demo

I need help understanding Identity in sql

IDENTITY [ (seed , increment) ]
What does seed do?
I can't seem to find the answer on google.
The seed param is the value that is used for the very first row loaded into the table.Think of seed as the starting value, and increment as the amount to go up by.The default val for seed an increment is (1,1) resulting in identities of 1,2,3,... If you specified (5,1) you would get identities 5,6,7,...
Source: https://msdn.microsoft.com/en-us/library/ms186775.aspx
Identity field must be of int datatype.
for example
Id int Identity(1,1) NOT NULL
You can't insert into that field coz it will be automatically incremented by 1 as in above example. You can start and increment it according to yourself.
e.g. Identity(100,1), Identity(100,5)-increment by 5.
Think of it as a value that auto-increments.
It starts at the seed value, and increments by the increment.
So a table with a column, IDENTITY(100, 1),
First row would have the value 100
Second row would have the value 101
Third row would have the value 102
and so on
It's often used as a unique primary key, since each row will get a new value.

SQL Server Database unique number generation on any record insertion

I have like 11 columns in my database table and i am inserting data in 10 of them. i want to have a unique number like "1101 and so on" in the 11th column.
Any idea what should i do?? Thanks in advance.
SQL Server 2012 and above you can generate Sequence
Create SEQUENCE RandomSeq
start with 1001
increment by 1
Go
Insert into YourTable(Id,col1...)
Select NEXT VALUE FOR RandomSeq,col1....
or else you can use Identity
Identity(seed,increment)
You can start the seed from 1101 and increment the sequence by 1
Create table YourTable
(
id INT IDENTITY(1101,1),
Col varchar(10)
)
If you want to have that unique number in a different field then you can manipulate that field with primary key and insert that value.
If you want in primary key value, then open the table in design mode, go to 'Identity specification', set 'identity increment' and 'identity seed' as you want.
Alternatively you can use table script like,
CREATE TABLE Persons
(
ID int IDENTITY(12,1) PRIMARY KEY,
FName varchar(255) NOT NULL,
)
here the primary key will start seeding from 12 and seed value will be 1.
If you have your table definition already in place you can alter the column and add Computed column marked as persisted as:
ALTER TABLE tablename drop column column11;
ALTER TABLE tablename add column11 as '11'
+right('000000'+cast(ID as varchar(10)), 2) PERSISTED ;
--You can change the right operator value from 2 to any as per the requirements.
--Also replace ID with the identity column in your table.
create table inc
(
id int identity(1100,1),
somec char
)

Can a sql server table have two identity columns?

I need to have one column as the primary key and another to auto increment an order number field. Is this possible?
EDIT: I think I'll just use a composite number as the order number. Thanks anyways.
CREATE TABLE [dbo].[Foo](
[FooId] [int] IDENTITY(1,1) NOT NULL,
[BarId] [int] IDENTITY(1,1) NOT NULL
)
returns
Msg 2744, Level 16, State 2, Line 1
Multiple identity columns specified for table 'Foo'. Only one identity column per table is allowed.
So, no, you can't have two identity columns. You can of course make the primary key not auto increment (identity).
Edit: msdn:CREATE TABLE (Transact-SQL) and CREATE TABLE (SQL Server 2000):
Only one identity column can be created per table.
You can use Sequence for second column with default value IF you use SQL Server 2012
--Create the Test schema
CREATE SCHEMA Test ;
GO
-- Create a sequence
CREATE SEQUENCE Test.SORT_ID_seq
START WITH 1
INCREMENT BY 1 ;
GO
-- Create a table
CREATE TABLE Test.Foo
(PK_ID int IDENTITY (1,1) PRIMARY KEY,
SORT_ID int not null DEFAULT (NEXT VALUE FOR Test.SORT_ID_seq));
GO
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
SELECT * FROM Test.Foo
-- Cleanup
--DROP TABLE Test.Foo
--DROP SEQUENCE Test.SORT_ID_seq
--DROP SCHEMA Test
http://technet.microsoft.com/en-us/library/ff878058.aspx
Add one identity column and then add a computed column whose formula is the name of the identity column
Now both will increment at the same time
No it is not possible to have more than one identity column.
The Enterprise Manager does not even allow you to set > 1 column as identity. When a second column is made identity
Also note that ##identity returns the last identity value for the open connection which would be meaningless if more than one identity column was possible for a table.
create table #tblStudent
(
ID int primary key identity(1,1),
Number UNIQUEIDENTIFIER DEFAULT NEWID(),
Name nvarchar(50)
)
Two identity column is not possible but if you accept to use a unique identifier column then this code does the same job as well. And also you need an extra column - Name column- for inserting values.
Example usage:
insert into #tblStudent(Name) values('Ali')
select * from #tblStudent
Ps: NewID() function creates a unique value of type uniqueidentifier.
The primary key doesn't need to be an identity column.
You can't have two Identity columns.
You could get something close to what you want with a trigger...
in sql server it's not possible to have more than one column as identity.
I've just created a code that will allow you inserting two identities on the same table. let me share it with you in case it helps:
create trigger UpdateSecondTableIdentity
On TableName For INSERT
as
update TableName
set SecondIdentityColumn = 1000000+##IDENTITY
where ForstId = ##IDENTITY;
Thanks,
A workaround would be to create an INSERT Trigger that increments a counter.
So I have a table that has one identity col : applicationstatusid. its also the primary key.
I want to auto increment another col: applicationnumber
So this is the trigger I write.
create trigger [applicationstatus_insert] on [ApplicationStatus] after insert as
update [Applicationstatus]
set [Applicationstatus].applicationnumber =(applicationstatusid+ 4000000)
from [Applicationstatus]
inner join inserted on [applicationstatus].applicationstatusid = inserted.applicationstatusid