I need help understanding Identity in sql - 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.

Related

How to generate a unique numeric ID in SQL Server (not using identity)?

I need a unique number id for my table. Usually I would use Identity in Sql Server, but there is a catch to my use case. I would like to know the id before the row is created (to be able to reference it in other records in memory, before committing everything to the database).
I don't know if it's possible to achieve with Identity, but I could not figure that out.
So my next best guess is that I need a table that will store one value and keep incrementing it and returning me a new value for the id. Access would have to be locked so that no two operations can get the same value.
I am thinking of using e.g. sp_getapplock #Resource = 'MyUniqueId' to prevent same number from being returned to a caller. Perhaps I can use ordinary locking in transactions for that as well.
Is there any better approach to the problem?
You can create a SEQUENCE object that produces incrementing values. A SEQUENCE can be used independently or as a default value for one or more tables.
You can create a sequence with CREATE SEQUENCE :
CREATE SEQUENCE Audit.EventCounter
AS int
START WITH 1
INCREMENT BY 1 ;
You can retrieve the next value atomically with NEXT VALUE FOR and use it in multiple statements eg :
DECLARE #NextID int ;
SET #NextID = NEXT VALUE FOR Audit.EventCounter;
Rolling back a transaction doesn't affect a SEQUENCE. From the docs:
Sequence numbers are generated outside the scope of the current transaction. They are consumed whether the transaction using the sequence number is committed or rolled back.
You can use NEXT VALUE FOR as a default in multiple tables. In the documentation example, three different types of event table use the same SEQUENCE allowing all events to get unique numbers:
CREATE TABLE Audit.ProcessEvents
(
EventID int PRIMARY KEY CLUSTERED
DEFAULT (NEXT VALUE FOR Audit.EventCounter),
EventTime datetime NOT NULL DEFAULT (getdate()),
EventCode nvarchar(5) NOT NULL,
Description nvarchar(300) NULL
) ;
GO
CREATE TABLE Audit.ErrorEvents
(
EventID int PRIMARY KEY CLUSTERED
DEFAULT (NEXT VALUE FOR Audit.EventCounter),
EventTime datetime NOT NULL DEFAULT (getdate()),
EquipmentID int NULL,
ErrorNumber int NOT NULL,
EventDesc nvarchar(256) NULL
) ;
GO
CREATE TABLE Audit.StartStopEvents
(
EventID int PRIMARY KEY CLUSTERED
DEFAULT (NEXT VALUE FOR Audit.EventCounter),
EventTime datetime NOT NULL DEFAULT (getdate()),
EquipmentID int NOT NULL,
StartOrStop bit NOT NULL
) ;
GO
One option here would be to use a UUID to represent each unique record. Should you want to generate the UUID within SQL Server, you could use the NEWID() function (see the documentation for more information). If this value would be generated from your application code, you could convert it to uniqueidentifier type within SQL Server using CONVERT.
For reference, a UUID is a 16 byte unique identifier. It is extremely unlikely that your application or SQL Server would ever generate the same UUID more than once. They look like this:
773c1570-1076-4e19-b728-6d7b0b20895a
If you want a behaviour that matches the one of an IDENTITY column, try:
CREATE SEQUENCE mydb.dbo.mysequence;
And then, repeatedly:
SELECT NEXT VALUE FOR mysequence;
And , if you want to play some more, see here:
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-sequence-transact-sql?view=sql-server-ver15
happy playing ...

How to auto increment alphanumeric column by 1

I have a column stating with value 't0005453'. How can I update this column till 't0005803'.
Should I put an auto increment in the column. I tried this with update query to just increment this by 1. But that is throwing null value.
If you like, you can add a computed column to mimic what you want:
create table t (
t_id int identity(1, 1) primary key,
. . . ,
my_id as ('t' as format(t_id, '0000000'))
);
Then the value is calculated on-the-fly based on the primary key column.

What happens when Identity seed reaches an existent value in a primary key?

I have an identity column that is also the primary key, of INT datatype. Due to the issue discussed here (cache loss), the identity has gaps and I chose to reseed to the previous value. In concrete terms, I have a situation that looks like this:
Table1
ID_PK Field1
---------------
28 'd'
29 'e'
30 'h'
1029 'f'
1030 'g'
I looked around and couldn't find a clear answer to what happens when I make an insertion and the seed reaches the existent value that would break the constraint. Suppose I were to insert values 'x' and 'y' in two separated queries to the table, I can think of the following possibilities:
The identity will be reseeded before the first insertion and I will have both values inserted correctly.
The first insertion will fail, then the column will be reseeded, and only then the second insertion would succeed.
Neither will work and I will have to explicitly call DBCC CHECKIDENT to reseed before inserting values in the table
So, which is it? Or none of the above? Would this behavior be different if I inserted a multi-row result query into Table1? Thanks in advance
For completeness anyway, here's a script you can use to test:
USE Sandbox;
GO
CREATE TABLE test(ID int IDENTITY(1,1) PRIMARY KEY CLUSTERED, string char(1));
GO
INSERT INTO test (string)
VALUES ('a'),('b'),('c'),('d');
GO
SELECT *
FROM test;
GO
DELETE FROM test
WHERE string IN ('b','c');
GO
SELECT *
FROM test;
GO
DBCC CHECKIDENT ('dbo.test', RESEED, 1);
GO
INSERT INTO test (string)
VALUES ('e'),('f');
GO
SELECT *
FROM test;
GO
INSERT INTO test (string)
VALUES ('g');
GO
SELECT *
FROM test;
GO
DROP TABLE test;
Running this script will give you the answer you need. If you wonder why I have used 1 as the RESEED value, this is explained in the documentation:
The following example forces the current identity value in the
AddressTypeID column in the AddressType table to a value of 10.
Because the table has existing rows, the next row inserted will use 11
as the value, that is, the new current increment value defined for the
column value plus 1.
In my script, this means that the next row to be inserted after the RESEED will have a value of 2 for its IDENTITY, not 1 (as rows already existing in the table (ID's 1 and 4)).
As several have said in the comments though, there's really no need to use RESEED on an IDENTITY column. If you need to maintain a sequence, you should (unsurprisingly) be using a SEQUENCE: CREATE SEQUENCE (Transact-SQL)
It depends:
Scenario 1
You get duplicates in the IDENTITY column, as no unique index or PK constraint.
create table I (
id int identity(1,1) not null,
i int null
)
Scenario 2
You get the following error as the inserted value conflicts with the Primary Key constraint:
Msg 2627, Level 14, State 1, Line 1 Violation of PRIMARY KEY
constraint 'PK__I__3213E83FE0B0E009'. Cannot insert duplicate key in
object 'dbo.I'. The duplicate key value is (11). The statement has
been terminated.
create table I (
id int identity(1,1) not null primary key,
i int null
)
This proves that IDENTITY on it's own does not guarantee uniqueness, only a UNIQUE CONSTRAINT does that.
To close, turns out it's (2).
First insertion fails, reseed is automatic to the highest value, and only next insertion suceeds. Multi-value insertions behave the same if any of the values would break the primary key constraint.

Two identity columns in SQL Server 2008

I am creating a table in SQL Server with three columns. I want the first two columns to increment counts one by one. I used the first column as identity column that automatically increments 1 when row is inserted. I tried to do the same with second column (but SQL Server does not allow two identity columns per table). I found another way i-e using Sequence but since I am using SQL Server 2008, it does not have this feature.
How can I achieve my task?
I am using the first identity column in reports and I reset it when some count is achieved; for example when it reaches 20, I reset it to 1 (Edited). The second incremental column will be used by me for sorting the data and i do not intend to reset it.
create table tblPersons
(
IDCol int primary key identity(1,1),
SortCol int primary key identity(1,1),
Name nvarchar(50)
)
PS : I cannot copy the values of IDCol to SortCol because when I reset the IDCol to 20 from my code, the SortCol will copy the same values (instead it should continue to 21,22,23 and so on)
If you plan on incrementing both columns always at the same time, then one workaround here might be to just use a single auto increment column, but use the remainder of that counter divided by 20 for the second value:
CREATE TABLE tblPersons (
IDCol int PRIMARY KEY IDENTITY(1,1),
Name nvarchar(50)
)
SELECT
IDCol,
IDCol % 20 AS SortCol -- this "resets" to zero upon reaching 20
FROM tblPersons;
As an alternative solution, you can use Computed Column
create table tblPersons
(
SortCol int primary key identity(1,1),
IDCol AS CASE WHEN (SortCol % 20) = 0 THEN 20 ELSE (SortCol % 20) END ,
Name nvarchar(50)
)

How to insert an increment value via 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