Home >Database >Mysql Tutorial >How to Extract a Substring Before an Underscore in Oracle SQL?
Identifying the position of a character within a string can be a common challenge in data manipulation. To address this, the question explores a scenario where substrings up to a specific character, in this case the underscore ('_'), need to be extracted from a table column.
The initial approach of using the SUBSTRING function proves insufficient due to its reliance on position-based selection. As the underscore's position varies in the given examples, this method fails to consistently retrieve the desired substring.
The consideration of the RTRIM function, intended to remove a specific set of characters from the right side, initially seems promising. However, it falls short in isolating the characters leading up to the underscore unless the RTRIM function is used in conjunction with another method.
The solution lies in combining the SUBSTR function with INSTR, which identifies the character's position, and NVL, which handles null values. The following code demonstrates this approach:
SELECT NVL(SUBSTR('ABC_blah', 0, INSTR('ABC_blah', '_')-1), 'ABC_blah') AS output FROM DUAL
The above is the detailed content of How to Extract a Substring Before an Underscore in Oracle SQL?. For more information, please follow other related articles on the PHP Chinese website!