Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

I have a Char(15) field, in this field I have the data below:

94342KMR
947JCP
7048MYC

I need to break down this, I need to get the last RIGHT 3 characters and I need to get whatever is to the LEFT. My issue is that the code on the LEFT is not always the same length as you can see.

How can I accomplish this in SQL?

Thank you

like image 456
jorame Avatar asked Jul 01 '13 16:07

jorame


People also ask

How do you use the left function?

The LEFT function in Excel is a type of text function in Excel that gives the number of characters from the start of the string, from left to right. So, for example, if we use this function as =LEFT ( “ANAND”,2) this will give us AN as a result.

What is left use?

LEFT returns the first character or characters in a text string, based on the number of characters you specify. LEFTB returns the first character or characters in a text string, based on the number of bytes you specify. Important: These functions may not be available in all languages.


2 Answers

SELECT  RIGHT(RTRIM(column), 3),
        LEFT(column, LEN(column) - 3)
FROM    table

Use RIGHT w/ RTRIM (to avoid complications with a fixed-length column), and LEFT coupled with LEN (to only grab what you need, exempt of the last 3 characters).

if there's ever a situation where the length is <= 3, then you're probably going to have to use a CASE statement so the LEFT call doesn't get greedy.

like image 176
Brad Christie Avatar answered Oct 05 '22 05:10

Brad Christie


You can use RTRIM or cast your value to VARCHAR:

SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)

Or

SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)
like image 30
Lamak Avatar answered Oct 05 '22 06:10

Lamak