Fomalhaut
Fomalhaut

Reputation: 9747

How do I assign a variable with the first selected value in Postgres syntax?

I try this:

myvar := select "name" from "mytable" where "id" = 15;

But it causes an error. How can I assign the variable correctly?

Upvotes: 0

Views: 34

Answers (2)

Gehtnet
Gehtnet

Reputation: 447

It will work when you are using the INTO Keyword like

select "name" into myvar from "mytable" where "id" = 15;

But its possible that this returns more than one row. (Throws an Error in Oracle-SQL, cant speak for Postgres)

I think somithing like

select "name" into myvar from "mytable" where "id" = 15 limit 1;

would be better to fit your question title.

Upvotes: 1

Vao Tsun
Vao Tsun

Reputation: 51446

select "name" into myvar from "mytable" where "id" = 15;

or

myvar := (select "name" from "mytable" where "id" = 15);

Upvotes: 1

Related Questions