Update values incrementally in mysql - mysql

One field of my table's field is set to 0 for all rows. But I want to update the incremental value by step 1 in an update query.
How can I do that in mysql?

Try this:
mysql> select #i := 0;
mysql> update bar set c = (select #i := #i + 1);

SET #a = 0;
UPDATE customers SET id = #a:=#a+1;
You can go for this as well.

One line solution:
UPDATE tablename AS a, (SELECT #a := 0) AS b SET a.fieldname = #a:=#a+1

One way is to create a new table with an AUTO_INCREMENT column instead of the original column, inserting all data from the old into the new table, and then renaming the new and deleting the old.
Another way is to run your update query with a MySQL variable that generates an increasing number for each row (to emulate the ROW_NUMBER() function found in other DBMS systems).

The easiest way for me is to drop the field and re-create it with auto-increment.

Related

A column that auto increments in MYSQL

I need to create a column that auto increments from 1- (however number of rows there are). However, I need the column to reorder itself depending on the Order of my probability column. Is is possible?
I'd generally recommend against implementing that kind of ordering calculation as an explicit table field. Keeping such information up to date would create more and more overhead as the table grows. Instead, you could just ORDER BY your probability column; or if you really need the "rank" in the query result, there are a number of ways to do that, something like this should work:
SELECT #seq := seq + 1, d.*
FROM theRealData AS d, (SELECT #seq := 0) AS init
ORDER BY theRealData.probability
;
Pseudo code (i'm not looking up exact syntax as I write this, so it there might be some things I overlook) for the stored procedure I mention in the comments below (may need adjustments if I have the ordering reversed.)
CREATE PROCEDURE theProc (newID INT)
BEGIN
DECLARE newProb INT; //Not sure if it is int, but for the sake of example
DECLARE seqAt INT;
SET newProb = SELECT probability FROM theTable WHERE ID = newID;
SET seqAt = SELECT IFNULL(min(seq), 1) FROM theTable WHERE probability > newProb;
UPDATE theTable SET seq = seq + 1 WHERE seq >= seqAt;
UPDATE theTable SET seq = seqAt WHERE ID = newID;
END
If you pass all the fields inserted, instead of just the new row's id after it is inserted, then the procedure can do the insert itself and use last_insert_id() to do the rest of the work.
Modifying the primary key values can become very expensive, specially if you have related tables that point to it.
If you need to keep an order by probability, I would suggest adding an extra column with the probability_order. You can update this column after every insert or every minute, hour or day.
Alternatively, as #Uueerdo says you can just use ORDER BY when querying the table rows.

Updating all rows at once in mysql table with subquery

I have this table seller whose columns are
id mobile1
1 787811
I have another table with same columns ,I just want to update the mobile1 field from this table with the values from other table say "copy".
I have written this query
UPDATE seller
SET mobile1 = (
SELECT SUBSTRING_INDEX(mobile1, '.', 1)
FROM copy)
WHERE 1;
I am getting this obvious error when I run it.
Sub-query returns more than 1 row ,
Any way to do this??
You need condition which will be using to select only one row or you should use LIMIT:
UPDATE seller
SET mobile1 = (
SELECT SUBSTRING_INDEX(mobile1, '.', 1)
FROM copy
LIMIT 1)
WHERE id = 1;
You can constrain the number of rows returned to just one using MySQL limit.
UPDATE seller SET mobile1=(SELECT SUBSTRING_INDEX(mobile1,'.',1)
FROM copy LIMIT 1)
WHERE id=1;
If anyone who is looking for the possible answer here is what I did,I created a procedure with while loop.
DELIMITER $$
CREATE PROCEDURE update_mobile(IN counting BIGINT);
BEGIN
declare x INT default 0;
SET x = 1;
WHILE x <= counting DO
UPDATE copy SET mobile1=(SELECT SUBSTRING_INDEX(mobile1, '.', 1) as mobi FROM seller WHERE id=x LIMIT 1) WHERE id=x;
SET x=x + 1;
END WHILE;
END
AND finally I calculated the number of rows by count(id) and passed this number to my procedure
SET #var =count;
CALL update_mobile(#var);
AND it worked like a Charm...
If you want to copy all data, you can do this :
INSERT INTO `seller` (`mobile1`) SELECT SUBSTRING_INDEX(mobile1,'.',1) FROM copy

SQL - update table with sequential numbering

i have a table in my MySQL database which i have added a new column to.
I would like to update this column on every row with a number starting at 20000 going up +1 each time.
i have tried this solution:
UPDATE table1 set new_col = new_col + 1;
but it just updates all rows with the same number
The easy way:
UPDATE table1 t, (SELECT #nr:= 20000-1) tmp
SET t.new_col = (#nr:=#nr+1) ;
I have used this query to solve this:
SET #rank:=20000;
update customer
set accountnumber_new=#rank:=#rank+1

Adding incremented value to new column

i am trying to add incremented values to a new column in table.
Here is a sample structure of table
---------------------
Name - class - id
---------------------
abbc - 2 - null
efg - 4 - null
ggh - 6 - null
---------------------
i want to write a query that will generate unique id's for all records in table
Here is the query i have tried but show null
set #i=0;
update table1 set id =(#i:=#i+1);
What you have shown should work; the id column should be getting assigned values.
I tested your statement; I verified it works on my database. Here's the test case I ran:
CREATE TABLE table1 (`name` VARCHAR(4), class TINYINT, id INT);
INSERT INTO table1 (`name`,class) VALUES ('abbc',2),('efg',4),('ggh',6);
SET #i=0;
UPDATE table1 SET id =(#i:=#i+1);
SELECT * FROM table1;
Note that MySQL user variables are specific to a database session. If the SET is running in one session, and the UPDATE is running another session, that would explain the behavior you are seeing. (You didn't mention what client you ran the statements from; most clients reuse the same connection, and don't churn connections for each statement, I'm just throwing that out as a possibility.)
To insure that #i variable is actually initialized when the UPDATE statement runs, you can do the initialization in the UPDATE statement by doing something like this:
UPDATE table1 t
CROSS
JOIN (SELECT #i := 0) s
SET t.id =(#i:=#i+1);
I tested that, and that also works on my database.
try this query my friend:
set #i=0;
update table1 set id =(select #i:=#i+1);
SQL Fiddle
SET #a = 0;
UPDATE table_name SET id = #a:=#a+1;
Use AUTOINCREMENT parameter for the respective column instead. This parameter will put an unique auto incremented value in the respective column.

Insert the same fixed value into multiple rows

I've got a table with a column, lets call it table_column that is currently null for all rows of the table. I'd like to insert the value "test" into that column for all rows. Can someone give me the SQL for this?
I've tried INSERT INTO table (table_column) VALUES ("test"); but that only populates that last row. How do I do all of the rows at once?
You're looking for UPDATE not insert.
UPDATE mytable
SET table_column = 'test';
UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).
This is because in relational database terminology, what you want to do is not called "inserting", but "UPDATING" - you are updating an existing row's field from one value (NULL in your case) to "test"
UPDATE your_table SET table_column = "test"
WHERE table_column = NULL
You don't need the second line if you want to update 100% of rows.
To update the content of existing rows use the UPDATE statement:
UPDATE table_name SET table_column = 'test';
What you're actually doing is adding rows. To update the content of existing rows use the UPDATE statement:
UPDATE table SET table_column = 'test';
UPDATE `table` SET table_column='test';
The SQL you need is:
Update table set table_column = "test";
The SQL you posted creates a new row rather than updating existing rows.
To create a new empty column and fill it with the same value (here 100) for every row (in Toad for Oracle):
ALTER TABLE my_table ADD new_column INT;
UPDATE my_table SET new_column = 100;