Update the highest auto incremented primary key in MySQL - mysql

I want to update the latest data, or the highest ID.
MAX function doesn't seem to work on update.
edit:
UPDATE table SET name='test_name' ORDER BY id DESC LIMIT 1;
seems to work. but im not sure if its really the solution.

Try this:
UPDATE table
SET field = yourvalue
WHERE Id = (SELECT MAX(Id) FROM table)

you looking for LAST_INSERT_ID()
Update table SET name='test_name'
where id = LAST_INSERT_ID()

Related

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;

MySQL syntax error when trying to delete row

I have a simple database query that I can not figure out for some reason.
DELETE * FROM Wishlist WHERE (id, uid) VALUES ("18","34i274o1y24ouy1o4");
This might be just wrong syntax in general. My skills are pretty low when it comes to databases. Any ideas? Just trying to delete a row.
Thanks in advance!
It looks like you were trying to use the INSERT syntax to do a deletion. If you want to remove records with the criteria you gave try this:
DELETE
FROM Wishlist
WHERE id = '18' AND uid = '34i274o1y24ouy1o4'
You should use IN:
DELETE FROM Wishlist WHERE (id, uid) IN ('18','34i274o1y24ouy1o4');
Or just use AND:
DELETE FROM Wishlist WHERE id = '18' AND uid = '34i274o1y24ouy1o4';
DELETE FROM Wishlist WHERE id = '18' AND uid = '34i274o1y24ouy1o4';
In addition to other answers using IN keyword,
DELETE FROM Wishlist where id='18' and uid = '34i274o1y24ouy1o4' also works.
NOTE that you do not need asterisk in DELETE operation.
If id is the primary key, where id = '18'without uid should be enough.
Also, you might want to consider making id an auto increment column with type INT. It is faster to query and you can get rid of the quotes like where id = 18.

How do i update a record in mysql table row

I am stuck with following statement. i dont know where the problem is. can someone please look into it and let me know, is it correct or not and if not than whats the correct one to update the row.
SELECT id FROM records WHERE user_id = 12119 AND field_id = 9
UPDATE records (user_id, field_id, value) VALUES (12119, 9, 'dallas')
You probably want to update value column for user with id 12119.
UPDATE records
SET value ='dallas'
WHERE user_id = 12119
AND field_id = 9;
use mysql update query like this
UPDATE table_name
SET column1=value, column2=value2
WHERE some_column=some_value

How can I update an existing record to have a new auto_increment id in MySQL?

I have a table with primary key (its name is "id") defined as auto_increment. I use NULL in INSERT statements to "fill" the id value. It works, of course. However now I need to "move" an existing record to a new primary key value (the next available, the value is not so much important, but it must be a new one, and the last one if ordered by id). How can I do it in an "elegant" way? Since the "use NULL at INSERT" does not work too much with UPDATE:
update idtest set id=NULL where id=1;
This simply makes the id of the record zero. I would expect to do the same thing as with INSERT, but it seems my idea was incorrect.
Of course I can use "INSERT ... SELECT" statement, then a DELETE on the old one, or I can use something like MAX(id) + 1 to UPDATE the id of the old record in one step, etc, but I am curious if there is a finer solution.
Also, the MAX(id) solution doesn't seem to work either by the way:
mysql> update idtest set id=max(id)+1 where id=3;
ERROR 1111 (HY000): Invalid use of group function
mysql> update idtest set id=(select max(id)+1 from idtest) where id=3;
ERROR 1093 (HY000): You can't specify target table 'idtest' for update in FROM clause
This is the way I believe:
UPDATE users SET id = (SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'test'
AND TABLE_NAME = 'users') WHERE id = 2;
select * from users;
I used by own tables substitute yours.
test is database name, users is table name and id is AUTO_INCREMENT in my case.
EDIT: My Query above works perfect but its side effects are somewhat 'dangerous', upon next insert as AUTO_INCREMENT value will collide with this recently updated record so just next single insert will fail. To avoid that case I've modified above query to a transaction:
START transaction;
UPDATE users SET id = (SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'test'
AND TABLE_NAME = 'users') WHERE id = 2;
#renew auto increment to avoid duplicate warning on next insert
INSERT IGNORE INTO users(username) values ('');
COMMIT
Hope this will help someone if not OP.
The way you are trying to update same table is wrong but you can use join on same table
update idtest t
join (select id +1 as id
from idtest order by id desc
limit 1) t1
set t.id=t1.id
where t.id=3;
or
update idtest t
join (select max(id) +1 as id
from idtest ) t1
set t.id=t1.id
where t.id=3;
You can use the REPLACE INTO clause to do the trick.
From the manual:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2.5, "INSERT Syntax".
EDIT
My mistake (in the comments) that you have to have two unique constraint to achieve this:
When you use the auto_increment value to REPLACE the record, the record will be replaced with the give ID and will not change (however the AI value will increment).
You have to exclude the AI column from the query. You can do that if you have one more UQ constraint.
Check this SQLFiddle demo: http://sqlfiddle.com/#!2/1a702e
The first query will replace all the records (but the id's value will not change).
The second one will replace it too, and the new AI value will be used. (Please note, that the second query does not contain the id column, and there is a UQ constraint on the some column).
You can notice, that the second query uses higher AI values than it is excepted: this is because the first replace incremented the AI value.
If you do not have two unique keys (one for the AI and one for another columns), the REPLACE statement will work as a normal INSERT statement!
(Ofcourse you can change one of the UNIQUE KEYs with a PRIMARY KEY)

Limiting table rows

How can I store only 10 rows in a MySQL table? The older rows should be deleted when a new row is added but only once the table has 10 rows.
Please help me
You could achieve this with an after insert trigger, delete the row where it is min date. e.g. DELETE FROM myTable WHERE myTimestamp = (SELECT MIN(myTimestamp) FROM myTable) but that could in theory delete multiple rows, depending on the granularity of your updates.
You could have an incrementing sequence, and always just delete the min of that sequence.
The question is why you'd want to do this though? It's a slightly unusual requirement.
A basic example (not validated/executed, I don't have mySQL on this particular machine) would look something like.
CREATE TRIGGER CycleOldPasswords AFTER INSERT ON UserPasswords FOR EACH ROW
set #mycount = SELECT COUNT(*) FROM UserPasswords up where up.UserId = NEW.UserId;
if myCount >= 10 THEN
DELETE FROM UserPasswords up where up.Timestamp = (SELECT min(upa Timestamp) FROM UserPasswords upa WHERE NEW.UserId = upa.UserId) AND NEW.UserId = up.UserId;
END
END;
You can retrieve the last inserted id when your first row is inserted, and store it in a variable. When 10 rows are inserted, delete the row having id < id of the first inserted record. Please try it.
first of all insert all values using your insert query
and then run this query
delete from table_name where (cond) order by id desc limit 10
must specify an id or time in one column