2012
Quick Tip: Returning a Substring From an Oracle/MySQL Text Field (From the Start Or the End)
Miscellaneous , Oracle 2 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...
Recent Comments