I'm working on a PostgreSQL function, but having a real struggle with it. It's not my main area so that's probably why, but I wanted to see if this is doable.

I'm trying to create a function to generate records based on year.

In php I'd do something along the lines of:

```
function recordsByYear($year=''){
    $years = array();
    if(empty($year)){
        $sql = "SELECT year FROM myTable GROUP BY year ORDER BY year;";
        $res = $conn->query($sql);
        if($res !== false){
            $data = $res->fetchAll(PDO::FETCH_COLUMN);
            foreach($data as $oneYear){
                $years[] = $oneYear;
            }
        }
    }
    else{
        $years[] = $year;
    }

    foreach($years as $thisYear){
    //do some queries based on $thisYear
    }
}

```

But I'd like to create a function inside of PostgreSQL, and struggling because I'm not familiar enough with how it all works. I'd like to return a table. I can do some basic stuff, but haven't been able to get something like this working where I have one query then loop through those results running an additional query for each year, then combine the results of that second query and spit out the results as a table.