I've created the following stored procedure which should return all the location names that had an intersection with polygon group (without distinct... intersection with 3 polygons => 3 names)
CREATE OR REPLACE FUNCTION get_name_without_distinct_by_polygon_group(start_time TIMESTAMP,
                                                                      end_time TIMESTAMP,
                                                                      polygon_group_id INTEGER)
RETURNS TABLE(name_name_name_name VARCHAR(12)) AS $$
DECLARE
  name VARCHAR(12);
  poly_id INTEGER;
BEGIN
  FOR poly_id IN (SELECT polygon_id 
                  FROM polygon_group_members 
                  WHERE group_id = poly_id)
    LOOP
      FOR name IN (SELECT DISTINCT name
                   FROM location, polygons
                   WHERE location.timestamp BETWEEN start_time AND end_time
                        AND poly_id = polygons.id
                        AND st_intersects(location.polygon, polygons.polygon))
      LOOP
        RETURN NEXT name;
      END LOOP;
  END LOOP;
  RETURN;
END;
$$ LANGUAGE SQL;
When I tried to create this function I got the following error:
[42601] ERROR: syntax error at or near "VARCHAR" Position: 356
Based on PostgreSQL declaration documentation it seems OK ...
What I've tried so far:
- I changed - name VARCHAR(12);to- name location.mac%TYPE
- I changed - name VARCHAR(12);to- name RECORD
- I changed the scope of the declaration then I got the same error on - poly_id INTEGER;
- I changed the - LANGUAGE SQLto- postgressql
- I googled it and according to any example/problem I found this procedure should work. 
 
     
    