PL/pgSQL Select Into
Summary: in this tutorial, you will learn how to use the PL/pgSQL select into
statement to select data from the database and assign it to a variable.
Introduction to PL/pgSQL Select Into statement
The select into
statement allows you to select data from the database and assign it to a variable.
Here’s the basic syntax of the select into
statement:
select column1, column2, ...
into variable1, variable2, ...
from table_expression;
In this syntax,
- First, specify one or more columns from which you want to retrieve data in the
select
clause. - Second, place one or more variables after the
into
keyword. - Third, provide the name of the table in the
from
clause.
The select
into
statement will assign the data returned by the select
clause to the corresponding variables.
Besides selecting data from a table, you can use other clauses of the select
statement such as join
, group by,
and having
.
PL/pgSQL Select Into statement examples
Let’s take some examples of using the select into
statement.
1) Basic select into statement example
The following example uses the select into
statement to retrieve the number of actors from the actor
table and assign it to the actor_count
variable:
do
$$
declare
actor_count integer;
begin
-- select the number of actors from the actor table
select count(*)
into actor_count
from actor;
-- show the number of actors
raise notice 'The number of actors: %', actor_count;
end;
$$;
Output:
NOTICE: The number of actors: 200
In this example:
- First, declare a variable called
actor_count
that stores the number of actors from theactor
table. - Second, assign the number of actors to the
actor_count
using theselect into
statement. - Third, display a message that shows the value of the
actor_count
variable using theraise notice
statement.