Skip to content
Advertisement

How to Select a substring in Oracle SQL up to a specific character?

Say I have a table column that has results like:

I would like to be able to write a query that selects this column from said table, but only returns the substring up to the Underscore (_) character. For example:

The SUBSTRING function doesn’t seem to be up to the task because it is position-based and the position of the underscore varies.

I thought about the TRIM function (the RTRIM function specifically):

But I’m not sure how I’d get this to work since it only seems to remove a certain list/set of characters and I’m really only after the characters leading up to the Underscore character.

Advertisement

Answer

Using a combination of SUBSTR, INSTR, and NVL (for strings without an underscore) will return what you want:

Result:

Use:

Reference:

Addendum

If using Oracle10g+, you can use regex via REGEXP_SUBSTR.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement