I have a database column and its give a string like ,Recovery, Pump Exchange,
.
I want remove first and last comma from string.
Expected Result : Recovery, Pump Exchange
.
To delete the first characters from the field we will use the following query: Syntax: SELECT SUBSTRING(string, 2, length(string));
Below is the syntax for the SUBSTRING() function to delete the last N characters from the field. Syntax: SELECT SUBSTRING(column_name,1,length(column_name)-N) FROM table_name; Example: Delete the last 2 characters from the FIRSTNAME column from the geeksforgeeks table.
To get the first n characters of string with MySQL, use LEFT(). To get the last n char of string, the RIGHT() method is used in MySQL.
You can use SUBSTRING
for that:
SELECT
SUBSTRING(col, 2, LEN(col)-2)
FROM ...
Obviously, an even better approach would be not to put leading and trailing commas there in the first place, if this is an option.
I want to remove last and first comma only if exist otherwise not.
The expression becomes a little more complex, but the idea remains the same:
SELECT SUBSTRING(
col
, CASE LEFT(@col,1) WHEN ',' THEN 2 ELSE 1 END
, LEN(@col) -- Start with the full length
-- Subtract 1 for comma on the left
- CASE LEFT(@col,1) WHEN ',' THEN 1 ELSE 0 END
-- Subtract 1 for comma on the right
- CASE RIGHT(@col,1) WHEN ',' THEN 1 ELSE 0 END
)
FROM ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With