Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return everything before 2nd occurrence in a string in PostgreSQL

I want to return all characters before the 2nd occurrence of the character slash '/' (if any) in PostgreSQL.

Input Column:

/apple/orange/banana
/
/mango
/avocado/kiwi

Desired Output Column:

/apple
/
/mango
/avocado

Can anyone help with this please?

like image 388
htols Avatar asked Apr 15 '26 00:04

htols


1 Answers

One method is regexp_replace():

select t.*,
       regexp_replace(col, '^([^/]*/[^/]*)/.*$', '\1')
from t;

Here is a db<>fiddle.

like image 109
Gordon Linoff Avatar answered Apr 17 '26 00:04

Gordon Linoff