Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL UPDATE with LIKE

Tags:

database

mysql

I was trying to update approx 20,000 records in a table by using statements like this one, however, I got the message say 0 row(s) affected so it didn't work.

UPDATE nc_files SET title ="Worklog details" WHERE "log_name" LIKE "%PC01%"

The log_name field has all the file names with mixed file extensions and cases ,e.g.

PC01.TXT | Worklog details

PC02.txt | Project Summary

PC03.DOC| Worklog details

PC04.doc| Project Summary

The reason why I need to use LIKE is that the updated file only have file name without extension, e.g.

PC01 | Worklog details

PC02 | Project Summary

How do I update records by using LIKE?

like image 907
jumax Avatar asked Aug 29 '12 11:08

jumax


People also ask

How do you use like in UPDATE query?

As an additional suggestion, if your updated file contains file names without extension, I suggest to change your LIKE clause as follows: WHERE log_name LIKE "PC01%" . This will make sure that indexes (if any is present) are used, making queries faster.

Can we use like operator in UPDATE statement?

The LIKE operator is used in the WHERE clause of the SELECT , UPDATE , and DELETE statements to filter rows based on pattern matching.

What is like %% in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

How do you UPDATE values based on conditions in SQL?

Update with condition WHERE clause can be used with SQL UPDATE to add conditions while modifying records. Without using any WHERE clause, the SQL UPDATE command can change all the records for the specific columns of the table.


2 Answers

The log_name is a field name, remove literal quotes from it -

UPDATE nc_files SET title ="Worklog details" WHERE log_name LIKE "%PC01%"
like image 95
Devart Avatar answered Sep 22 '22 19:09

Devart


this is because your column name log_name should not be in ' quotes.

"log_name" LIKE "%PC01%" condition will always fail and zero rows will get updated, try this:

UPDATE nc_files 
SET title ="Worklog details" 
WHERE log_name LIKE "%PC01%";
like image 41
Omesh Avatar answered Sep 25 '22 19:09

Omesh