Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL delete last 4 letters

Tags:

mysql

I need a MySQL query (if PHP is required you can use that too) that will delete the ending of all the values on one column named 'url'.

The problem is that I saved the urls having the .php and now I want to delete that ending from all the values in the database.

Example:

old values:

my_url.php
my_sadas.php

new values:

my_url
my_sadas
like image 785
XCS Avatar asked May 26 '11 12:05

XCS


People also ask

How can I remove last 4 characters from a string in SQL?

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.

How do I get the last 3 characters of a string in SQL?

It could be this using the SUBSTR function in MySQL: SELECT `name` FROM `students` WHERE `marks` > 75 ORDER BY SUBSTR(`name`, -3), ID ASC; SUBSTR(name, -3) will select the last three characters in the name column of the student table.

How do I remove a specific character from a string in MySQL?

Remove characters from string using TRIM() TRIM() function is used to remove any character/ whitespace from the start/ end or both from a string.

What is trim MySQL?

MySQL TRIM() Function The TRIM() function removes leading and trailing spaces from a string.


2 Answers

UPDATE mytable
SET myfield = SUBSTRING(myfield, 1, LENGTH(myfield)-4) ;

If you want to also check whether the field ends with '.php' before truncating, you can add this condition:

UPDATE mytable
SET myfield = SUBSTRING(myfield, 1, LENGTH(myfield)-4)
WHERE RIGHT(myfield, 4) = '.php' ;

Oh, there's also LEFT() which can be used instead of SUBSTRING() as well

And CHAR_LENGTH() should be used instead of LENGTH() as it is multi-byte safe (while LENGTH() is not):

UPDATE mytable
SET myfield = LEFT(myfield, CHAR_LENGTH(myfield)-4)
WHERE RIGHT(myfield, 4) = '.php' ;
like image 126
ypercubeᵀᴹ Avatar answered Oct 05 '22 08:10

ypercubeᵀᴹ


UPDATE files
SET fileName = SUBSTRING(fileName, 1 , (LENGTH(fileName) - 4)) ;
like image 22
Layke Avatar answered Oct 05 '22 09:10

Layke