CREATE INDEX IF NOT EXISTS rd_el_residential_idx ON rd_el USING btree (residential);

CREATE FUNCTION update_residential() RETURNS void AS $$
DECLARE
v_r_residential_id bigint;
BEGIN
SELECT vehicle_restriction_id INTO v_r_residential_id FROM vehicle_restriction WHERE universal_id='residential';

IF v_r_residential_id IS NOT NULL THEN
INSERT INTO rd_el_vehicle_restriction (rd_el_id, vehicle_restriction_id)
    SELECT rd_el_id, v_r_residential_id
    FROM rd_el WHERE residential = 1 AND
        NOT EXISTS (SELECT rd_el_id FROM rd_el_vehicle_restriction rdvr
                        WHERE rdvr.rd_el_id = rd_el.rd_el_id AND
                            rdvr.vehicle_restriction_id = v_r_residential_id);
END IF;

END;
$$ LANGUAGE plpgsql;

SELECT update_residential();

DROP INDEX IF EXISTS rd_el_residential_idx;
