How to take last four characters from a varchar?

SqlSql Server-2008Tsql

Sql Problem Overview


I'm trying to take the last four characters only from a varchar field. All the rows are different lengths. What function should I be using to accomplish this?

Sql Solutions


Solution 1 - Sql

Right should do:

select RIGHT('abcdeffff',4)

Solution 2 - Sql

SUBSTR(column, LENGTH(column) - 3, 4)

LENGTH returns length of string and SUBSTR returns 4 characters from "the position length - 4"

Solution 3 - Sql

RIGHT ( character_expression , integer_expression )

SELECT RIGHT(column, 4) FROM ...

Also a list of other string functions.

Solution 4 - Sql

Use the RIGHT() function: http://msdn.microsoft.com/en-us/library/ms177532(v=sql.105).aspx

SELECT RIGHT( '1234567890', 4 ); -- returns '7890'

Solution 5 - Sql

For Oracle SQL, SUBSTR(column_name, -# of characters requested) will extract last three characters for a given query. e.g.

SELECT SUBSTR(description,-3) FROM student.course;

Solution 6 - Sql

I have Used RIGHT function in SQL Server and it's working.

SELECT RIGHT( your_column_name, 4 );

--It will show last 4 digit/char

Solution 7 - Sql

You can select last characters with -
WHERE SUBSTR('Hello world', -4)

Solution 8 - Sql

tested solution on hackerrank....

select distinct(city) from station
where substr(lower(city), length(city), 1) in ('a', 'e', 'i', 'o', 'u') and substr(lower(city), 1, 1) in ('a', 'e', 'i', 'o', 'u');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael AView Question on Stackoverflow
Solution 1 - SqlVoid RayView Answer on Stackoverflow
Solution 2 - SqldrchrisView Answer on Stackoverflow
Solution 3 - SqlBrad ChristieView Answer on Stackoverflow
Solution 4 - SqlTim M.View Answer on Stackoverflow
Solution 5 - SqlalexanderjsingletonView Answer on Stackoverflow
Solution 6 - SqlDiganta DasView Answer on Stackoverflow
Solution 7 - SqlAmr TawfikView Answer on Stackoverflow
Solution 8 - SqlPratishtha TripathiView Answer on Stackoverflow