Summary: In this tutorial, you’ll learn how to PL/pgSQL SELECT INTO statement to select data from a table and assign it to a variable.
Overview of the PL/pgSQL SELECT INTO Statement #
The SELECT INTO statement retrieves data from a table and assigns it to a variable:
SELECT column1, column2, ...
INTO variable1, variable2, ...
FROM table_name;Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)In this syntax:
- First, provide one or more columns of the table_name to retrieve data in the
SELECTclause. - Second, specify a variable list in the
INTOclause. - Third, specify the table name from which you retrieve data in the
FROMclause.
The SELECT statement assigns the values retrieved from column1, column2, … to the corresponding variable1, variable2, … If the SELECT statement returns no rows, the variables will retain their initial values.
Besides table columns, you can use expressions in the SELECT clause. The SELECT statement may include clauses such as JOIN, GROUP BY, and HAVING.
PL/pgSQL SELECT INTO Statement Examples #
Let’s explore some examples of using the SELECT INTO statement. We’ll use the products and inventories tables: