Reputation: 11
I have data in table 000_ABC_AXEL. The expectation is that i have to exclude data after the last '_' and get 000_ABC in oracle sql? Any suggestions?
Need sql query to achieve below for ex:
a_222_4 -- > expected result :a_222
123_xyz_0 -- >expected result :123_xyz
Upvotes: 0
Views: 131
Reputation: 167981
You can do it with simple string functions (which are much faster than regular expressions) by finding the sub-string up to the character before the last underscore:
SELECT SUBSTR(col, 1, INSTR(col, '_', -1) - 1) AS first_parts
FROM table_name;
Which, for the sample data:
CREATE TABLE table_name (col) AS
SELECT 'a_222_4' FROM DUAL UNION ALL
SELECT '123_xyz_0' FROM DUAL;
Outputs:
FIRST_PARTS |
---|
a_222 |
123_xyz |
Upvotes: 1
Reputation: 521269
A regex replacement fits your requirement nicely:
SELECT col, REGEXP_REPLACE(col, '_[^_]+$', '') AS col_out
FROM yourTable;
Upvotes: 3