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
Related
If I have a table with only one column, how could I delete a particular row from it? I know the most logical answer would be to have another column in the table with a number that automatically increments, but in a table with only one column, how would I go about doing this? Is there something I can add in the WHERE clause to say row = 3 or something similar?
Please try the following...
DELETE FROM tblTable
WHERE fieldName = targetValue;
If you have any questions or comments, then please feel free to post a Comment accordingly.
You can do:
delete t from t
where col = #value;
However, that will delete all rows with the value. If the value is unique, you should declare the column to be either unique or a primary key.
I should add that you can delete just one row with the value by adding limit 1:
delete t from t
where col = #value
limit 1;
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)
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.
I don't think this is possible as I couldn't find anything but I thought I would check on here in case I am not searching for the correct thing.
I have a settings table in my database which has two columns. The first column is the setting name and the second column is the value.
I need to update all of these at the same time. I wanted to see if there was a way to update these values at the same time one query like the following
UPDATE table SET col1='setting name' WHERE col2='1 value' AND SET col1='another name' WHERE col2='another value';
I know the above isn't a correct SQL format but this is the sort of thing that I would like to do so was wondering if there was another way that this can be done instead of having to perform separate SQL queries for each setting I want to update.
Thanks for your help.
You can use INSERT INTO .. ON DUPLICATE KEY UPDATE to update multiple rows with different values.
You do need a unique index (like a primary key) to make the "duplicate key"-part work
Example:
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE b = VALUES(b), c = VALUES(c);
-- VALUES(x) points back to the value you gave for field x
-- so for b it is 2 and 5, for c it is 3 and 6 for rows 1 and 4 respectively (if you assume that a is your unique key field)
If you have a specific case I can give you the exact query.
UPDATE table
SET col2 =
CASE col1
WHEN 'setting1'
THEN 'value'
ELSE col2
END
, SET col1 = ...
...
I decided to use multiple queries all in one go. so the code would go like
UPDATE table SET col2='value1' WHERE col1='setting1';
UPDATE table SET col2='value2' WHERE col1='setting1';
etc
etc
I've just done a test where I insert 1500 records into the database. Do it without starting a DB transaction and it took 35 seconds, blanked the database and did it again but starting a transaction first, then once the 1500th record inserted finish the transaction and the time it took was 1 second, so definetely seems like doing it in a db transaction is the way to go.
You need to run separate SQL queries and make use of Transactions if you want to run as atomic.
UPDATE table SET col1=if(col2='1 value','setting name','another name') WHERE col2='1 value' OR col2='another value'
#Frits Van Campen,
The insert into .. on duplicate works for me.
I am doing this for years when I want to update more than thousand records from an excel import.
Only problem with this trick is, when there is no record to update, instead of ignoring, this method inserts a record and on some instances it is a problem. Then I need to insert another field, then after import I have to delete all the records that has been inserted instead of update.
I'd like to know how to update several records at once where a certain column type is selected.
I have found how to select records. I have found how to update records. But i don't know how to do it both together for it to work.
Selecting:
SELECT * FROM users WHERE 'type'='new'
Updating:
update table
set column = 937
So basically i want to change the info in the 'column' to 937 in the 'table' if another column 'type' is 'new'.
Thanks,
You can do this by simply adding a WHERE clause to your UPDATE statement:
UPDATE `users`
SET `myColumn` = 937
WHERE `type` = 'new'
Of course, change myColumn to match your column name
You can do this with a subquery :
update users
set column = 937
where id in (select id from users where type='new')
Just change the columns name if I got them wrong.
After researching for a while I found another solution to this problem. When referencing the same table or field name in a query, the name space in MySQL ends up with duplicates and fails. To overcome this use the "AS" syntax to name the duplicate items. Also, update queries often require a key field to be used as the parameter for the where clause, this is often your auto-incremented ID field. This example provides a solution for both of these problems.
UPDATE tbl
SET field=newValue
WHERE tbl.key IN
(SELECT idNew FROM
(Select tbl.key AS idNew
FROM tbl
WHERE field=editValue) AS tblNew);
tbl - Table name being updated
field - Target field for update
newValue - Value to replace items in the target field
tbl.key - Field name for the key in your table
idNew - New name for key in your table, to replace the name and prevent failure from duplicating names in query. could be any alphanumeric string. 'id' or 'id_new' or 'id_n'
editValue - The value to change
tblNew - New name for query, to prevent duplicate table names in the query. Could be any alphanumeric string 'tbl_n' or 'tbl_new' or 'tbl_test'
This query gets the key values for all the records that match records that have values you want edited, then changes the names of the key and tbl so they can be processed by MySQL, lastly the update query runs and changes the values based on the keys provided in the sub-query.
Hopefully this saves someone else a few hours!