While converting Oracle to Postgresql I came to know the following Oracle query need to be converted in Postgres.
Oracle Query: Find pattern and replace with null
select regexp_replace('1', '[^0-9]', null) from dual;
select regexp_replace('a', '[^0-9]', null) from dual;
select regexp_replace('1a1', '[^0-9]', null) from dual;
My try:
As per the postgres document we need to use REGEXP_REPLACE
with [[:alpha:]]
pattern.
But the statement is replacing with
empty string if match found. I'm looking for null
instead.
PostgreSQL Query:
select REGEXP_REPLACE('1','[[:alpha:]]','','g') --Correct
select REGEXP_REPLACE('a','[[:alpha:]]','','g') --Wrong: output should be NULL
select REGEXP_REPLACE('1a1','[[:alpha:]]','','g') --Correct
select REGEXP_REPLACE(' ','[[:alpha:]]','','g') --Wrong: output should be NULL
Definitely we can use case
statement like following but I want the solution in single line without using case
condition.
SELECT case when REGEXP_REPLACE('1a','[[:alpha:]]','','g') = ''
then
null
else
REGEXP_REPLACE('1a','[[:alpha:]]','','g')
end;