Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the last 4 characters from a mysql database field?

Tags:

In order to be able to simulate substr from PHP and mysql, I want to do something like

select * from table where last_four_chars(field) = '.png' 
like image 394
Toni Michel Caubet Avatar asked Mar 29 '11 02:03

Toni Michel Caubet


People also ask

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

You can select last characters with - This will be giving you all the lines but only with their last 4 characters.

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.

Which query will extract last four characters from a string?

SQL Server RIGHT() Function The RIGHT() function extracts a number of characters from a string (starting from right).


2 Answers

The docs have an example directly relevant to this.

select * from table where SUBSTRING(field, -4) = '.png' 
like image 60
Frank Farmer Avatar answered Oct 06 '22 08:10

Frank Farmer


With RIGHT function :

SELECT RIGHT('abcdefg', 3); -- efg 

You can achieve the same result with SUBSTRING :

SELECT SUBSTRING('abcdefg', -3); -- efg 
like image 24
Vincent Savard Avatar answered Oct 06 '22 08:10

Vincent Savard