Continue with Id order values after delete some rows - sql

I accidentally deleted some rows from a table, it's just 4 rows, but now when I try to insert the same values again the Id values are different, it's like it's remembering the Id values that had the rows I deleted before and now every time I insert a row the value generated for Id is not the next to the existent sequence... For example:
Id Name
1 Peter
2 Luis
3 Charles
4 John
Let's say I deleted rows with Name value Peter, Luis, Charles and John. When I try to insert the same names again it inserts them but with a different Id..
Id Name
1 Peter
5 Luis
6 Charles
7 John
I can not change the Identity value manually to the old values.. Which is the best solution in this case?

The reason is that auto-incrementing Id's don't automatically reset. This is by design, as you may have the same values references in other tables, which you may not want to delete (although it creates orphaned rows).
The method of resetting the auto-incrementing value differs between databases. For instance, in MySQL, you can run:
ALTER TABLE myTable SET AUTO_INCREMENT=1;

If you AUTOINCREMENT the Primary Key then you can't change the sequence with which you have started.Even if you insert the same name again it does not matter.It will continue from the next number with which it previously ended.
But if you want to give it a number then don't AUTOINCREMENT it,INSERT primary key value like other values you have inserted in the table.

I ended up setting identity_insert to on and entering the Ids manually with the names and then changed the table back to how it was with identity_insert off

Related

Duplicate multiple records with one INSERT statement

In MS-Access 2019, I'd like to duplicate existing records from tblTest and change one field tLink as a foreign key to another table.
I know how to do it with VBA looping over recordsets, but I'd like to use SQL here.
I assume it can be solved with a single statement, and as SQL-newbie I'm eager to learn how to do it.
So let's assume a simple table tblTest, tID is Primary Key and auto-number
tID tLink tName
Long Long Text(50)
-----------------------------
1 3 Bill
2 17 Sue
3 9 Tom
4 3 Chris
I'd like to duplicate all records with tLink = 3 and set their tLink to 1.
When snooping around in various tutorials, I learned ...
INSERT INTO tblTest SELECT * FROM tblTest WHERE tID=1
... but this fails because of tID having to be a unique value.
So I am stuck at this point, and removing the primary key from the table is not an option here. Is there a way around it?
So, (1) how to duplicate one record without running into the primary key issue, and then, (2) multiple records with 1 SQL statement?
I would then use UPDATE to set tLink to 1 WHERE tLink=3
I'd like to duplicate all records with tLink = 3 and set their tLink to 1.
If you have an auto-number column, then you can just leave it apart in the insert statement. Access will automatically assign a new value for every inserted row.
What you want should be as simple as:
INSERT INTO tblTest(tLink, tName) SELECT 1, tName FROM tblTest WHERE tLink = 3

Entering data at a specific ID where as Auto Increment is ON (i.e Identity =TRUE)

how to insert value at a specific index in id Column where as Id Field is auto increment
for Example in may case say columns are ID and Name
ID Name
========================================
2 Austin
3 Peter
4 Albness
22 Sidhu
23 deepika
24 Shahrukh
Where Id is Auto incremented here in my case I have deleted the Id 1,4,5,6 to onward 21 and now I want to add the new name at Id=1 remember again Id is auto_increment (i.e Identity=TRUE in the property )
How do I Accomplish it
For all use cases I can think of, just leaving the gaps seems to be the simpler and safer solution. End users should not see these IDs, and DBAs should be OK with it.
If it's such a big deal, I'd still rather have a DBA manually run a "cleanup" script in a maintenance window than add complexity to production code.
To insert ID value on a table just do that
SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON | OFF }
Example your table name is People it should be
INSERT INTO People(ID,NAME) VALUES(3,'Felicio')
PS: to insert indentity value you also need to explicity the columns names and order as in previous example.
Id is either surrogate or natural key.
If it's surrogate, it doesn't have a meaning, and therefore gaps don't matter.
If it's natural, it shouldn't have been auto-increment in the first place.

Automatic id assign

i'm a student and im having problems using the automatic increment because when i delete a row it will continue to increment. explaining:
i want to increment id automaticly
so:
id name age
1 michael 18
2 katy 17
3 jack 20
now i delete row 3 and when i click in the button new it'll go to the id 4 instead of id 3
i'v tried rows.count and refresh the textbox but nothing
some adicional info
ds= dataset
maxrows = ds.Tables("virtualtable").Rows.Count
idcliTextBox.Text = maxrows
how do i make it set id to the real last row?
It is the correct behavior and it is not a problem. Usually the autoincrement columns in a database are never reset to accomodate for empty holes caused by deletion of previous inserted records.
The autoincrement column is usually used as primary key to uniquely identify a single record in your table.
Suppose that your table represents students where the ID field value is used as foreign key for another table examresults. In this table you store the exam result of your students. Your student Katy (2) has two records in the examresults table for the graduation in math and geography.
If you delete the record with ID=2 from the table students and the related records from examresults changing the record for Jack from 3 to 2 means that you need to change also the related records for examresults of Jack. This is very impractical and useless if you think about it.

Autoincrement in Oracle(Adjust the ID sequence after deleting)

CREATE TABLE test
(id NUMBER PRIMARY KEY,
name VARCHAR2(30));
CREATE SEQUENCE test1_sequence
START WITH 1
INCREMENT BY 1;
INSERT INTO test (id, name) VALUES (test1_sequence.nextval,'Jon');
INSERT INTO test (id, name) VALUES (test1_sequence.nextval,'Hello');
INSERT INTO test (id, name) VALUES (test1_sequence.nextval,'Matt');
INSERT INTO test (id, name) VALUES (test1_sequence.nextval,'Bork');
And suppose if I deleted one record from this table by-
delete from test where id='2';
then If I do select query-
select * from test;
then I get
ID Name
1 Jon
3 Matt
4 Bork
So If I need to maintain the order of id, like as soon as I delete any data it adjusts the id automatically. So I should be getting the table as
ID Name
1 Jon
2 Matt
3 Bork
Any suggestions how can I do this..
If I remember correctly from articles on Ask Tom website, sequence DOES NOT guarantee that it will produce gap free numbers. So the way you are filling up your table and generating ID's will never be 100% gap free (even without deleting rows).
Here's one of the articles on that subject: http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:4343369880986
Also keep in mind that you are updating (what seems a) primary key column.
My suggestion is not to do it. If you need a ordered list of rows, use ROW_NUMBER and leave PK to be a surrogate key without attaching any "application meaning" to it.

Filling the gaps in values of IDENTITY column

I have a table with an IDENTITY column
[Id] int IDENTITY(1, 1) NOT NULL
After some rows beeing added/removed I end with gaps in Id values:
Id Name
---------
1 Tom
2 Bill
4 Kate
Is there an easy way to compress the values to
Id Name
---------
1 Tom
2 Bill
3 Kate
?
I would strongly recommend that you leave the identity values as they are.
if this ID column is used as a foreign key on another table, changing them will get complicated very quickly.
if there is some business logic where they must be sequential then add a new column ID_Display where you can update them using ROW_NUMBER() and keep them pretty for the end user. I never let end users see and/or dictate how I create/populate/store the data, and if they are bothering you about the IDs then show them some other data that looks like an ID but is not a FK or PK.
I think it's pretty easy to create a 2nd table with the same schema, import all the data (except for the identity column of course; let the 2nd table start renumbering) from the first table, drop the first table and rename the 2nd to the original name.
Easiness may be in question if you'd have a ton of FK relationships to rebuild with other tables etc.
Well as far as I know the only way you can is manually update the values by turning Identity insert on..but you should really avoid doning such a thing in first place..also if you truncate the table it will not have those gaps.
I cannot control the part which requires ID columns to be in sequence.
This sounds like there is program logic which assumes there are no gaps--correct?
I need this to keep two different databases in sync.
It's still not clear what you mean. If the actual values in the IDENTITY column are not meaningful (not used as foreign keys by other tables), you can just do this:
DELETE FROM db1.table
SELECT col1, col2, col3 /* leave out the IDENTITY column */
INTO db1.table FROM db2.table