tl;dr
Use split_part
which was purposely built for this:
split_part(string, '_', 1)
Explanation
Quoting this PostgreSQL API docs:
SPLIT_PART()
function splits a string on a specified delimiter and returns the nth substring.
The 3 parameters are the string to be split, the delimiter, and the part/substring number (starting from 1) to be returned.
So if you have a field named string
that contains stuff like AB_XXX
and you would like to get everything before _
, then you split by that and get the first part/substring: split_part(string, '_', 1)
.