sql identity issue - sql

I have column id which has identity column
CREATE TABLE EMP
(id int primary key identity(1,1),
name varchar(255));
Problem is that after 10 its gives value 111 then 112
why it is not giving 11

It depends how you are inserting the data into it. If it's simple INSERT INTO and nothing else around it, it's weird.
Maybe it's that issue with MSSQL 2012 server? There is a know bug about identity jump when server restarts.
More information http://www.codeproject.com/Tips/668042/SQL-Server-Auto-Identity-Column-Value-Jump-Is

Whatever the cause, you can reset your identity column using the DBCC CHECKIDENT command.
It accepts parameters to allow you to reset the value to whatever you desire. For example this:
DBCC CHECKIDENT ('[TableNameHere]', RESEED, 11)
Will reset the column to 11 - you can substitute whatever number is required as the final parameter.
Using TRUNCATE TABLE will also reset any identity columns - but it will also delete all your data, obviously. Using DELETE will remove data, but it does not change identity values.

Related

Identity specification

I have a problem with identity specification when I create a table in SQL Server 2016.
In column Id I set Identity Increment and Identity Seed equal 1.
Next I add new record to new table.
In column Id show up 2 value. Why? Why not 1 value?
Next drop the first record and add new. In column Id show up 3 value. Why? Why not 1 value.
Next I use command ' update nametable set id=1' and receive answer cannot update identity column Id. Why?
This is probably easier to explain with some code:
CREATE TABLE YourTable (ID int IDENTITY(1,1),
SomeCol varchar(5));
INSERT INTO dbo.YourTable (SomeCol)
VALUES('abc'); --Will get ID 1
INSERT INTO dbo.YourTable (SomeCol)
VALUES('def'),('ghi'); --Will get 2 and 3.
SELECT *
FROM dbo.YourTable;
DELETE FROM dbo.YourTable;
INSERT INTO dbo.YourTable (SomeCol)
VALUES('abc'); --Will get ID 4, because 1-3 have been used. Deleting doesn't let you reuse values.
SELECT *
FROM dbo.YourTable;
DELETE FROM dbo.YourTable;
DBCC CHECKIDENT ('dbo.YourTable', RESEED, 1);
INSERT INTO dbo.YourTable (SomeCol)
VALUES('abc'); --Will get ID 2, as you seeded back to 1; so the NEXT ID is used.
SELECT *
FROM dbo.YourTable;
TRUNCATE TABLE dbo.YourTable;
INSERT INTO dbo.YourTable (SomeCol)
VALUES('abc'); --Will get ID 4, because 1-3 have been used.
SELECT *
FROM dbo.YourTable; --Will get ID 1, as the column was reseed with the TRUNCATE
DROP TABLE dbo.YourTable;
For your specific question on reseeding, the next value after the seed your define is use. The seed you define is the one you are saying was last used. This is covered in the documentation Forcing the current identity value to a new value:
Because the table has existing rows, the next row inserted will use 11
as the value – the new current identity value defined for the column
plus 1 (which is the column's increment value).
The only way to define a table doesn't have existing rows is the TRUNCATE it, which is what I do later on in the above batch (and why 1 is reused).
At the end of the day, the value of your IDENTITY is meaningless other than to provide the row with a single use value (which is not guarenteed to be unique on it's own). Combined with the Primary key/Unique constraints, it makes a good Clustered index candidate, as the next value is always greater than the last used, and values aren't reused.
If having sequential values is important, then what you need to use is a SEQUENCE, not the IDENTITY property. The latter doesn't guarantee uniqueness, or sequential values on it's own (as they could be skipped due to deletes, failed inserts, an unexpected shutdown, etc), but it does guarantee it will not reuse values once they have been (without a RESEED): IDENTITY (Transact-SQL) - Remarks. A SEQUENCE can be used to ensure the values are indeed sequential (apart from due to a DELETE).
Welcome to the forum :)
If you created the table using
Id INT IDENTITY(1,1)
Then the first record inserted will have Id = 1, however, if the insert statement fails or the transaction is rolled back the consumed identity be marked as used (or lost) and the next insert statement will proceed from Id = 2.
Have a look at Microsoft documentation on this topic:
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-2017
When deleting inserted rows (which also happens when those inserts are rolled-back in a transaction, by the way), the identity value is not automatically reset. The identity functionality "remembers" its last value.
Gaps in the identity values will also NOT be filled when older records are deleted from the table and new records are inserted into the table.
That's just how identity works. It's a simple and safe mechanism.
If you (occasionally!) want to reset the identity value, you can take a look at DBCC CHECKIDENT. I personally tend to use it like this:
DBCC CHECKIDENT (MyTable, RESEED, 0) WITH NO_INFOMSGS;
DBCC CHECKIDENT (MyTable, RESEED) WITH NO_INFOMSGS;
(I execute both lines, in this order.)
I would advice against this practice in production environments, however.

identity id column in sql table doesn't start at 1

I ran a delete script to delete all rows that had an id greater than 0 to clear the table and now when I try to add rows to the table, the id starts off where it left off from before. How can I delete the info in the table so the id starts off at 1 again?
Delete statement doesnt reset the identity value. Use Truncate table command if you want identity value to be reset. something like this..
TRUNCATE TABLE Table_Name
This will empty the table and reset the identity value.
Only use TRUNCATE when you want all the rows to be deleted. As it does not allow you to use WHERE clause.
I don't think that is possible in the same table. Which database are you using? In previous versions of MS Access compacting the database used to work but not any more. I don't think SQL Server allows that either. The only way is to copy the records from this table to a new table, delete the old table and rename the new table to the old table name.
In MS-SQL you can have a play with DBCC CHECKIDENT (yourtable, reseed, 0)

How to Reorganize Identity Column Values in SQL Server 2008

I have a SQL Server database set up as the publisher in a replication environment. It has a couple of subscriptions and several different people have been executing INSERT statements on these. Because of the different value ranges allocated for identity columns, we end up with very wide variations once all the data is pushed back up into the publication.
This is of course to be expected and even desirable in a production environment. However, we're still in development and therefore desire to reorganize all identity values so they are sequential. Instead of [1,2,3,1001,1001,1003] we'd like to have [1,2,3,4,5,6]. I realize this means changing the identity column values and to update them accordingly across the relationships they support. Is it possible to do something like this?
Seed an identity column when you create it in Management Studio.
If you create the table using code, you can easily seed the table’s identity column using the Transact-SQL (T-SQL) CREATE TABLE statement in the following form:
CREATE TABLE tablename
(
columnname datatype identity [(seed, increment)
[NOT FOR REPLICATION]],
[columnname ...]
)
In the code, datatype is a numeric column. Both seed and increment are optional and the default value for both is 1.
Figure B shows the result of using CREATE TABLE to create a table named Orders and setting the OrderID column’s identity seed and increment values to 100 and 10, respectively. As you can see, the first identity value is 100 and each subsequent value increases by 10. (You can decrease identity values by specify a negative value for increment.)
And Use CREATE TABLE to seed an identity column.
Checking and reseeding
For instance, if you copy all the table’s records to an archive table and then delete all the records in the source table, you might want to reseed the source table’s identity column, so you can control the sequence. Use T-SQL’s DBCC CHECKIDENT as follows to reseed an identity column:
DBCC CHECKIDENT
(
tablename
[, [NORESEED | RESEED [, newreseedvalue]]]
)
[WITH NO_INFOMSGS]
Table A defines this statement’s optional parameters.
Table A: DBCC CHECKIDENT
Parameter
Description
NORESEED
Returns the current identity value and the current maximum value of the identity column, without reseeding. These values are usually (and should be) the same.
RESEED
Changes the current identity value, using the maximum value in the identity column, if the current identity value is less than the maximum identity value stored in the identity column.
newreseedvalue
Specifies the new seed value when reseeding. If the table is empty, the first identity value (after executing DBCC CHECKIDENT) will equal newreseedvalue. If the table contains data, the next identity value will equal newreseedvalue + the current increment value (the default is 1). This behavior is new to SQL Server 2005 (and remains in 2008). SQL Server 2000 always increments the seed value.
WITH NO INFOMSGS
Suppresses all informational messages.
Technically, DBCC CHECKIDENT checks and corrects an identity value. Simply put, use it to learn the current identity value or to reseed an existing identity column.

How to reseed/replace identity columns on existing data

Hey all I want to reseed my IDENTITY COLUMN values starting from 1 I know how to do this with DBCC CHECKIDENT, however, I would like to replace the value in all existing rows.. This table has a little over 2 million rows.
What is the best approach for this task?
You can simply add a new identity column, a la How to add a new identity column to a table in SQL Server?. Just delete the old column and re-add it. This will break any foreign keys, of course, but I assume since you are re-numbering everything I am guessing that's ok.
See this example how to replace values, but RESEED is something else:
CREATE TABLE t (id INT IDENTITY)
GO
INSERT t DEFAULT VALUES
GO 25
SET IDENTITY_INSERT t ON
delete t
OUTPUT DELETED.Id+100 INTO T(Id)
SET IDENTITY_INSERT t Off
SELECT * FROM t
DROP TABLE t
An example of reseed:
DBCC CHECKIDENT('YourTableName', 150, reseed)
AND
If you have to replace the value - with 2M rows it definitely have to take time

SQL-How to Insert Row Without Auto incrementing a ID Column?

I have a table that has a forced auto increment column and this column is a very valuable ID that is retained through out the entire app. Sorry to say it was poor development on my part to have this be the auto incrementing column.
So, here is the problem. I have to insert into this table an ID for the column that has already been created and removed from the table. Kind of like resurrecting this ID and putting it back into the table.
So how can I do this programatically do this without turning the column increment off. Correct me if I am wrong, if I turn it off programatically, It will restart at 0 or 1 and I don't want that to happen...
If you are in Microsoft SQL Server, you can "turn off" the autoIncrementing feature by issuing the statement Set Identity_Insert [TableName] On, as in:
Set Identity_Insert [TableName] On
-- --------------------------------------------
Insert TableName (pkCol, [OtherColumns])
Values(pkValue, [OtherValues])
-- ---- Don't forget to turn it back off ------
Set Identity_Insert [TableName] Off
In addition to Charles' answer (which is now 100% correct :-) and which preserves the current value of the IDENTITY on the table), you might also want to check the current value of an IDENTITY on a table - you can do this with this command here:
DBCC CHECKIDENT('YourTableName')
If you ever need to actually change it, you can do so by using this command here:
DBCC CHECKIDENT ('YourTableName', RESEED, (new value for IDENTITY) )
Actually, the code above for INDENTITY_INSERT is correct - turning it ON tells the server you want to insert the values yourself. It allows you to insert values into an IDENTITY column. You then want to turn it back off (allowing the server to generate and insert the values) when you are done.
bulk insert tablename from 'C:\test.csv' with (rowterminator = '\n',fieldterminator = ',',KEEPIDENTITY)