My requirement is following simple handling of strings using Oracle 23c:
NULL
or has a length <= 5, it should be returned as it is.So for following sample input data...
CREATE TABLE test (col VARCHAR2(100));
INSERT INTO test VALUES
('hello!'), ('world'), ('worl.'), ('x'), ('long text'), ('alsotoolong'), (NULL);
COL |
---|
hello! |
world |
worl. |
x |
long text |
alsotoolong |
null |
...following result must be returned:
COL |
---|
hell. |
world |
worl. |
x |
long. |
also. |
null |
I was able to get the expected outcome with following query:
SELECT
CASE WHEN LENGTH(col) > 5
THEN SUBSTR(col,1,4) || '.'
ELSE col END AS col
FROM test;
What I just wonder is if we really need a CASE
expression here to check the length. I guess there should be a more trivial way which is shorter and better to read. A solution that just replaces the rest after the fourth character by a dot in one step.
Maybe you have an idea?
I searched here on Stackoverflow and also generally in the net, but couldn't find something related to this use case, so sorry in case there is a duplicate question here which I haven't spotted or in case there is no simpler option.
Anyway, you can use this sample fiddle to try out possible solutions.
This can be done with a regex replace function call, by matching strings of length 6 or more and replacing it with the first 4 characters plus a dot.
SELECT REGEXP_REPLACE(col, '(.{4}).{2,}', '\1.') AS col
FROM test;
This will probably be slower than a case + substring statement though.