Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL query to replace spaces in a column with underscores

Tags:

I have a MySQL database table 'photos' with a column 'filename'. I need to replace the spaces in the filename column values with underscores. Is it possible with a single/multiple query? If so how?

like image 357
Mithun Sreedharan Avatar asked Nov 27 '09 05:11

Mithun Sreedharan


People also ask

How can remove space from column in MySQL?

The TRIM() function returns a string that has unwanted characters removed. Note that to remove the leading spaces from a string, you use the LTRIM() function. And to remove trailing spaces from a string, you use the RTRIM() function.

How do I change a space in SQL?

SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.

Is underscore allowed in MySQL?

You cannot give underscore in table name. If you still want to create a new table with underscore, surround it using backticks, not single quotes.


1 Answers

You can use the REPLACE function :

REPLACE(str,from_str,to_str)

Returns the string str with all occurrences of the string from_str replaced by the string to_str.
REPLACE() performs a case-sensitive match when searching for from_str.

So, to replace all occurences of a character by another one in all lines of a table, something like this should do :

update photos set filename = replace(filename, ' ', '_'); 

ie, you search for ' ' in the column filename and use '_' instead ; and put the result back into filename.

like image 77
Pascal MARTIN Avatar answered Sep 23 '22 22:09

Pascal MARTIN