Increment autoincrement id field by one - mysql

I have a MySQL 5 server and a table in it with an autoincrement on an id field (primary key). Now I want to add a record in between and so I have to increase all other ids by one. This is what I tried:
UPDATE myTable SET id=id+1 WHERE id >= 53
This doesn't work because for example a record with id = 52 already exists. How can I do this? If he would start at the last entry and makes the updates it should work I think. But how?

I see no good reason for this. Only problems. Before running the folowing statement, check if you have FOREIGN keys defined, that reference this id. Are they set to ON UPDATE CASCADE? Also, do you have any triggers that are related to this table?
But first consider, why you (think you) need this. Is it going to be used for ordering the table? In that case, as #Mark pointed, you should use a separate column to specify your desired order.
If, however, you decide you really want this, use:
UPDATE myTable
SET id = id + 1
WHERE id >= 53
ORDER BY id DESC ;

Quick and dirty you do it in 2 steps.
increase the id to a number higher that all others
decrease all ids to the number you want
Like that
UPDATE myTable SET id=id+10000 WHERE id >= 53
UPDATE myTable SET id=id-9999 WHERE id >= 53

I had faced same problem. And also tried with query by OP and #Romain Hoog . But not succeeded.
Finally exported data of whole table in excel and done it in excel (not one by one but using trick that makes it very fast).
then taken backup of original table recreated new table and imported data from updated excel .

I guess something like that works :
UPDATE myTable SET id=id+1 WHERE id >= (select id from myTable order by id DESC)

Related

Update the path column in MySQL database for specific records

I have a column in MySQL database that store the images names/IDs something like "523523525.jpg".
I want to update this column by adding the folder before the image name/ID to be like "101/523523525.jpg". I want to update specific records not all the column, for example update from record 1 to 1000 by adding "101/...." and records from 1001 to 2000 by adding "102/....".
Look for your ideas.
Add an id column.
ALTER TABLE your_table ADD
COLUMN id INT AUTO_INCREMENT
PRIMARY KEY FIRST;
use concat to update rows based on id
UPDATE your_table SET
Column=CONCAT("101/",column)
WHERE id BETWEEN 1 AND 1000;
for first 1 to 1000 to use LIMIT in update statement.
For next 1001-2000 you need to write anonymous block or procedure using cursor to update records.
How about using the CONCAT function? Assuming you have a seperate column for the id, you can execute an update query to add the path to the existing value.
UPDATE your_table SET path_col=CONCAT('101/', path_col) WHERE id between 1 AND 1000;
Hope it helps! Feel free to ask if you need to know anything.

A way to keep and update only one row with TYPE=3

The table:
ID TYPE USER_ID
======================
1 1 15
2 1 15
. 3 15
. 1 15
.
should keep multiple USER_ID's with TYPE=1 but only 0 or 1 row where TYPE=3.
In the case that TYPE=3, upon insert I need to either update or create (much like insert on duplicate key update) that row.
Is there a good way to accomplish this without first SELECTing, and updating or inserting depending on the SELECT results in the program?
Preferably doing this in a single command, and without triggers?
One way might be to add new tuple, hold the user id you added in a variable, then
delete where type = 3 and id != {Added id}
it would work, but I want to make the disclaimer that it seems dodgy somehow
You can do the update with subqueries. In this case since you would want to read and write to the same tuple you would need to rename the subquery on the same table to erase the lock on that tuple.
Say you want to update the user_id of the first row of data with type=3 to
20 do:
UPDATE tbl SET user_id=20 WHERE id=
(SELECT A.id FROM (SELECT MIN(id) id
FROM tbl
WHERE type=3) A);
See DEMO ON SQL Fiddle.

How to update the nth row in a SQL database table?

How can I update only the nth row from a table?
To update the second row for example, i tried using UPDATE and LIMIT, but it is giving me an error.
UPDATE database_table
SET field = 'new_value'
LIMIT 0, 1
Is there a way to do it?
If you have a primary key and a column you'd like to order by (to get the nth row), you could do something like:
UPDATE database_table
SET field = 'new_value'
WHERE primary_key IN (
SELECT primary_key
FROM database_table
ORDER BY some_date_column
LIMIT n - 1, 1
)
Edit: I should probably add a caveat. This answer might be technically correct, but you're likely wrong to use it. I can't imagine too many scenarios where you'd actually want to update the nth row of a table. You should generally only be updating tables based on primary keys. Updating the nth row will likely break your app if multiple users (or even multiple sessions with the same user) are using it at the same time.
The real answer is you should probably change your code to update based on primary key.
You would need some sort of id, and then do something like this:
UPDATE database_table SET field = 'new_value' WHERE id = 2

Is it possible to insert a new row at top of MySQL table?

All rows in MySQL tables are being inserted like this:
1
2
3
Is there any way how to insert new row at a top of table so that table looks like this?
3
2
1
Yes, yes, I know "order by" but let me explain the problem. I have a dating website and users can search profiles by sex, age, city, etc. There are more than 20 search criteria and it's not possible to create indexes for each possible combination. So, if I use "order by", the search usually ends with "using temporary, using filesort" and this causes a very high server load. If I remove "order by" oldest profiles are shown as first and users have to go to the last page to see the new profiles. That's very bad because first pages of search results always look the same and users have a feeling that there are no new profiles. That's why I asked this question. If it's not possible to insert last row at top of table, can you suggest anything else?
The order in which the results are returned when there's no ORDER BY clause depends on the RDBM. In the case of MySQL, or at least most engines, if you don't explicitly specify the order it will be ascending, from oldest to new entries. Where the row is located "physically" doesn't matter. I'm not sure if all mysql engines work that way though. I.e., in PostgreSQL the "default" order shows the most recently updated rows first. This might be the way some of the MySQL engines work too.
Anyway, the point is - if you want the results ordered - always specify sort order, don't just depend on something default that seems to work. In you case you want something trivial - you want the users in descending order, so just use:
SELECT * FROM users ORDER BY id DESC
I think you just need to make sure that if you always need to show the latest data first, all of your indexes need to specify the date/time field first, and all of your queries order by that field first.
If ORDER BY is slowing everything down then you need to optimise your queries or your database structure, i would say.
Maybe if you add the id 'by hand', and give it a negative value, but i (and probably nobody) would recommend you to do that:
Regular insert, e.g.
insert into t values (...);
Update with set, e.g.
update t set id = -id where id = last_insert_id();
Normally you specify a auto_incrementing primary key.
However, you can just specify the primary key like so:
CREATE TABLE table1 (
id signed integer primary key default 1, <<-- no auto_increment, but has a default value
other fields .....
Now add a BEFORE INSERT trigger that changes the primary key.
DELIMITER $$
CREATE TRIGGER ai_table1_each BEFORE INSERT ON table1 FOR EACH ROW
BEGIN
DECLARE new_id INTEGER;
SELECT COALESCE(MIN(id), 0) -1 INTO new_id FROM table1;
SET NEW.id = new_id;
END $$
DELIMITER ;
Now your id will start at -1 and run down from there.
The insert trigger will make sure no concurrency problems occur.
I know that a lot of time has passed since the above question was asked. But I have something to add to the comments:
I'm using MySQL version: 5.7.18-0ubuntu0.16.04.1
When no ORDER BY clause is used with SELECT it is noticeable that records are displayed, regardless of the order in which they are added, in the table's Prime Key sequence.

Adjust MySQL ID column +1

I have about 1000 rows, and want to increment all of the rows' ID number by 1. I was thinking something like this might work
UPDATE table
SET id = id+1
I tried in phpMyAdmin, but got this: Duplicate entry '2' for key 'PRIMARY'
This makes perfect sense, but how can I get around it?
Isn't it much easier to order it backwards?
update table set id = id +1 order by id desc
this works for me...
Follow the steps:
crate a temp table
copy all data to this temp table with desired id
delete original table
At the end rename the temp table to original table.
That's all.
use a big enough number that wont create duplicates
update table set id = id + 1000001;
update table set id = id - 1000000;
keep in mind this will increase the auto increment key if you are using one