Skip to content

Instantly share code, notes, and snippets.

@gintsmurans
Created April 6, 2016 14:52
Show Gist options
  • Save gintsmurans/6b2ea70bab4fd1b42a46cf16fcde310c to your computer and use it in GitHub Desktop.
Save gintsmurans/6b2ea70bab4fd1b42a46cf16fcde310c to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION jsonb_array_search(json_arr jsonb, col TEXT, search_for TEXT) RETURNS boolean
LANGUAGE plpgsql IMMUTABLE AS $$
DECLARE
rec jsonb;
len int;
ret boolean = false;
BEGIN
-- If json_arr is not an array, return false
BEGIN
len := jsonb_array_length(json_arr);
EXCEPTION WHEN OTHERS THEN
RETURN false;
END;
-- Do the search
FOR rec in SELECT * FROM jsonb_array_elements(json_arr)
LOOP
CASE WHEN rec ? col AND rec->>col ILIKE search_for THEN
ret = true;
EXIT;
ELSE
END CASE;
END LOOP;
RETURN ret;
END $$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment