Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Substring - Last 3 Characters

Using T-SQL, how would I go about getting the last 3 characters of a varchar column?

So the column text is IDS_ENUM_Change_262147_190 and I need 190

like image 671
Jared Avatar asked Dec 02 '11 16:12

Jared


People also ask

How do I get the last 3 letters 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 get last 4 characters of a string in SQL?

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.

How do you order last 3 characters?

SELECT *FROM yourTableName ORDER BY RIGHT(yourColumnName,3) yourSortingOrder; Just replace the 'yourSortingOrder' to ASC or DESC to set the ascending or descending order respectively.


2 Answers

SELECT RIGHT(column, 3) 

That's all you need.

You can also do LEFT() in the same way.

Bear in mind if you are using this in a WHERE clause that the RIGHT() can't use any indexes.

like image 69
JNK Avatar answered Oct 07 '22 14:10

JNK


You can use either way:

SELECT RIGHT(RTRIM(columnName), 3) 

OR

SELECT SUBSTRING(columnName, LEN(columnName)-2, 3) 
like image 45
Elias Hossain Avatar answered Oct 07 '22 15:10

Elias Hossain