tried this on postgresql
--Syntax
SELECT
LOWER(REGEXP_REPLACE(<CamelCaseExample>, '([a-z0-9])([A-Z])', '\1_\2', 'g')) AS snake_case;
--Example
SELECT
LOWER(REGEXP_REPLACE('CamelCaseExample', '([a-z0-9])([A-Z])', '\1_\2', 'g')) AS snake_case;
--On all records in any table
with my_table (camelcase) as (
values ('StackOverflow'),
('Stackoverflow'),
('stackOverflow'),
('StackOverFlowCom'),
('stackOverFlow')
)
select camelcase, trim(both '_' from lower(regexp_replace(camelcase, '([a-z0-9])([A-Z])', '\1_\2', 'g'))) as snake_case
from my_table;
Just FYI, a) REGEXP_REPLACE
finds places where a lowercase letter or digit is followed by an uppercase letter. b) It inserts an underscore (_
) between them. c) LOWER()
converts the entire result to lowercase.