Store query result in a variable using in PL/pgSQL
I think you're looking for SELECT select_expressions INTO
:
select test_table.name into name from test_table where id = x;
That will pull the name
from test_table
where id
is your function's argument and leave it in the name
variable. Don't leave out the table name prefix on test_table.name
or you'll get complaints about an ambiguous reference.
The usual pattern is EXISTS(subselect)
:
BEGIN
IF EXISTS(SELECT name
FROM test_table t
WHERE t.id = x
AND t.name = 'test')
THEN
---
ELSE
---
END IF;
This pattern is used in PL/SQL, PL/pgSQL, SQL/PSM, ...
To assign a single variable, you can also use plain assignment in a PL/pgSQL code block, with a scalar subquery to the right:
name := (SELECT t.name from test_table t where t.id = x);
Effectively the same as SELECT INTO
like @mu already provided, with subtle differences:
SELECT INTO
is slightly faster in my tests on Postgres 14.
(Plain assignment of a constant, without involvingSELECT
, is 10x faster, still.)SELECT INTO
also sets the special variableFOUND
, while plain assignment does not. You may want one or the other.SELECT INTO
can also assign multiple variables at once. See:- SELECT INTO with more than one attribution
Notably, this works, too:
name := t.name from test_table t where t.id = x;
A SELECT
statement without leading SELECT
. But I would not use this hybrid. Better use one of the first two, clearer, documented methods, as @Pavel commented.