Q
Problem solve Get help with specific problems with your technologies, process and projects.

SQL string functions

SQL expert Rudy Limeback explains how to use string functions.

I have a field which is char(12) and numeric value stored. The value could be numeric 9 or numeric 12. I am interested in the last two digits of numeric field. How can I use select statement to pick up those records which the last two digit are "21"?
To set the stage for the answer, let's look at a couple of exampes of the data in your column.

Because the column has the CHAR datatype, all values in the column are "padded" with enough trailing spaces to fill out the entire 12 characters. Let's use the special character "§" to represent a space. You said the values could be numeric 9 or numeric 12, which means that the values in that column would look like this:

123456789§§§
111122223333
937937937§§§

Notice that the 9-digit numbers occupy the leftmost 9 characters of the column, with trailing spaces.

The solution you're looking for, to extract the last two digits, can be accomplished using the RIGHT string function. This is not a standard SQL function, and not every database system has implemented it, but it works in all the popular ones like Oracle, SQL Server, MySQL, et cetera.

But before we can use RIGHT, we have to do something about those trailing spaces. Standard SQL has the TRIM function, which is exactly what we need:

TRIM(TRAILING ' ' FROM column)

Again, popular database systems have all implemented a TRIM function, all of which default to trimming spaces (if no other character is specified). Some database systems allow you to use a function called RTRIM, which trims from the right.

Putting both functions together, we get:


RIGHT(RTRIM(column),2)

This produces these results on our sample values:

89
33
37

Thus, in order to find values where the last two digits are 21, use:

SELECT ...
  FROM ...
 WHERE RIGHT(RTRIM(column),2) = '21'

SQL string functions can be nested, as shown.

This was last published in June 2008

Dig Deeper on Oracle development languages

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide.com

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close