How to get the first two characters of a string in an Oracle query?
To fetch the first two characters from a string using an Oracle SQL query, just use the SUBSTR
function:
It extracts the inaugural 2 characters of your_column
in your_table
.
Practical demonstration and nuances of SUBSTR
Extract while selecting other columns
The SUBSTR
function is friendly and blends well with others. Here's how to extract while selecting other columns as well:
This gives you the ID and the first two letters of the name field for each user. initial
is a new column alias.
Renaming: Because what's in a name anyway?
You can rename the extracted substring for a more comprehensible output:
Label the extracted data as first_two_letters
, making your result set eaSY to understand.
Dealing with less than two characters
If your column content is less than two characters, SUBSTR
doesn't panic; it calmly hands out whatever exists:
Unlocking the true potential of SUBSTR
Traversing the length of parameters
The SUBSTR
function starts counting from 1, indicating the first character, using the length parameter, you can decide the number of characters to pick. If you cross the total string length, it doesn't cause an error - it just ends where the string does.
Probing with DUAL table
You can use Oracle's DUAL
table to trial run some SUBSTR function action:
And remember SUBSTR
is an Oracle-specific native. Other SQL dialects offer similar functionality but via different functions or under different labels like LEFT
, RIGHT
, or SUBSTRING
.
Advanced usage of SUBSTR
Cracking the code from the middle
Don't limit SUBSTR
to the start of a string. You can command it to extract from any position:
Merging with other functions
Combine SUBSTR
with other Oracle functions for achieving complex tasks, like obtaining the last two characters:
Conditional substring extraction
SUBSTR
fits well with CASE
or DECODE
for conditional extraction:
Handling NULL values
A NULL
string? No problem! Use the NVL
function to get a default value:
Was this article helpful?