I have a table T with some data having 3 rows. Now I added a new column c.
Now I want to insert values into c for existing rows.
I do it like this :
insert into T (c) values(1),(2),(3);
But instead of updating existing data, it inserted new rows.
How can I update existing data ?
I don't want to specify where clause. I just want to add values serial wise as insert does.
You would use the UPDATE statement to assign values to columns of existing rows.
UPDATE t
SET t.c = 1
WHERE t.a = 1 ;
To assign unique, sequential integer to each existing row, you'd need to make use of the primary key, or a unique identifier from each row. In this example, we assume that the id column is unique:
UPDATE t
JOIN ( SELECT r.id
, #i := #i + 1 AS i
FROM t r
JOIN (SELECT #i := 0) n
ORDER BY r.id
) s
ON s.id = t.id
SET t.c = s.i
Actually, you can also do this:
UPDATE t
JOIN ( SELECT #i := 0 ) n
SET t.c = #i := #i + 1
ORDER BY t.id
It sounds like you might want to investigate the AUTO_INCREMENT attribute.
You can use below query
UPDATE Table
SET Col1='1', Col2='2'
and so on...
Also, you can use where condition, if you want to update data with some specified conditions, as below:
---it's just an example of query used in my database---
UPDATE City_Employee
SET City='Banglore' where (City='Delhi')
Best of luck !
Related
I am new to SQL, I have a requirement where I have to increment the value in a specific column by 1 and update that value in the same column based on the id.
Here is what I want,
UPDATE books SET version_num =
(SELECT (version_num + 1) FROM books WHERE book_recid IN
('72b72282-707b-4dd4-ab08-f5a085e92a2b', '73255df2-413e-4aad-892d-edc08ffa3405'))
WHERE book_recid IN
('72b72282-707b-4dd4-ab08-f5a085e92a2b', '73255df2-413e-4aad-892d-edc08ffa3405');
I know the above query won't work. I want a query to update the values in the database like above.
It is simple to add 1 to a column.
You have just over complicated your query.
UPDATE books SET version_num = version_num +1
WHERE book_recid IN ('72b72282-707b-4dd4-ab08-f5a085e92a2b',
'73255df2-413e-4aad-892d-edc08ffa3405');
You can do a from in the update query
UPDATE A SET col1 = something
FROM B
INNER JOIN C on B.col4 = C.col5
WHERE A.col2 = B.col3
In your case, it could be something like the following
UPDATE books b SET version_num = tcp.version_num + 1
FROM tag_config_params tcp
WHERE tcp.book_recid = b.book_recid
AND tcp.book_recid IN ('72b72282-707b-4dd4-ab08-f5a085e92a2b', '73255df2-413e-4aad-892d-edc08ffa3405');
I'm assuming that book_recid is a foreign key relationship here.
Do like this
UPDATE books
SET version_num = tb1.vers
from (
SELECT (version_num + 1) as vers FROM tag_config_params
WHERE book_recid IN
('72b72282-707b-4dd4-ab08-f5a085e92a2b', '73255df2- 413e-4aad-892d-edc08ffa3405')
) tb1
WHERE book_recid IN
('72b72282-707b-4dd4-ab08-f5a085e92a2b', '73255df2-413e-4aad-892d-edc08ffa3405');
I have: something like
UPDATE table
SET field = (SELECT field FROM another_table WHERE id = #id);
Problem: SELECT field FROM another_table WHERE id = #id subquery can return one field or EMPTY SET.
Question: How to handle situation when subquery returns empty set?
Updated:
UPDATE table t
SET field = IF((SELECT field FROM another_table WHERE id = #id) IS NOT NULL, -- select field
(SELECT field FROM another_table WHERE id = #id), -- Problem #1: select field AGAIN!
(SELECT field FROM table WHERE id = t.id) -- Problem #2: try to not change value, so select the current field value!!
);
If function can be useful:
UPDATE table
SET field = if((SELECT field FROM another_table WHERE id = #id) IS NULL,true,false);
You can add the conditional:
WHERE (SELECT COUNT(*) FROM another_table WHERE id = #id) > 0
This will make sure that at least one row exists in another_table with the id. See my SQL Fiddle as an example.
Note: this may not be the most efficient because it does a count on another_table, and if it is greater than 1 it will do another SELECT (two sub-queries). Instead, you can do an INNER JOIN:
UPDATE table
INNER JOIN another_table ON table.id=another_table.id
SET table.field = another_table.field
WHERE another_table.id = #id;
See this SQL Fiddle. The reason why I saved this as a second option, is not all SQL languages can UPDATE with joins (MySQL can). Also, you need some way to relate the tables..in this case I said that the table.id we are updating is equal to another_table.id we are taking the data from.
NOTE The UPDATE statement will modify EVERY row in table and assign the same value to every row; that seems a little unusual.
To answer your question:
If you want to handle the "empty set" by not updating any rows in table, then one way to do this is with a JOIN to an inline view:
UPDATE table t
CROSS
JOIN (SELECT a.field
FROM another_table a
WHERE a.id = #id
LIMIT 1
) s
SET t.field = s.field
Note that if the inline view query (aliased as s) return an "empty set", then no rows in table will be updated, because the JOIN operation will also return an "empty set", meaning there are zero rows to be updated.
I have a table in a database that I made using an "auto-increment" primary key. Only now I went back and deleted some of the rows.
The problem is, that I would like the table to be 1->X without any holes in the numbered column (in other words it should be 1,2,3,4,5,6,7,8,9,10 - but now it's more like 1,2,3,7,8,10.
Is there a way I can re-set the values of this column to be incremented correctly via mysql???
Use a user defined variable, which is incremented during every row, and an order by to prevent duplicate id's *during the update process:
SET #x := 0;
UPDATE mytable SET
id = (#x := #x + 1)
ORDER BY id;
See an SQLFiddle
You can put it in select process:
SELECT #s:=#s+1 AS fake_id, tbl.*
FROM tbl, (SELECT #s:= 0) AS tmp_tbl
UPDATE yourtable t
JOIN (SELECT id oldid, #id := #id + 1 newid
FROM yourtable
JOIN (SELECT #id := 0) var
ORDER BY oldid) newid
ON t.id = oldid
SET t.id = newid
The ORDER BY and ON conditions are needed to prevent it from temporarily creating duplicate keys, which causes an error.
DEMO
I want to loop through some records and update them with an ad hoc query in MySql. I have a name field, so I just want to loop though all of them and append a counter to each name, so it will be name1, name2, name3. Most examples I see use stored procs, but I don't need a stored proc.
As a stepping stone on your way to developing an UPDATE statement, first generate a SELECT statement that generates the new name values to your liking. For example:
SELECT t.id
, t.name
, CONCAT(t.name,s.seq) AS new_name
FROM ( SELECT #i := #i + 1 AS seq
, m.id
FROM mytable m
JOIN (SELECT #i := 0) i
ORDER BY m.id
) s
JOIN mytable t
ON t.id = s.id
ORDER BY t.id
To unpack that a bit... the #i is a MySQL user variable. We use an inline view (aliased as i) to initialize #i to a value of 0. This inline view is joined to the table to be updated, and each row gets assigned an ascending integer value (aliased as seq) 1,2,3...
We also retrieve a primary (or unique) key value, so that we can match each of the rows from the inline view (one-to-one) to the table to be updated.
It's important that you understand how that statement is working, before you attempt writing an UPDATE statement following the same pattern.
We can now use that SELECT statement as an inline view in an UPDATE statement, for example:
UPDATE ( SELECT t.id
, t.name
, CONCAT(t.name,s.seq) AS new_name
FROM ( SELECT #i := #i + 1 AS seq
, m.id
FROM mytable m
JOIN (SELECT #i := 0) i
ORDER BY m.id
) s
JOIN mytable t
ON t.id = s.id
ORDER BY t.id
) r
JOIN mytable u
ON u.id = r.id
SET u.name = r.new_name
SQL Fiddle demonstration here:
http://sqlfiddle.com/#!2/a8796/1
I had to extrapolate, and provide a table name (mytable) and a column name for a primary key column (id).
In the SQL Fiddle, there's a second table, named prodtable which is identical to mytable. SQL Fiddle only allows SELECT in the query pane, so in order to demonstrate BOTH the SELECT and the UPDATE, I needed two identical tables.
CAVEAT: be VERY careful in using MySQL user variables. I typically use them only in SELECT statements, where the behavior is very consistent, with careful coding. With DML statements, it gets more dicey. The behavior may not be as consistent in DML, the "trick" is to use a SELECT statement as an inline view. MySQL (v5.1 and v5.5) will process the query for the inline view and materialize the resultset as a temporary MyISAM table.
I have successfully used this technique to assign values in an UPDATE statement. But (IMPORTANT NOTE) the MySQL documentation does NOT specify that this usage or MySQL user variables is supported, or guaranteed, or that this behavior will not change in a future release.
Have the names stored in a table. Do a join against the names and update in the second table you want to.
Thanks
I have a table which has a field sort_id. In this field there are numbers from 1 to n, that define the order of the data sets.
Now I want to delete some elements and afterwards I want to reorder the table. Therefore I need a query that "finds" the gaps and changes the sort_id field according to the modifications.
Sure, I could do something like this:
SELECT sort_id FROM table WHERE id = 5
Then save the sort_id and afterwards:
DELETE FROM table WHERE id = 5
UPDATE table SET sort_id = sort_id - 1 WHERE sort_id > {id from above}
But I'd like to do the reordering process in one step.
Mladen and Arvo have good ideas, but unfortunately in MySQL you can't SELECT and UPDATE the same table in the same statement (even in a subquery). This is a known limitation of MySQL.
Here's a solution that uses MySQL user variables:
SET #i := 0;
UPDATE mytable
SET sort_id = (#i := #i + 1)
ORDER BY sort_id;
For what it's worth, I wouldn't bother doing this anyway. If your sort_id is used only for sorting and not as a kind of "row number," then the rows are still in sorted order after you delete the row where id=6. The values don't necessarily have to be consecutive for sorting.
for sql server 2005:
this is how you get the new sequence:
SELECT row_number() over(order by sort_id) as RN
FROM table
updating the table means you should join that select to your update:
update t1
set sort_id = t2.RN
FROM table t1
join (SELECT row_number() over(order by sort_id) as RN FROM table) t2
on t1.UniqueId = t2.UniqueId
I don't know MySQL syntax variations and cannot test query live, but something like next should give you at least an idea:
update table t1
set sort_id = (select count * from table t2 where t2.sort_id <= t1.sort_id)