Quick Tip: Returning a Substring From an Oracle/MySQL Text Field (From the Start Or the End)

Miscellaneous , Oracle Add comments

In addition to the normal aggregate functions (Count, Sum, Avg, etc.), most database implementations of SQL also include functions for manipulating string values.  One of those is substr(), which allows you to extract a substring of the text value in a database field by specifying the start position and the number of characters. 

So if you wanted to extract the first 5 digits of a 9-digit postal code from your "zipCode" field.  You could do it like so:

select substr(zipCode,1,5) as mainZip...

...where 1 is the starting position and 5 the number of characters.  If you knew that the format of all the zip codes was "xxxxx-xxxx", then you could also retrieve the last 4-digits by moving the starting position and adjusting the character count:

select substring(zipCode,6,4) as extendedZip...

But what if you had strings where you wanted to extract the last 4 letters in the string, but the string length varied, like these values:

Professor - GVPT
Assist. Professor - LTSC
Prof. Emeritus - ENGR

You could use the length() function to get the full length of the string and then subtract one less than the number of characters you want from it to get the starting position:

select substr(nameDept,length(nameDept)-3,4) as dept...

...but Oracle and MySQL provide a simpler method:  you can designate the starting position from the right end of the string by using a negative number:

select substr(nameDept,-4,4) as dept...

2 responses to “Quick Tip: Returning a Substring From an Oracle/MySQL Text Field (From the Start Or the End)”

  1. Maggie Says:
    This is very interesting. Tello me would the code be the same for postal codes with letters and numbers in it.

    Thanks for your reply
  2. Brian Swartzfager Says:
    @Maggie: Not if the length of the postal code remained the same. The substr command doesn't differentiate between the letters and numbers within the string.

Leave a Reply