0

I'm trying to declare a variable for later use in a PostgreSQL query. I've done this often in TSQL, but I wasn't sure about the syntax.

The stuff I've seen online all points to something like this:

declare timestamp_utc timestamp := current_timestamp;
select start_date;

when I run the above query, I get an error message:

ERROR: syntax error at or near "timestamp"

I'm sure this is simple, but I just can't find the answer online. Any help you could provide would be greatly appreciated.

asked Sep 8, 2023 at 13:20
1

2 Answers 2

0

There are no variables in plain SQL.
You can use "customized options" as limited workaround. See:

Server-side procedural languages like PL/pgSQL have variables. You can use DECLARE in a code block - in functions, procedures and in anonymous code blocks executed with the DO command. PL/pgSQL is the default PL for the latter. See:

Or you can set variables in the client, like the default command-line terminal psql. See:

Related:

answered Sep 8, 2023 at 13:58
1
  • This was very helpful. Thanks! Commented Sep 8, 2023 at 14:01
0

As Erwin pointed out, you can't declare variables in vanilla PostgreSQL. The way I got around this was by declaring a temp table and inserting the values I needed in there.

drop table if exists variables;
create temp table variables (
 timestamp_utc timestamp 
);
insert into variables select current_timestamp;
select timestamp_utc from variables;
drop table if exists variables;

It's a lot more code, but it handles the use case I'm working with.

answered Sep 8, 2023 at 14:16
1
  • Put all of that inside a transaction! Commented Sep 9, 2023 at 7:31

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.