Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim commas with MySQL?

I have a list of keywords like below and some keyword lists in the database have a leading or trailing ,

keyword,keyword,keyword,keyword,

How do I trim the leading and/or trailing , using mysql?

I have tried using trim but can't seem to get it to work on an UPDATE, which is what I'm trying to achieve.

like image 348
Sean H Jenkins Avatar asked Dec 17 '11 14:12

Sean H Jenkins


People also ask

How do I trim a comma in MySQL?

To remove all characters after the last comma in the string, you can use SUBSTRING_INDEX(). If you do not know the location of the last comma, then you need to find the last comma dynamically using LENGTH().

How do I trim a character in MySQL?

Use the TRIM() function with the LEADING keyword to remove characters at the beginning of a string. TRIM() allows you to remove specific character(s) or space(s) from the beginning, end, or both ends of a string. This function takes the following arguments: An optional keyword that specifies the end(s) to trim.

How do I remove comma separated values in MySQL query?

SELECT TRIM(BOTH ',' FROM ',,,demo, ,xxxx,,,yyy,,,'); SELECT REPLACE(TRIM(TRIM(',' FROM ',,,demo, ,xxxx,,,yyy,,,')), ',,', ',');

How do I trim a word 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.


1 Answers

 TRIM(BOTH ',' FROM ',keyword,keyword,')

The above would return 'keyword,keyword'.

BOTH can be replaced with either LEADING or TRAILING if you just want to trim on one side of the string.

Documentation

  • MySQL 5.0 Reference Manual :: 11.5 String Functions :: TRIM

There shouldn't be any problem using TRIM in an UPDATE query, but without the query in question we cannot offer any specific help. But TRIM is just like any other function available, it takes a set of parameters and returns a value.


Sample post-insert query to fix fields with trailing ','

UPDATE `table_name` SET `keywords` = TRIM(TRAILING ',' FROM `keywords`);
like image 76
Filip Roséen - refp Avatar answered Oct 24 '22 15:10

Filip Roséen - refp