I have a column Id
in a PostgreSQL table ABC
.
Id
is a bigint
of length 10 (minLength=maxLength=10)
I have to write a SQL query and classify Id
as:
Each type can be found with a regular expression.
create table ABC ( Id decimal(10) primary key check(length(Id::text)=10) ); insert into ABC (Id) values (1350000042) , (1640000000) , (1090000503) , (1294567890) , (1090000907) , (1090000902)
/* Type A: Any Id that commences with exactly 3 consecutive odd digits and concludes with at least 2 consecutive even digits; Type B: Any Id where the second digit is greater than 6 or the third character is less than or equal to 4; Type C: Any odd-numbered Id unless it ends in 7; Type D: Any even-numbered Id unless it ends in 2; Type X: All other Id; */ select Id , case when Id::text ~ '^[13579]{3}[02468].*[02468]{2}$' then 'A' when Id::text ~ '^(.[7-9]|..[0-4])' then 'B' when Id::text ~ '[1359]$' then 'C' when Id::text ~ '[0468]$' then 'D' else 'X' end as Type from ABC order by Type
id | type ---------: | :--- 1350000042 | A 1760000000 | B 1640000000 | B 1090000503 | C 1294567890 | D 1090000907 | X 1090000902 | X
db<>fiddle here