Wednesday, July 25th, 2007...9:27 am
Postgres Array Joins
Every once in a while you'll come across the need to create a temp table to perform a complicated select query. Not being a big fan of creating these temp tables, I came up with a better solution. Leveraging Postgresql's array structure, I wrote a function that converts a varchar[] to a record set.
RETURNS SETOF character varying AS
$BODY$
DECLARE
in_array alias FOR $1;
out_varchar varchar;
BEGIN
FOR i IN 1..array_upper(in_array,1) loop
RETURN next in_array[i];
end loop;
RETURN;
END
$BODY$
LANGUAGE 'plpgsql' STABLE;
This allows me to pass in an unknown amount of data and perform a LEFT OUTER JOIN on it without losing my orignal data.
a.name, b.name, b.other_info
FROM
(SELECT array_to_rows AS name FROM array_to_rows(ARRAY['JOE', 'SCOTT', 'BOB']) a
LEFT OUTER JOIN names b ON a.name ilike '%' || b.name || '%'
Hope you find this useful!







1 Comment
April 28th, 2008 at 9:05 am
nice post! exactly what I am looking for.
Leave a Reply