Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add result of generate_series to array in PostgreSQL?

Tags:

postgresql

PostgreSQL 9.5.4.

I have a function which returns array of days between two dates in string form. It's based on this code:

select (generate_series('2012-06-29', '2012-07-03', '1 day'::interval))::date

This code gives five dates in output, it's ok.

But if I do this in function:

DECLARE
dates date[];

BEGIN
select (generate_series('2012-06-29', '2012-07-03', '1 day'::interval))::date into dates;
return array_to_string(dates, ',');
END;

Then there is an error like this: "Invalid array literal '2012-06-29'. The value of the array must begin with "{" or specify the dimension. "

How can I fix this?

like image 292
Log Avatar asked Apr 08 '17 18:04

Log


People also ask

What is generate series in PostgreSQL?

Generate a series of numbers in postgres by using the generate_series function. The function requires either 2 or 3 inputs. The first input, [start], is the starting point for generating your series. [ stop] is the value that the series will stop at. The series will stop once the values pass the [stop] value.

What is Unnest in PostgreSQL?

Unnest function generates a table structure of an array in PostgreSQL. Unnest array function is beneficial in PostgreSQL for expanding the array into the set of values or converting the array into the structure of the rows. PostgreSQL offers unnest() function.

What is a set returning function?

A Set Returning Function is a PostgreSQL Stored Procedure that can be used as a relation: from a single call it returns an entire result set, much like a subquery or a table. It used to be possible to use SRF in the SELECT clause, with dubious (but useful at times) semantics, and also in scalar contexts.

Should you use arrays in Postgres?

When you are considering portability (e.g. rewriting your system to work with other databses) then you must not use arrays. If you are sure you'll stick with Postgres, then you can safely use arrays where you find appropriate. They exist for a reason and are neither bad design nor non-compliant.


2 Answers

You can use the array constructor:

DECLARE
  dates date[];
BEGIN
  select array(select generate_series('2012-06-29', '2012-07-03', '1 day'::interval)::date)
    into dates;  --need semicolon here
  return dates;
END;

If that code is actually a function, then you can simplify it to a SQL function

create function get_dates()
  returns date[]
$$
  select array(select generate_series(current_date - 6, current_date, interval '1' day)::date);
$$
language sql;
like image 175
a_horse_with_no_name Avatar answered Sep 26 '22 14:09

a_horse_with_no_name


"Invalid array literal '2012-06-29'. The value of the array must begin with "{" or specify the dimension. "

SELECT returns a row set,

ARRAY() function can convert row set into an array. and the reverse function is UNNEST().

like image 26
Ben Avatar answered Sep 22 '22 14:09

Ben