AsWhat @Pavel answered, the code in the question does not make a whole lot of sensesaid.
Either way Plus, according to your description, you do not need a function at all.
I want to create a function that takes each of those years and runs a query on another table to count the number of rows that belonging to that year.
"Belonging to a year" seems to mean overlapping"overlapping time rangerange". Use a simple query with a JOINJOIN, a smart join condition and aggregation.
Assuming this table (missing in the question):
CREATE TABLE years (
the_date date PRIMARY KEY
);
This query would do the job:
SELECT the_date, count(*) AS row_ct
FROM years y
JOIN other_table o ON (y.the_date, y.the_date + interval '1 year')
OVERLAPS (o.valid_from, COALESCE(o.valid_to, 'infinity'))
GROUP BY 1;
Details forAbout the OVERLAPSOVERLAPS operator:
Find overlapping date ranges in PostgreSQL