Johnny Metz
Johnny Metz

Reputation: 5955

postgresql: store result of sql query in variable

I'm trying to store the result of a sql query, which should be a single date, in a variable. I'm doing this because I plan to reuse the variable several times throughout the rest of the script. I've tried the following:

DO
$$
DECLARE
  date_ordered date;
BEGIN
  date_ordered := SELECT MIN(event_date) FROM event;
END;
$$

Unfortunately I'm getting a syntax error at SELECT. Any idea what I'm doing wrong here or if this is even possible?

Upvotes: 1

Views: 1281

Answers (1)

sticky bit
sticky bit

Reputation: 37472

Enclose the query in parenthesis.

...
date_ordered := (SELECT MIN(event_date) FROM event);
...

Or use SELECT ... INTO.

...
SELECT MIN(event_date) INTO date_ordered FROM event;
...

Upvotes: 3

Related Questions