How to reseed an an auto increment column in a SQLite database? - sql

Is it possible to reseed an auto increment column in a SQLite database, and if so, how is this done?
ie. The equivalent of DBCC CHECKIDENT ('MyTable', RESEED, 1) in SQL Server.

In SQLite there is a table named SQLITE_SEQUENCE, which tracks the largest RowId value that a table has. You can do insert, updates and deletes on this table. For example, to mimic similar functionality as the TRUNCATE TABLE statement SQL Server you could something like:
DELETE FROM MyTableName;
DELETE FROM SQLITE_SEQUENCE WHERE NAME = 'MyTableName';
In the above example all data from MyTableName is removed, and the auto increment rowid is reset by removing the value from the SQLITE_SEQUENCE table. See the documentation for AUTOINCREMENT for more information.

DELETE
FROM MyTableName
select *
from SQLITE_SEQUENCE
update SQLITE_SEQUENCE
set seq = 0
where name ='MyTableName'

Alternatively you could export a SQL file from the SQLite database. Then edit the generated SQL file and update the appropriate entries to the desired IDs or delete the INSERT statements. After this create a new empty database and seed it with the adjusted SQL file. The highest ID + 1 will then be the ID for a new entry...
With this way you can decide, which entries to keep and which entries should be removed as a non-destructive or even a more flexible approach.
For me it worked - clean and easy. ;)

Related

how to Reset AutoIncrement in SQL Server after all data Deleted

i got a function in sql that generate sequential series of alphanumeric
no.like (c000,c0001 .......) , which is working good . but when i deleted all data in table , it starts from last generated no. i want it to reset its value from "c0000" .
code is as follows :-
create table Customers
(
dbID int identity not null primary key,
CustomerName varchar(100)
)
create function CustomerNumber (#id int)
returns char(5)
as
begin
return 'C' + right('0000' + convert(varchar(10), #id), 4)
end
alter table Customers add CustomerNumber as dbo.CustomerNumber(dbID)
thanks in advance....
EDIT 1 -
how to update it to increment based on last value . means if last entry having no. c0053 , and i deleted this record , so when next entry added it should have value "C0053" not "C0054".
thanks
Truncate Table Command is good way to reset Identity, but there is other command also to reset Identity after deletion of records.
DBCC CHECKIDENT (TableName, RESEED, 0)
After Deleting you can use this command to reset Identity to 0.
TRUNCATE TABLE
Removes all rows from a table or specified partitions of a table, without logging the individual row deletions. TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources.
TRUNCATE TABLE Customers
or remove your in build function.
My suggestion is instead of deleting all rows of data why dont you truncate the table.
If you are truncate the table it automatically reset your auto increment to 0
TRUNCATE TABLE your_table_name;
This example would truncate the table and remove all records from that table. and rest your auto increment too.
The SQL TRUNCATE TABLE command is used to delete complete data from an existing table
Try this way. May help you.

Updating Identity Column of a table with consecutive numbers through SQL Stored Procedure

After deleting the duplicate records from the table,
I want to update Identity column of a table with consecutive numbering starting with 1. Here is my table details
id(identity(1,1)),
EmployeeID(int),
Punch_Time(datetime),
Deviceid(int)
I need to perform this action through a stored procedure.
When i tried following statement in stored procedure
DECLARE #myVar int
SET #myVar = 0
set identity_insert TempTrans_Raw# ON
UPDATE TempTrans_Raw# SET #myvar = Id = #myVar + 1
set identity_insert TempTrans_Raw# off
gave error like...Cannot update identity column 'Id'
Anyone please suggest how to update Identity column of that table with consecutive numbering starting with 1.
--before running this make sure Foreign key constraints have been removed that reference the ID.
--insert everything into a temp table
SELECT (ColumnList) --except identity column
INTO #tmpYourTable
FROM yourTable
--clear your table
DELETE FROM yourTable
-- reseed identity
DBCC CHECKIDENT('table', RESEED, new reseed value)
--insert back all the values
INSERT INTO yourTable (ColumnList)
SELECT OtherCols FROM #tmpYourTable
--drop the temp table
DROP TABLE #tmpYourTable
GO
The IDENTITY keword is used to generate a key which can be used in combination with the PRIMARY KEY constraint to get a technical key. Such keys are technical, they are used to link table records. They should have no other meaning (such as a sort order). SQL Server does not guarantee the generated IDs to be consecutive. They do guarantee however that you get them in order. (So you might get 1, 2, 4, ..., but never 1, 4, 2, ...)
Here is the documentation for IDENTITY: https://msdn.microsoft.com/de-de/library/ms186775.aspx.
Personally I don't like it to be guaranteed that the generated IDs are in order. A technical ID is supposed to have no meaning other then offering a reference to a record. You can rely on the order, but if order is information you are interested in, you should store that information in my opinion (in form of a timestamp for example).
If you want to have a number telling you that a record is the fifth or sixteenth or whatever record in order, you can get always get that number on the fly using the ROW_NUMBER function. So there is no need to generate and store such consecutive value (which could also be quite troublesome when it comes to concurrent transactions on the table). Here is how to get that number:
select
row_number() over(order by id),
employeeid,
punch_time,
deviceid
from mytable;
Having said all this; it should never be necessary to change an ID. It is a sign for inappropriate table design, if you feel that need.
If you really need sequential numbers, may I suggest that you create a table ("OrderNumbers") with valid numbers, and then make you program pick one row from OrderNumbers when you add a row to yourTable.
If you everything in one transaction (i.e. with Begin Tran and Commit) then you can get one number for one row with no gabs.
You should have either Primary Keys or Unique Keys on both tables on this column to protect against duplicates.
HIH,
Henrik
Check this function: DBCC CHECKIDENT('table', RESEED, new reseed value)

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)

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)

Reset auto-incrementing column

I recently added Items to an ID and the the table got messed up in the transfer process so I deleted the Items from the table. Upon reentering the data instead of the ID starting at one it now starts at 332. I would like to have the table start at one instead of 332. I've removed the data from the data so it's clear. How do I reset the ID to one.
Thanks and sorry if this on here somewhere I wasn't sure how to search for this.
In SQL Server:
DBCC CHECKIDENT (myTable, RESEED, 0)
truncate table yourtable --will reseed
Assuming MSSQL:
DBCC CHECKIDENT('MyTable', RESEED, 0) -- One less than next ID to allocate
If you want to remove the data too you can use
TRUNCATE TABLE MyTable
but you cannot use TRUNCATE TABLE on a table referenced by a Foreign Key, or if the table is part of an indexed view, and unlike DELETE MyTable any trigger(s) on the table won't be activated.
Set the starting identity value to 1
DBCC CHECKIDENT (tableName, RESEED, 1)
If you are using MS Access, delete and recreate the table
you need to truncate the table
but to do so it has be empty, and no foreign keys attached to it at all