Change MySQL query execution order - mysql

I want to put a entry in the database with id of 2. In order to do that I'm moving all records having more than 2 to id + 1.
UPDATE
`pedo_meta`
SET
`id` = `id` + 1
WHERE
`id` > 1;
Because id is a primary key. This query is failing saying :
#1062 - Duplicate entry '3' for key 'PRIMARY'. I know this is happening because query execution starts from top to bottom and when the query tries to make a the column having id 2 to id 3, a duplicate entry error occurs because id 3 column already exists.
I believe this problem can be solved if we reverse the order of execution. So the query starts by making id 537 to 538 then 536 to 537 and so on. So is there any to reverse the order of execution for a query in MySQL?

You can use ORDER BY on the UPDATE statement to affect the order the rows are updated:
If the ORDER BY clause is specified, the rows are updated in the order that is specified.
source: https://dev.mysql.com/doc/refman/8.0/en/update.html
So you can use the following UPDATE statement:
UPDATE `pedo_meta`
SET `id` = `id` + 1
WHERE `id` > 1
ORDER BY `id` DESC;
demo on dbfiddle.uk
Note: If you want to change the sort order of items you shouldn't use the ID column. You can add an additional numeric column to define a sort order. The ID column should only be use to identify a record in the table.

Here is a simple algorithm to accomplish that fast:
1. create a new column new_id
2. set new_id = id + 1
3. update id and set it to be id = new_id
4. remove column new_id when you are done
P.S. IF you want to sort your items after id is better to create a new column sort_order which can be updated extremely fast...

Related

MYSQL: How to update unique random number to existing rows

It's been my first question to this website, I'm sorry if I used any wrong keywords. I have been with one problem from quite a few days.
The Problem is, I have a MYSQL table named property where I wanted to add a ref number which will be a unique 6 digit non incremental number so I alter the table to add a new column named property_ref which has default value as 1.
ALTER TABLE property ADD uniqueIdentifier INT DEFAULT (1) ;
Then I write a script to first generate a number then checking it to db if exist or not and If not exist then update the row with the random number
Here is the snippet I tried,
with cte as (
select subIdentifier, id from (
SELECT id, LPAD(FLOOR(RAND() * (999999 - 100000) + 100000), 6, 0) AS subIdentifier
FROM property as p1
WHERE "subIdentifier" NOT IN (SELECT uniqueIdentifier FROM property as p2)
) as innerTable group by subIdentifier
)
UPDATE property SET uniqueIdentifier = (
select subIdentifier from cte as c where c.id = property.id
) where property.id != ''
this query returns a set of record for almost all the rows but I have a table of entries of total 20000,
but this query fills up for ~19000 and rest of the rows are null.
here is a current output
[current result picture]
If anyone can help, I am extremely thanks for that.
Thanks
Instead of trying to randomly generate unique numbers that do not exist in the table, I would try the approach of randomly generating numbers using the ID column as a seed; as long as the ID number is unique, the new number will be unique as well. This is not technically fully "random" but it may be sufficient for your needs.
https://www.db-fiddle.com/f/iqMPDK8AmdvAoTbon1Yn6J/1
update Property set
UniqueIdentifier = round(rand(id)*1000000)
where UniqueIdentifier is null
SELECT id, round(rand(id)*1000000) as UniqueIdentifier FROM test;

A command in MySql to increment by one the ID column

This is my case:
What I want is to increment all rows after the raw of 135th by one, for e.g: 136,137.
I have been trying to make some updates but none of them works.
Can you please help me?
Thanks in advance
It fails because the consecutive ID's already exist. What you could do is first increasing you ID's to non-existing values, then decrease them to the values you want.
Example
Increase the ID's with a bigger amount than the highest ID, i.e.:
UPDATE tablename SET id = id + 100000 WHERE id >= 135;
Then decrease them to the values you wanted (in this case 100.000 minus 1)
UPDATE tablename SET id = id - 99999 WHERE id >= 100000;
Reset the auto increment
ALTER TABLE tablename AUTO_INCREMENT = 1;
Try
UPDATE `tablename` SET `id` = `id` + 1 WHERE `id` >= 135 ORDER BY `id` DESC

Delete first row and place copy of row on end of table

Hi guys I have a mySQL database with a table called queue the rows consist columns singer and song. I'm using the table to keep the order the singers have gone up there is an auto increment Id
What I am trying to find is the proper syntax to copy the first row from my table to the last row with a new auto increment ID value and then delete the first row. It didn't seem such a challenge until I tried to write it . Any ideas are welcome.
Since getting an answer I have tried this.. but keep getting error 1111
UPDATE `queue`
SET `id` = MAX(id) + 1;
WHERE `id` = MIN(id);
Have also tried this...how can this be so hard.
Set $max = (SELECT MAX(id) + 1 FROM queue);
Set $min = (SELECT MIN(id) FROM queue);
UPDATE `queue`
SET `id` = $max
WHERE `id` = $min;
So I have abandoned the max() min() thought unless someone has a usable answer and moved to my original thought and I am very close. but my problem is I will not know the lowest id to remove because it would only be 1 once so I need to fill it in with a MIN(id) value or variable somehow. Here is where I am at.
INSERT INTO queue (SELECT NULL,singer, song1 FROM queue WHERE id = 1);
DELETE FROM queue ORDER BY id ASC LIMIT 1;
Why not just UPDATE the row to change its id by using a SET and WHERE clause?
UPDATE `queue`
SET `id` = 21 -- (current_highest_value + 1)
WHERE `id` = 1
This way you don't have to worry about adding a new row and deleting the old one.
i think all things are fine just you need to update SQL_SAFE_UPDATES = 0 for delete statement, so you can try below way
SET SQL_SAFE_UPDATES = 0;
INSERT INTO queue (SELECT NULL,singer, song1 FROM queue WHERE id = 1);
DELETE FROM queue ORDER BY id ASC LIMIT 1;

update unique indexed column in mysql

I have a unique indexed column A with integer in it. I'd like it to increment by 1, in Oracle I do: update table set A=A+1 and it worked. But in mySQL, it give me the following error:
- MySQL Database Error: Duplicate entry '2' for key 1. I have three rows in the table with value: 1, 2 and 3 individually. I know why it gives me this error. But how do I solve this problem? Thanks.
You receive this error because your UPDATE TABLE SET A = A + 1, when updating the first ROW from 1 to 2 (1+1), it will get conflict with your second ROW, because there already is a ROW with ID = 2.
You have to do it descender from the last ROW to the first, do you have to alter your query to this:
UPDATE TABLE SET ID = ID + 1 ORDER By ID DESC;
The DESC clause will make the updates from the bottom of your table, so it won't find any duplicate ID in his path...
You can do this using an ORDER BY:
update table
set A=A+1
order by A desc

Autoincrement manually a column MySQL

I have a table with columns:
[id,name,public_id]
actually the table contains
[1,john,0]
[2,sara,0]
[3,jack,0]
.....
I want to change the third column to 1050,1051,1052....
[1,john,1050]
[2,sara,1051]
[3,jack,1052]
.....
How can I make that update?
Some considerations: The public id must be over 1049 and must be consecutive. For example for 100 rows the public_id must be [1050....1149]
Thanks in advance
You can do an update like this:
UPDATE table SET public_id = id + 1049
With this, you are using the ID, and adding 1049 to it to get the result you need
Assuming your table's name is TEST_TABLE, this MySQL syntax will update PUBLIC_ID with consecutive values starting from 1500 (and in order of ID):
REPLACE INTO TEST_TABLE
SELECT TEST_TABLE.ID, TEST_TABLE.NAME, #ROWNUM := #ROWNUM + 1
FROM
TEST_TABLE,
(SELECT #rownum := 1499) R
ORDER BY ID
In plain English:
For each row, figure out its order when data is sorted by ID. Call this order "ROWNUM".
Put ROWNUM (+ starting offset) back to the table instead of the original PUBLIC_ID.
WARNING: According to MySQL documentation, REPLACE will actually delete a duplicated row before inserting it again (instead of just updating modified fields), which my be an issue in the presence of foreign keys.
(Not sure about SQLite, but I'm guessing you could employ a similar general idea.)