How to set auto increment value after deleting a middle row - php

I have a Table
id paper_title
1 General English1
2 General English2
3 General English3
4 General English4
5 General English5
6 General English6
7 General English7
.
.
.
.
100 General English100.
Suppose If i delete row 4 and row 5, is it possible to update the id of General English6 And General English7 Set to 4,5 respectively and If i delete a row in middle or start the id should reset continuously like 1 2 3 4 5..................100.Please Help.

Determine the id of the row that you want to delete (let's call that id $foo). Then execute
UPDATE tbl SET id = id-1 WHERE id > $foo
get the highest id and call it $max:
SELECT MAX(id) FROM tbl
Then set the new auto increment value:
ALTER TABLE tbl AUTO_INCREMENT = $max+1
Do this for every row you delete. I sure hope id is not your primary key. And anyways, there is definitely a better solution to your underlying problem. There is usually no need to have the rows in a database table numbered from 1 to whatever without gaps.

Related

Inserting row in the middle of SQL table and adjusting ascending id's

I wish to allow insertion of rows in the middle of a sql table and afterwards automaticly update the ascending id's to be +1.
Example:
ROW ID
1 5
2 6
3 7
4 8
I then want to be able to insert a 5th row with the id of 6, and make the other rows update to be +1 of their current number:
ROW ID
1 5
2 7
3 8
4 9
5 6
Is there an efficient way to this? other than running through the whole table and adjusting the other id's to +1?
Add an index to the ID column. That way you only need to run through the rows that are actually affected by the update operation instead of though the whole table. On the downside, each index makes inserts more expensive.
BTW Don't change ID entries if the ID column belongs to your primary key.

How to maintain proper number order in mysql auto increment field when delete rows

I have a table A which has a auto increment serial number field SLNO. When i insert values in table it will increment automatically like 1,2,3,4... etc. But when i delete a row from the table the order get break. ie, if delete row with serial number 2 then the serial number field will 1,3,4. But I want to maintain a continuous order like 1,2,3 even delete rows. Is there any way to maintain this order, like using trigger or somthing
A primary auto-increment key is only for uniquely identifying a record. Just leave it be.
Don't misuse the primary key as indicator of your record order. If you need specific order of your records then use an extra column for that. For instance a timestamp column.
If you need a specific order of your records use a timestamp column with a default value of current_timestamp. That way it will be inserted automatically.
ALTER TABLE your_table
ADD column inserted_timestamp TIMESTAMP default current_timestamp;
SQLFiddle demo
You should leave it as it is.
However, if you do really need, you can "recalculate" the primary key, the index:
set #pk:=0;
update
your_table
set pk=#pk:=#pk+1
order by pk;
add a column that will speicfy that is deleted
example:
1 - deleted already
0 - not deleted
and add where deleted = 0 in your select query
primary key column 2 column3 ..... deleted
1 1
2 0
3 0
4 1
5 0
Storing an number of a record would make deletes inefficient. Instead you can rely on existing SLNO indexes you already have, that should be enough for all use cases that come up to my mind.
If you SELECT whatever ORDER BY SLNO LIMIT ... OFFSET k, then returned rows have IDs k, k+1, k+2, ...
If you want to get an id of a record knowing its SLNO:
SELECT COUNT(SLNO) FROM A WHERE SLNO <= thatnumber
If you want to get thatnumber'th record:
SELECT * FROM A ORDER BY SLNO LIMIT 1 OFFSET thatnumber
You can do by alter the table and delete primary key then again create primary key.
But why you need this. If you have use this key as foreign key in other table. Then you lost all the data.

MySQL update IDs on update, insert and delete

In my current application I am making a menu structure that can recursively create sub menu's with itself. However due to this I am finding it difficult to also allow some sort of reordering method. Most applications might just order by an "ordering" column, however in this case although doing that does not seem impossible, just a little harder.
What I want to do is use the ID column. So if I update id 10 to be id 1 then id 1 that was there previously becomes 2.
What I was thinking at a suggestion from a friend was to use cascades. However doing a little more research that does not seem to work as I was thinking it might.
So my question is, is there an ability to do this naively in MySQL? If so what way might I do that? And if not what would you suggest to come to the end result?
Columns:
id title alias icon parent
parents have a lower id then their children, to make sure the script creates the array to put the children inside. That part works, however If I want to use an ordering column I will have to make a numbering system that would ensure a child element is never higher then its parent in the results. Possible, but if I update a parent then I must uniquely update all its children as well, resulting in more MySQL queries that I would want.
I am no MySQL expert so this is why I brought up this question, I feel there might be a perfect solution to this that can allow the least overhead when it comes to the speed of the application.
Doing it on the ID column would be tough because you can't ever have 2 rows with the same ID so you can't set row 10 to row 1 until after you've set row 1 to row 2 but you can't set row 1 to row 2 until you set row 2 to row 3, etc. You'd have to delete row 10 and then do an update ID += 1 WHERE ID < 10... but you'd also have to tell MySQL to start from the highest number and go down....
You'd have to do it in separate queries like this:
Move ID 10 to ID 2
DELETE FROM table WHERE id = 10;
UPDATE table SET id = id + 1 WHERE id >= 2 AND id < 10 ORDER BY id DESC
INSERT INTO table (id, ...) VALUES (2, ...);
Another option, if you don't want to delete and reinsert would be to set the id for row 10 to be MAX(id) + 1 and then set it to 1 after
Also if you want to move row 2 to row 10 you'd have to subtract the id:
Move ID 2 to ID 10
DELETE FROM table WHERE id = 2;
UPDATE table SET id = id - 1 WHERE id > 2 AND id <= 10 ORDER BY id DESC
INSERT INTO table (id, ...) VALUES (10, ...);
If you don't have your ID column set as UNSIGNED you could make all the IDs you want to switch to negative ids since AUTO_INCREMENT doesn't do negative numbers. Still this is pretty hacky and I wouldn't recommend it. You also probably need to lock the table so no other writes happen while this is running.:
Move ID 2 to ID 10
UPDATE table SET id = id * -1 WHERE id > 2 AND id <= 10;
UPDATE table SET id = 10 WHERE id = 2;
UPDATE table SET id = id * -1 - 1 WHERE id < -2 AND id >= -10;

Auto update unique id

I have a table with a column 'id' which has auto_increment on.
So for example when I add a new record it will assign it a number.
But what I need is a way I can change the order of the records so for example there are 48 records in the db and I want record 29 to have the id of 5 instead of 29. So is there a way for record 29 to replace 5 and for them to all move up one so 5 would now be record 6 etc?
Thanks!
If you need to allocate the id yourself, do not use an auto increment column.
A separate question is to do with renumbering records in a database table and yes, this can be done with an ordered update query.
First of all you would clear the space for the new record 5 thus:
UPDATE table SET id=id+1 WHERE id > 4 ORDER BY id DESC
Then you would renumber record 29 thus
UPDATE table SET id=5 WHERE id = 29

delete one row in the middle and how to refresh the table id(auto increment) in mysql

For example:
Row Name
1 John
2 May
3 Marry
4 Tom
5 Peter
Suppose I delete row 2 and row 3, is it possible to update Tom and Peter to row id 2 and 3 respectively and the next insert row to be row id 4?
yes, but you need to recreate Row:
ALTER TABLE `users` DROP `Row`;
ALTER TABLE `users` AUTO_INCREMENT = 1;
ALTER TABLE `users` ADD `Row` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
No, because think of the problems that this could create. Imagine if you are managing a store inventory and each item has an internal barcode, based on an ID in a database table. You decide never to stock one item again and take it out of the database, and then every ID for every item with an ID greater than the removed item gets decremented by 1... all those barcodes on all those items become useless.
ID numbers in databases aren't generally meant to be used or referenced by people. They are meant to be a static index of a certain item in a database which allows the computer to pull up a given record quickly and reliably. When creating your ID field of your table, make sure you make the datatype large enough to account for these lost IDs when they do occur.
This is just a suggestion. I don't say this is the best solution. Just consider.
You execute your delete query.
DELETE FROM table_name WHERE Row IN (2,3);
Once deleted you make a select query request with PHP and get the data set to an array.
SELECT Row, Name from table_name ORDER BY Row ASC;
Then make a UPDATE execution using a loop.
$index = 1;
foreach($dataset as $item)
{
// Your update query
$sql = "UPDATE table_name SET Row=$index where Name='" . $item['Name'] . "'";
$index++;
}
Before you insert next query you have to get the max value of Row and set +1 value as the Row of the insert query.
This is just an idea. Not the complete code.

Categories