Updating a column with one query in MYSQL - mysql

To update a column in the database i use the following query
UPDATE table_name
SET column1 = value1
WHERE condition;
The problem with this query is that i end up updating one column at a time
i want to update a column by setting a condition and updating a whole column that meets the condition set
An example of what i have tried:
UPDATE adggtnz1.lng01_rpt_animrec
SET origin = 'New'
WHERE origin = NULL;
and the result of this query is
0 row(s) affected Rows matched: 0 Changed: 0 Warnings: 0 0
picture of sample data:

Why does NULL = NULL evaluate to false in SQL server
NO
WHERE origin = NULL;
YES
WHERE origin is NULL;
create table `lng01_rpt_animrec`
(
`origin` varchar(10)
)
insert into `lng01_rpt_animrec` (`origin`) values
('EADD'),
(null),
('EADD'),
(null),
(null),
('EADD'),
(null),
('EADD'),
('EADD');
UPDATE
lng01_rpt_animrec
SET
origin = 'New'
WHERE
origin is null;
select * from `lng01_rpt_animrec`
| origin |
| :----- |
| EADD |
| New |
| EADD |
| New |
| New |
| EADD |
| New |
| EADD |
| EADD |
db<>fiddle here

use case when clause for conditional update below query be an example for that
UPDATE table_name
SET column1 = case when 1<2 then value1 else value2 end
WHERE condition;

Related

Target table cannot be same one for update clause in mysql

I have a table name named 'employee'. Table creation code given below:
create table employee(name varchar(50),ph_no varchar(10),e_id varchar(5),pay_scale varchar(5),year varchar(4));
The table content is like below:
insert into employee(name,ph_no,pay_scale,year) values('AMIT','123456','PL-10','2019');
insert into employee(name,ph_no,pay_scale,year) values('AMIT','123456','PL-10','2020');
insert into employee(name,ph_no,pay_scale,year) values('AMIT','123456','PL-11','2021');
insert into employee(name,ph_no,pay_scale,year) values('AMIT','123456','PL-11','2022');
+------+--------+------+-----------+------+
| name | ph_no | e_id | pay_scale | year |
+------+--------+------+-----------+------+
| AMIT | 123456 | NULL | PL-10 | 2019 |
| AMIT | 123456 | NULL | PL-10 | 2020 |
| AMIT | 123456 | NULL | PL-11 | 2021 |
| AMIT | 123456 | NULL | PL-11 | 2022 |
+------+--------+------+-----------+------+
Now I want to update 'e_id', first it will check whether the same e_id is in the table anywhere or not, if it is not in the table then only it will update the rows with given e_id, else it will not going to update.
So, my upgradation query is below:
update employee
set e_id='0132'
where concat_ws(',',name,ph_no,pay_scale)=concat_ws(',','AMIT','123456','PL-10')
and not exists (select e_id
from employee
group by e_id
having count(*)>=1);
But it is giving the following error:
ERROR 1093 (HY000): You can't specify target table 'employee' for update in FROM clause
I have tried the below query:
update employee set e_id='0132' where
concat_ws(',',name,ph_no,pay_scale)=concat_ws(',','AMIT','123456','PL-10') and
e_id not in
(select e_id from
(select e_id from employee group by e_id having count(*)>=1) as t);
But this also cannot update the table and showing below result:
Query OK, 0 rows affected (0.01 sec)
Rows matched: 0 Changed: 0 Warnings: 0
also tried the below code:
update employee set
employee.e_id='0132' where
employee.e_id not in (select * from
(select f.e_id from
employee f inner join employee b on
b.name=f.name and b.ph_no=f.ph_no and b.pay_scale=f.pay_scale) as tmp)
and employee.name='AMIT' and employee.ph_no='123456' and employee.pay_scale='PL-10';
but this also cannot update the table and gives below result:
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
Please help. Thank you in advance.
NULL doesn't play the way some people expect with NOT IN: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=24c176ff4d4e2c52309aaca14cc121c5 So, just put WHERE e_id IS NOT NULL in the sub-query. Also, HAVING COUNT(*) >= 1 can be removed as it's always going to return a value of 1 or more...
update
employee
set
e_id='0132'
where
name = 'AMIT'
and ph_no = '123456'
and pay_scale = 'PL-10'
and e_id not in (select e_id from
(select distinct e_id
from employee
where e_id IS NOT NULL
)
as t
);
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=2a0b036a7d1db9138e3ab29af3d346f8

MySQL 5.7 JSON column update

I am using MySQL 5.7. I have a table with a JSON column.
MySQL [test_db]> select * from mytable;
+----+-------+---------------------+
| id | name | hobby |
+----+-------+---------------------+
| 1 | Rahul | {"Game": "Cricket"} |
| 2 | Sam | null |
+----+-------+---------------------+
Here, for row id = 2, I want to insert a data. I did -
update mytable set hobby = JSON_SET(hobby, '$.Game', 'soccer') where id = 2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
It seems like data inserted properly, But when I checked
MySQL [test_db]> select * from mytable;
+----+-------+---------------------+
| id | name | hobby |
+----+-------+---------------------+
| 1 | Rahul | {"Game": "Cricket"} |
| 2 | Sam | null |
+----+-------+---------------------+
data is not inserted, Can anybody give some hint, what I am missing here.
Thanks.
Hobby is NULL, and you can't set a property on NULL, so use an IF statement instead, to convert null to an empty object first (Or initialize hobby as an empty object instead of NULL):
UPDATE mytable
SET hobby = JSON_SET(IF(hobby IS NULL, '{}', hobby), '$.Game', 'soccer')
WHERE id = 2;
Alternatitvely, use COALESCE:
UPDATE mytable
SET hobby = JSON_SET(COALESCE(hobby, '{}'), '$.Game', 'soccer')
WHERE id = 2;
See dbfiddle here.

Updating on the same MySQL table the row when the values of columns are equals

I need updating on the same MySQL table the row when the values of columns xID and ID are equals.
This is one example:
mysql> SELECT
Euro,
ALMACEN,
Imagen,
xID,
ID
FROM
`tbl_g`
WHERE
xID IN (2025)
OR ID IN (2025);
+--------+----------+--------+------+------+
| Euro | ALMACEN | Imagen | xID | ID |
+--------+----------+--------+------+------+
| 7742,8 | ARGUALAS | NULL | NULL | 2025 |
| NULL | EMPALME | | 2025 | 4441 |
+--------+----------+--------+------+------+
2 rows in set
I have tried this SQL Update query without success, because the row with xID number 2025 not update with values of row with ID 2025 :
mysql> UPDATE `tbl_g` kkk,
`tbl_g` jjj
SET kkk.Euro = jjj.Euro
WHERE
kkk.ID = jjj.xID
AND kkk.xID IS NOT NULL;
Query OK, 0 rows affected
Rows matched: 0 Changed: 0 Warnings: 0
How to do resolve this?
Can you help me?
Thank you in advance for any help, really appreciated.
Update the table using a JOIN (self Join) and use a WHERE clause to check the column Euro is null.
Query
update `tbl_g` as `t1`
join `tbl_g` as `t2`
on `t1`.`xID` = `t2`.`ID`
set `t1`.`Euro` = `t2`.`Euro`
where `t1`.`Euro` is null;
Note: There is a chance for multiple rows which satisfy the condition.
You need a self join for example
drop table if exists t;
create table t(Euro decimal(10,2) , ALMACEN varchar(20), Imagen int, xID int, ID int);
insert into t values
( 7742.80 , 'ARGUALAS' , NULL , NULL , 2025),
( NULL , 'EMPALME' , null , 2025 , 4441);
update t t1 join t t2 on t2.xid = t1.id
set t2.euro = t1.euro;
select * from t;
MariaDB [sandbox]> select * from t;
+---------+----------+--------+------+------+
| Euro | ALMACEN | Imagen | xID | ID |
+---------+----------+--------+------+------+
| 7742.80 | ARGUALAS | NULL | NULL | 2025 |
| 7742.80 | EMPALME | NULL | 2025 | 4441 |
+---------+----------+--------+------+------+
2 rows in set (0.00 sec)

Updating value, of a Column with PRIMARY KEY constraint

I have a MySQL table with the following schema
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(7) | NO | UNI | NULL | auto_increment |
| title | varchar(20) | NO | PRI | NULL | |
+-------+-------------+------+-----+---------+----------------+
And here is the content in it.
+----+-------+
| id | title |
+----+-------+
| 1 | a |
| 2 | b |
+----+-------+
Question: I want to interchange the values in a single query so that the table now becomes
+----+-------+
| id | title |
+----+-------+
| 1 | b |
| 2 | a |
+----+-------+
I tried: UPDATE myTable SET title = CASE id WHEN 1 THEN "b" WHEN 2 THEN "a" END;
but it gives me an error ERROR 1062 (23000): Duplicate entry 'b' for key 'PRIMARY'
What should I do?
A solution found here in one of the links seems the only way as of now but I am still looking for a better solution
START TRANSACTION;
UPDATE prime SET title = CASE id WHEN 1 THEN "$b" WHEN 2 THEN "$a" END;
UPDATE prime SET title = CASE id WHEN 1 THEN SUBSTRING(title,2) WHEN 2 THEN SUBSTRING(title,2) END;
COMMIT;
START TRANSACTION ;
UPDATE prime SET title = 'zzzzz$$$$$xxxxx!##$%' WHERE id = 1 ;
UPDATE prime SET title = 'a' WHERE id = 2 ;
UPDATE prime SET title = 'b' WHERE id = 1 ;
COMMIT ;
Comment, not related to the unique issue:
Use WHERE in your update statements, unless you want to update all the rows of the table. Your statement:
UPDATE myTable SET title = CASE id WHEN 1 THEN 'b' WHEN 2 THEN 'a' END;
(if it worked) it would also try to update all other rows (with id >= 3) with a NULL value because CASE has an implicit ELSE NULL part. Of course it would fail as the title is the primary key but in other cases, you would have undesirable effects.
with PIMARY key help to use ORDER BY title
UPDATE myTable SET title = CASE id WHEN 1 THEN "a" WHEN 2 THEN "b" ElSE title END WHERE id in (1,2) ORDER BY id DESC;
if not work change direction to ASC or ORDER BY title. And don't fogot ELSE. it doesn't work wiout it.
I use it with id, like that:
UPDATE `table1` SET `id` = CASE `id` WHEN 1 THEN 2 WHEN 2 THEN 3 WHEN 0 THEN 1 ELSE `id` END WHERE `id` IN ( 1, 2, 0 ) ORDER BY `id` DESC
all works fine,
but if update 0=>3,3=>2,2=>1 - 0 should update separatly.

How do I combine two UPDATE statements in one MySQL query?

Greetings,
How would one go about performing two UPDATE statements in one query, for example:
UPDATE albums SET isFeatured = '0' WHERE isFeatured = '1'
combined with
UPDATE albums SET isFeatured = '1' WHERE id = '$id'
Basically, when a new album is featured, the previously featured album is switched back to normal and the newly featured one is set to active.
Thanks!
Try this:
UPDATE albums SET isFeatured = IF(id!='$id', '0','1')
When you have to do this sort of thing it is an indicator that your data model is wrong and could do with some fixing.
So, I'd recommend to add a seperate table featured_albums (FK: int id_album) and use that to determine if the album is featured.
Your update becomes
DELETE FROM featured_album; INSERT INTO featured_album SET id_album = $id;
When selecting join the tables
SELECT album.id,
album.name,
( id_album IS NOT NULL ) AS isfeatured
FROM album
LEFT JOIN featured_album ON id_album = album.id
As requested to expand on the above basically I'm suggesting adding a table that will contain a row indicating the currently selected album. This is a 1 to 1 relationship, i.e. one record in the album table has one related record in the feature_albums table. See Types of Relationship.
You remove the isFeatured field from the album table and add a new table.
CREATE TABLE `featured_album` (
`id_album` INTEGER NOT NULL,
FOREIGN KEY (id_album) REFERENCES `album` (`id`)
);
The DELETE FROM .. INSERT INTO line sets the featured album by creating an entry in the table.
The SELECT statement with the LEFT JOIN will pull in the records from the album table and join those that match from the featured_album table, in our case only one record will match so as there is one field in the featured_album table it will return NULL for all records except the featured album.
So if we did
SELECT album.id, album.name, featured_album.id_album as isFeatured0
FROM album
LEFT JOIN featured_album ON id_album = album.id
We'd get something like the following:
+----+----------------+------------+
| id | name | isFeatured |
+----+----------------+------------+
| 1 | Rumours | NULL |
| 2 | Snowblind | NULL |
| 3 | Telegraph road | 3 |
+----+----------------+------------+
i.e. a NULL for isFeatured or an ID.
By adding the ( id_album IS NOT NULL ) AS isfeatured and using the first query we get
+----+----------------+------------+
| id | name | isfeatured |
+----+----------------+------------+
| 1 | Rumours | 0 |
| 2 | Snowblind | 0 |
| 3 | Telegraph road | 1 |
+----+----------------+------------+
i.e. 0/1 for isfeatured which makes things more readable, although if you're processing the results in PHP it won't make a difference to your code.
You can use CASE WHEN statement and remember to set original value where necessary (ELSE clause below) and order CASE conditions as required (in statement below isFeatured will be 0 if row having requested id also has isFeatured = 1, to change it swap WHEN clauses).
UPDATE albums
SET isFeatured = CASE
WHEN isFeatured = '1' THEN '0'
WHEN id = '$id' THEN '1'
ELSE isFeatured
END
You just can't. You can only select one group of records that should be updated and can then only perform one operation on all of them. It's not possible to do
UPDATE x SET col1 = 1 WHERE col1 = 0 AND col1 = 0 WHERE col1 = 1;
Be careful when using functions to work around this, as they need to be evaluated for every row and this can become really expensive.
MySQL is unable to use the index when it is inside an if function:
You need an index on the function which is not possible in MySQL.
see also: How does one create an index on the date part of DATETIME field in MySql
I am using the employee test database http://dev.mysql.com/doc/employee/en/employee.html
mysql> describe employees;
+------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+-------+
| emp_no | int(11) | NO | PRI | NULL | |
| birth_date | date | NO | | NULL | |
| first_name | varchar(14) | NO | | NULL | |
| last_name | varchar(16) | NO | | NULL | |
| gender | enum('M','F') | NO | | NULL | |
| hire_date | date | NO | | NULL | |
+------------+---------------+------+-----+---------+-------+
6 rows in set (0.01 sec)
mysql> select count(*) from employees;
+----------+
| count(*) |
+----------+
| 300024 |
+----------+
1 row in set (0.37 sec)
Set all genders to male so it mimics the question.
mysql> update employees set gender = 'M';
Query OK, 1 row affected (9.11 sec)
Rows matched: 300024 Changed: 1 Warnings: 0
mysql> select emp_no, gender from employees order by emp_no limit 2;
+--------+--------+
| emp_no | gender |
+--------+--------+
| 10001 | M |
| 10002 | M |
+--------+--------+
2 rows in set (0.00 sec)
Set one employee to female.
(Notice it uses the index and is almost instant.)
mysql> update employees set gender = 'F' where emp_no = 10001;
Query OK, 1 row affected (0.14 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Now we use the suggested answer. (Notice it does not use the index and touches every row.)
mysql> update employees set gender = if(emp_no=10002, 'F', 'M');
Query OK, 2 rows affected (10.67 sec)
Rows matched: 300024 Changed: 2 Warnings: 0
Will an index help?
> mysql> create index employees_gender_idx on employees(gender);
Query OK, 300024 rows affected (21.61 sec)
Records: 300024 Duplicates: 0 Warnings: 0
> mysql> update employees set gender = if(emp_no=10001, 'F', 'M');
Query OK, 2 rows affected (9.02 sec)
Rows matched: 300024 Changed: 2 Warnings: 0
Nope.
It was also said that MySQL is only going to look at the rows that need to be changed.
mysql> update employees set gender = 'M';
Query OK, 1 row affected (8.78 sec)
Rows matched: 300024 Changed: 1 Warnings: 0
Guess not. What if use a WHERE clause?
mysql> update employees set gender = 'M' where gender ='F';
Query OK, 0 rows affected (0.03 sec)
Rows matched: 0 Changed: 0 Warnings: 0
Gee that fast, now it used the index.
Mysql has no idea what the IF function will return and must do a full table scan. Notice that WHERE really does mean where and SET really does mean set. You can't expect the DB to just arrange all your clauses to get good performance.
The correct solution is to issue two updates (which if use indexes will be almost instant.)
Notice, it was said elsewhere that MySQL will magically know only update the rows it needs to change.
Adding an alternate method to the excellent answer provided by
#too where instead of CASE IF statement is used -
UPDATE album
-> SET isFeatured = IF (
-> isFeatured = '1', '0', IF (
-> id = '$id', '1', isFeatured
-> ));
I don't think you can, or at least not in a neat or practical way.
If you're wanting to do one call from php/whatever then you can seperate them with semicolons thus:
UPDATE albums SET isFeatured = '0' WHERE isFeatured = '1';UPDATE albums SET isFeatured = '1' WHERE id = '$id';