UPDATE query for multiple rows of same column - mysql

I have a database table and What I required to do is that,
I need to update the column with the column name 'Co15' of every rows according to the following conditions
Co15 = SAMPLE if Co13 = 'c1' AND Col2 = 'b4'
Co15 = LIST if Co13 = 'c6'
Currently I am running each update query separately as follows
UPDATE tblname SET Co15 = 'SAMPLE' WHERE Co13 = 'c1' AND Col2 = 'b4';
UPDATE tblname SET Co15 = 'LIST' WHERE Co13 = 'c6';
But wanted to know if there is any way where I could run only one update query all at once.
Thanks

Try this
UPDATE tblname SET Co15=
CASE
WHEN Co13 = 'c1' AND Col2='b4' THEN 'SAMPLE'
WHEN Co13 = 'c6' THEN 'LIST'
END

exactly getting the output to as following as:
UPDATE tblname
SET col5= CASE
WHEN col3 = 'c1' AND col2 = 'b4' THEN 'SAMPL'
WHEN col3 = 'c6' THEN 'LIST'
END
example: sqlfiddle to click here

Related

Replace value in SQL Table

I like to replace a 'NULL' value in FG_NFG_Selektion column but only in those row where Plant='935S'
Tried:
UPDATE [Table] SET [FG_NFG_Selektion] = REPLACE([FG_NFG_Selektion], 'NULL', 'FG') WHERE [Plant] = '935S'
Message back: 10000 rows affected but still the same 'NULL' is there in the table.
Try with following query
UPDATE [Table] SET `FG_NFG_Selektion` = 'FG' WHERE `Plant` = '935S' AND `FG_NFG_Selektion` IS NULL;

Select Case / Update one field based on another

Basically, I am trying to cleanse a database and have all file paths point to sample documents. I am reading from one column (extension), and then updating another column (filename) and making a change based on the extension. I also want a catch all. For example, if extension is DOC, then make the path "sample.doc"; if the extension is PDF, then make the path "sample.pdf", if unknown, then make the path "sample.txt".
I have this code working, but think it would be better served with a select/case loop:
select * from dbo.tsrecelec
UPDATE dbo.TSRECELEC
SET dbo.tsrecelec.reSID = '00+SampleWord.doc'
WHERE dbo.tsrecelec.reExtension = 'DOC'
UPDATE dbo.TSRECELEC
SET dbo.tsrecelec.reSID = '00+SampleWord.docx'
WHERE dbo.tsrecelec.reExtension = 'DOCX'
UPDATE dbo.TSRECELEC
SET dbo.tsrecelec.reSID = '00+SampleADOBE.pdf'
WHERE dbo.tsrecelec.reExtension = 'PDF'
In my NONE SQL brain, I was thinking something like this might work?
SELECT reSID, reExtension,
CASE
WHEN reExtension = 'DOC' THEN SET reSID = '00+SampleWord.doc'
WHEN dbo.tsrecelec.reExtension = 'DOCX' THEN SET dbo.tsrecelec.reSID = '00+SampleWord.docx'
ELSE dbo.tsrecelec.reSID = '00+SampleFile.txt'
END
FROM dbo.tsrecelec;
Any and all help is appreciated!
Three updates is fine, but you can phrase this as:
UPDATE dbo.TSRECELEC
SET reSID = (CASE WHEN reExtension = 'DOC'
THEN '00+SampleWord.doc'
WHEN reExtension = 'DOCX'
THEN '00+SampleWord.docx'
WHEN reExtension = 'PDF'
THEN '00+SampleADOBE.pdf'
END)
WHERE reExtension IN ('DOC', 'DOCX, 'PDF');
Try to use CASE...WHEN...THEN.... It's more performant if you are getting more extensions in the future:
UPDATE yourtable
SET col1 = (CASE WHEN col2 = 'extension you want'
THEN 'nameofyourfile.extension'
WHEN ...
THEN ...
END)
WHERE col2 IN ('extension1', 'extension2', 'extension3','...');

Update Statement in oracle PL/SQL updating the values to null

UPDATE FD DCS
SET DCS.F_DISTANCE =
(SELECT FD.F_DISTANCE
FROM TMP FD
WHERE FD.DATE_SID = DCS.DATE_SID
AND FD.SID = DCS.SID
AND FD.DA_SID = DCS.DASID
AND FD.AA_SID = DCS.AA
AND FD.F_DISTANCE IS NOT NULL
)
WHERE DCS.BATCH_ID=BATCH_ID;
The inner SQl query is updating all the satisfied values to the FD table's column F_distance but where subquery didn't match it is updating the FD table F_Distance values to null. I don't want to update the values to null.
please suggest what to do.
In ORACLE you can use NVL
UPDATE FD DCS
SET DCS.F_DISTANCE = NVL(
(SELECT FD.F_DISTANCE
FROM TMP FD
WHERE FD.DATE_SID = DCS.DATE_SID
AND FD.SID = DCS.SID
AND FD.DA_SID = DCS.DASID
AND FD.AA_SID = DCS.AA
AND FD.F_DISTANCE IS NOT NULL
), DCS.F_DISTANCE)
WHERE DCS.BATCH_ID=BATCH_ID;
In this case if the result is null the NVL return 0 (you cna change with the value you prefer)

UPDATE multiple rows with different values in one query in MySQL

I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand.
For instance, three updates into 1 query:
UPDATE table_users
SET cod_user = '622057'
, date = '12082014'
WHERE user_rol = 'student'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '2913659'
, date = '12082014'
WHERE user_rol = 'assistant'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '6160230'
, date = '12082014'
WHERE user_rol = 'admin'
AND cod_office = '17389551';
I read an example, but I really don't understand how to make the query. i.e:
UPDATE table_to_update
SET cod_user= IF(cod_office = '17389551','622057','2913659','6160230')
,date = IF(cod_office = '17389551','12082014')
WHERE ?? IN (??) ;
I'm not entirely clear how to do the query if there are multiple condition in the WHERE and in the IF condition..any ideas?
You can do it this way:
UPDATE table_users
SET cod_user = (case when user_role = 'student' then '622057'
when user_role = 'assistant' then '2913659'
when user_role = 'admin' then '6160230'
end),
date = '12082014'
WHERE user_role in ('student', 'assistant', 'admin') AND
cod_office = '17389551';
I don't understand your date format. Dates should be stored in the database using native date and time types.
MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.
INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'student', '17389551'),
('2913659', '12082014', 'assistant','17389551'),
('6160230', '12082014', 'admin', '17389551')
ON DUPLICATE KEY UPDATE
cod_user=VALUES(cod_user), date=VALUES(date)
This assumes that the user_rol, cod_office combination is a primary key. If only one of these is the primary key, then add the other field to the UPDATE list.
If neither of them is a primary key (that seems unlikely) then this approach will always create new records - probably not what is wanted.
However, this approach makes prepared statements easier to build and more concise.
UPDATE table_name
SET cod_user =
CASE
WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END, date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
You can use a CASE statement to handle multiple if/then scenarios:
UPDATE table_to_update
SET cod_user= CASE WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END
,date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
To Extend on #Trevedhek answer,
In case the update has to be done with non-unique keys, 4 queries will be need
NOTE: This is not transaction-safe
This can be done using a temp table.
Step 1: Create a temp table keys and the columns you want to update
CREATE TEMPORARY TABLE temp_table_users
(
cod_user varchar(50)
, date varchar(50)
, user_rol varchar(50)
, cod_office varchar(50)
) ENGINE=MEMORY
Step 2: Insert the values into the temp table
Step 3: Update the original table
UPDATE table_users t1
JOIN temp_table_users tt1 using(user_rol,cod_office)
SET
t1.cod_office = tt1.cod_office
t1.date = tt1.date
Step 4: Drop the temp table
In php, you use multi_query method of mysqli instance.
$sql = "SELECT COUNT(*) AS _num FROM test;
INSERT INTO test(id) VALUES (1);
SELECT COUNT(*) AS _num FROM test; ";
$mysqli->multi_query($sql);
comparing result to transaction, insert, case methods in update 30,000 raw.
Transaction: 5.5194580554962
Insert: 0.20669293403625
Case: 16.474853992462
Multi: 0.0412278175354
As you can see, multiple statements query is more efficient than the highest answer.
Just in case if you get error message like this:
PHP Warning: Error while sending SET_OPTION packet
You may need to increase the max_allowed_packet in mysql config file.
UPDATE Table1 SET col1= col2 FROM (SELECT col2, col3 FROM Table2) as newTbl WHERE col4= col3
Here col4 & col1 are in Table1. col2 & col3 are in Table2 I Am trying to update each col1 where col4 = col3 different value for each row
I did it this way:
<update id="updateSettings" parameterType="PushSettings">
<foreach collection="settings" item="setting">
UPDATE push_setting SET status = #{setting.status}
WHERE type = #{setting.type} AND user_id = #{userId};
</foreach>
</update>
where PushSettings is
public class PushSettings {
private List<PushSetting> settings;
private String userId;
}
it works fine

Set all rows except 1

I have a flag in my database called published, I set this to 1 for a published row. My question is , is there a way to set all other rows to 0 and set a particular row to 1 with just one query.
At the moment im using:
$db->query("UPDATE my_table SET published = '0'");
$db->query("UPDATE my_table SET published = '1' WHERE id = '$id'");
UPDATE my_table SET published = IF (id = $id,1,0);
Use a CASE Statement
UPDATE my_table
SET published = CASE
WHEN id = '$id' THEN 1
ELSE 0 END
In MySQL, there's no boolean type (conditions return an integer), so this works too :
UPDATE my_table
SET published = (id = $id);
id = $id returns 0 if $id is different than id, else 1.