Skip to content

Instantly share code, notes, and snippets.

@molind
Created February 10, 2024 11:44
Show Gist options
  • Save molind/58196935caf96c9a78f0a4a2732c8802 to your computer and use it in GitHub Desktop.
Save molind/58196935caf96c9a78f0a4a2732c8802 to your computer and use it in GitHub Desktop.
Magic in nested branches
CREATE TABLE test_data (
housenumber text
);
INSERT INTO test_data VALUES
('123;456'),
('789;'),
(';'),
('abc;def'),
('');
CREATE OR REPLACE FUNCTION display_housenumber_nonnumeric(raw_housenumber text)
RETURNS text AS $$
SELECT substring(raw_housenumber from 1 for position(';' in raw_housenumber) - 1)
|| '–'
|| substring(raw_housenumber from position(';' in raw_housenumber) + 1);
$$ LANGUAGE SQL IMMUTABLE;
CREATE OR REPLACE FUNCTION display_housenumber_numeric(raw_housenumber text)
RETURNS text AS $$
SELECT min(value)::text || '–' || max(value)::text
FROM unnest(string_to_array(raw_housenumber, ';')::int[]) AS value;
$$ LANGUAGE SQL IMMUTABLE;
CREATE OR REPLACE FUNCTION display_housenumber(raw_housenumber text)
RETURNS text AS $$
SELECT CASE
WHEN raw_housenumber !~ ';' THEN raw_housenumber
WHEN raw_housenumber ~ '[^0-9;]' THEN display_housenumber_nonnumeric(raw_housenumber)
else display_housenumber_numeric(raw_housenumber)
END
$$ LANGUAGE SQL IMMUTABLE;
SELECT display_housenumber('') FROM test_data;
SELECT display_housenumber(housenumber) FROM test_data;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment