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:
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.
Dig Deeper on Oracle development languages
Related Q&A from Rudy Limeback
Read SQL expert Rudy Limeback's advice for counting combinations in a table with SQL's GROUP BY clause Continue Reading
Read about the Mimer Validator, a tool used to verify your SQL code, in this tip from SQL expert Rudy Limeback. Continue Reading
Read an example of an SQL case expression from our SQL expert Rudy Limeback. Continue Reading