Check if a value can be typecast as an interval in postgres Check if a value can be typecast as an interval in postgres postgresql postgresql

Check if a value can be typecast as an interval in postgres


There is a fairly wide variety of formats that produce valid interval input. The simple answer is therefore that you cannot simply check if some string is a valid interval.

Probably the most straightforward solution is to use a PL/pgSQL function that converts the string to interval and returns null on any error:

CREATE FUNCTION string_to_interval(s text) RETURNS interval AS $$BEGIN    RETURN s::interval;EXCEPTION WHEN OTHERS THEN    RETURN NULL;END; $$ LANGUAGE plpgsql STRICT;

Use it like:

SELECT string_to_interval(my_interval) AS my_valid_intervalFROM ...