43.3. Declarations
  Chapter 43. PL/pgSQL — Procedural Language  

43.3. Declarations #

All variables used in a block must be declared in the declarations section of the block. (The only exceptions are that the loop variable of a FOR loop iterating over a range of integer values is automatically declared as an integer variable, and likewise the loop variable of a FOR loop iterating over a cursor's result is automatically declared as a record variable.)

PL/pgSQL variables can have any SQL data type, such as integer , varchar , and char .

Here are some examples of variable declarations:

The general syntax of a variable declaration is:

The DEFAULT clause, if given, specifies the initial value assigned to the variable when the block is entered. If the DEFAULT clause is not given then the variable is initialized to the SQL null value. The CONSTANT option prevents the variable from being assigned to after initialization, so that its value will remain constant for the duration of the block. The COLLATE option specifies a collation to use for the variable (see Section 43.3.6 ). If NOT NULL is specified, an assignment of a null value results in a run-time error. All variables declared as NOT NULL must have a nonnull default value specified. Equal ( = ) can be used instead of PL/SQL-compliant := .

A variable's default value is evaluated and assigned to the variable each time the block is entered (not just once per function call). So, for example, assigning now() to a variable of type timestamp causes the variable to have the time of the current function call, not the time when the function was precompiled.

Once declared, a variable's value can be used in later initialization expressions in the same block, for example:

43.3.1. Declaring Function Parameters #

Parameters passed to functions are named with the identifiers $1 , $2 , etc. Optionally, aliases can be declared for $ n parameter names for increased readability. Either the alias or the numeric identifier can then be used to refer to the parameter value.

There are two ways to create an alias. The preferred way is to give a name to the parameter in the CREATE FUNCTION command, for example:

The other way is to explicitly declare an alias, using the declaration syntax

The same example in this style looks like:

These two examples are not perfectly equivalent. In the first case, subtotal could be referenced as sales_tax.subtotal , but in the second case it could not. (Had we attached a label to the inner block, subtotal could be qualified with that label, instead.)

Some more examples:

When a PL/pgSQL function is declared with output parameters, the output parameters are given $ n names and optional aliases in just the same way as the normal input parameters. An output parameter is effectively a variable that starts out NULL; it should be assigned to during the execution of the function. The final value of the parameter is what is returned. For instance, the sales-tax example could also be done this way:

Notice that we omitted RETURNS real — we could have included it, but it would be redundant.

To call a function with OUT parameters, omit the output parameter(s) in the function call:

Output parameters are most useful when returning multiple values. A trivial example is:

As discussed in Section 38.5.4 , this effectively creates an anonymous record type for the function's results. If a RETURNS clause is given, it must say RETURNS record .

This also works with procedures, for example:

In a call to a procedure, all the parameters must be specified. For output parameters, NULL may be specified when calling the procedure from plain SQL:

However, when calling a procedure from PL/pgSQL , you should instead write a variable for any output parameter; the variable will receive the result of the call. See Section 43.6.3 for details.

Another way to declare a PL/pgSQL function is with RETURNS TABLE , for example:

This is exactly equivalent to declaring one or more OUT parameters and specifying RETURNS SETOF sometype .

When the return type of a PL/pgSQL function is declared as a polymorphic type (see Section 38.2.5 ), a special parameter $0 is created. Its data type is the actual return type of the function, as deduced from the actual input types. This allows the function to access its actual return type as shown in Section 43.3.3 . $0 is initialized to null and can be modified by the function, so it can be used to hold the return value if desired, though that is not required. $0 can also be given an alias. For example, this function works on any data type that has a + operator:

The same effect can be obtained by declaring one or more output parameters as polymorphic types. In this case the special $0 parameter is not used; the output parameters themselves serve the same purpose. For example:

In practice it might be more useful to declare a polymorphic function using the anycompatible family of types, so that automatic promotion of the input arguments to a common type will occur. For example:

With this example, a call such as

will work, automatically promoting the integer inputs to numeric. The function using anyelement would require you to cast the three inputs to the same type manually.

43.3.2.  ALIAS #

The ALIAS syntax is more general than is suggested in the previous section: you can declare an alias for any variable, not just function parameters. The main practical use for this is to assign a different name for variables with predetermined names, such as NEW or OLD within a trigger function.

Since ALIAS creates two different ways to name the same object, unrestricted use can be confusing. It's best to use it only for the purpose of overriding predetermined names.

43.3.3. Copying Types #

%TYPE provides the data type of a variable or table column. You can use this to declare variables that will hold database values. For example, let's say you have a column named user_id in your users table. To declare a variable with the same data type as users.user_id you write:

By using %TYPE you don't need to know the data type of the structure you are referencing, and most importantly, if the data type of the referenced item changes in the future (for instance: you change the type of user_id from integer to real ), you might not need to change your function definition.

%TYPE is particularly valuable in polymorphic functions, since the data types needed for internal variables can change from one call to the next. Appropriate variables can be created by applying %TYPE to the function's arguments or result placeholders.

43.3.4. Row Types #

A variable of a composite type is called a row variable (or row-type variable). Such a variable can hold a whole row of a SELECT or FOR query result, so long as that query's column set matches the declared type of the variable. The individual fields of the row value are accessed using the usual dot notation, for example rowvar.field .

A row variable can be declared to have the same type as the rows of an existing table or view, by using the table_name %ROWTYPE notation; or it can be declared by giving a composite type's name. (Since every table has an associated composite type of the same name, it actually does not matter in PostgreSQL whether you write %ROWTYPE or not. But the form with %ROWTYPE is more portable.)

Parameters to a function can be composite types (complete table rows). In that case, the corresponding identifier $ n will be a row variable, and fields can be selected from it, for example $1.user_id .

Here is an example of using composite types. table1 and table2 are existing tables having at least the mentioned fields:

43.3.5. Record Types #

Record variables are similar to row-type variables, but they have no predefined structure. They take on the actual row structure of the row they are assigned during a SELECT or FOR command. The substructure of a record variable can change each time it is assigned to. A consequence of this is that until a record variable is first assigned to, it has no substructure, and any attempt to access a field in it will draw a run-time error.

Note that RECORD is not a true data type, only a placeholder. One should also realize that when a PL/pgSQL function is declared to return type record , this is not quite the same concept as a record variable, even though such a function might use a record variable to hold its result. In both cases the actual row structure is unknown when the function is written, but for a function returning record the actual structure is determined when the calling query is parsed, whereas a record variable can change its row structure on-the-fly.

43.3.6. Collation of PL/pgSQL Variables #

When a PL/pgSQL function has one or more parameters of collatable data types, a collation is identified for each function call depending on the collations assigned to the actual arguments, as described in Section 24.2 . If a collation is successfully identified (i.e., there are no conflicts of implicit collations among the arguments) then all the collatable parameters are treated as having that collation implicitly. This will affect the behavior of collation-sensitive operations within the function. For example, consider

The first use of less_than will use the common collation of text_field_1 and text_field_2 for the comparison, while the second use will use C collation.

Furthermore, the identified collation is also assumed as the collation of any local variables that are of collatable types. Thus this function would not work any differently if it were written as

If there are no parameters of collatable data types, or no common collation can be identified for them, then parameters and local variables use the default collation of their data type (which is usually the database's default collation, but could be different for variables of domain types).

A local variable of a collatable data type can have a different collation associated with it by including the COLLATE option in its declaration, for example

This option overrides the collation that would otherwise be given to the variable according to the rules above.

Also, of course explicit COLLATE clauses can be written inside a function if it is desired to force a particular collation to be used in a particular operation. For example,

This overrides the collations associated with the table columns, parameters, or local variables used in the expression, just as would happen in a plain SQL command.

   
43.2. Structure of PL/pgSQL   43.4. Expressions

Submit correction

If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.

Advertisement

TechOnTheNet Logo

  • Oracle / PLSQL
  • Web Development
  • Color Picker
  • Programming
  • Techie Humor

clear filter

PostgreSQL Basics

  • AND & OR
  • COMPARISON OPERATORS
  • IS NOT NULL
  • SELECT LIMIT

down caret

PostgreSQL Advanced

  • Alter Table
  • Change Password
  • Comments in SQL
  • Create Table
  • Create Table As
  • Create User
  • Declare Variables
  • Find Users Logged In
  • Grant/Revoke Privileges
  • Primary Key
  • Rename User
  • Unique Constraints

String Functions

  • char_length
  • character_length
  • concat with ||

Numeric/Math Functions

Date/time functions.

  • current_date
  • current_time
  • current_timestamp
  • localtimestamp

Conversion Functions

  • to_timestamp

totn PostgreSQL

PostgreSQL: Declaring Variables

This PostgreSQL tutorial explains how to declare variables in PostgreSQL with syntax and examples.

What is a variable in PostgreSQL?

In PostgreSQL, a variable allows a programmer to store data temporarily during the execution of code.

The syntax to declare a variable in PostgreSQL is:

Parameters or Arguments

Example - declaring a variable.

Below is an example of how to declare a variable in PostgreSQL called vSite .

This example would declare a variable called vSite as a varchar data type.

You can then later set or change the value of the vSite variable, as follows:

This statement would set the vSite variable to a value of 'TechOnTheNet.com'.

Example - Declaring a variable with an initial value (not a constant)

Below is an example of how to declare a variable in PostgreSQL and give it an initial value. This is different from a constant in that the variable's value can be changed later.

This would declare a variable called vSite as a varchar data type and assign an initial value of 'TechOnTheNet.com'.

You could later change the value of the vSite variable, as follows:

This SET statement would change the vSite variable from a value of 'TechOnTheNet.com' to a value of 'CheckYourMath.com'.

Example - Declaring a constant

Below is an example of how to declare a constant in PostgreSQL called vSiteID .

This would declare a constant called vSiteID as an integer data type and assign an initial value of 50. Because this variable is declared using the CONSTANT keyword, you can not change its value after initializing the variable.

previous

Home | About Us | Contact Us | Testimonials | Donate

While using this site, you agree to have read and accepted our Terms of Service and Privacy Policy .

Copyright © 2003-2024 TechOnTheNet.com. All rights reserved.

  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database

PostgreSQL – Variables

In PostgreSQL , a variable is a meaningful name for a memory location that holds a value that can be changed throughout a block or function. A variable is always associated with a particular data type. Before using a variable, you must declare it in the declaration section of a PostgreSQL Block .

Let us better understand the Variables in PostgreSQL to better understand the concept.

The following illustrates the syntax for declaring a variable:

Let’s analyze the above syntax:

  • Variable Name : Specify the name of the variable. It is a good practice to assign a meaningful name to a variable. For example, instead of naming a variable “i” one should use index or counter .
  • Data Type : Associate a specific data type with the variable. The data type can be any valid PostgreSQL data type such as INTEGER , NUMERIC , VARCHAR , and  CHAR .
  • Default Value : Optionally assign a default value to a variable. If you don’t, the initial value of the variable is initialized to NULL .

PostgreSQL Variables Examples

Let us take a look at some of the examples of Variables in PostgreSQL to better understand the concept.

Example 1: Basic Variable Declaration and Usage

postgresql variable assignment

Explanation: In this example, we declared four variables: ‘ counter' , ‘ first_name' , ‘ last_name' , and ‘ payment' . Each variable is initialized with a specific value. The ‘ RAISE NOTICE' statement is used to display the values of these variables.

Example 2: Using System Functions with Variables

postgresql variable assignment

Explanation: In this example, we declared a variable ‘ created_at' and initialized it with the current time using the NOW () function . The ‘ pg_sleep(10)' function pauses the execution for 10 seconds. The ‘ RAISE NOTICE' statements display the value of ‘ created_at' before and after the pause, showing that the time remains the same as it was initialized once.

Important Points About PostgreSQL Variables

Variables declared within a block or function are only accessible within that block or function. Variables can be assigned values using the := operator. Alternatively, you can use the SELECT INTO statement to assign values from queries to variables. When assigning values to variables, ensure that the data types are compatible. PostgreSQL will raise an error if there is a type mismatch. If a variable is not explicitly initialized, its default value is NULL .

Please Login to comment...

Similar reads.

  • postgreSQL-basics

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

How to declare variables in PL/pgSQL stored procedures

Default Author

Rajkumar Raghuwanshi

SUMMARY: This article covers how stored procedures can make use of variables to be more functional and useful. After defining PL/pgSQL, stored procedures, and variables, it provides examples of how variables can be used.

The title of this post makes use of 3 terms: PL/pgSQL, stored procedure, and variable. Let’s start with a basic understanding of them.

PL/pgSQL : An abbreviation for Procedure Language/PostgreSQL. It is a procedural language that provides the ability to perform more complex operations and computations than SQL.

Stored Procedure: A block for SQL statements combined together under a name and saved in database which can be called on multiple times when needed.

Variable: A variable holds a value that can be changed through the block. It is always associated with a datatype. 

Now let’s try to understand these with examples.

Stored procedures include functions, procedures, triggers, and other objects that can be saved in databases. Below is a simple example for a stored procedure “Procedure”:

In this example, an SQL statement, which upon call prints “Procedure example1 called,” is saved under the name example1 and can be called multiple times as needed.

The example has a fixed message which it prints upon call. To make the function more dynamic and useful, we can use different types of variables and assign values to them at compile time as well at run time.

A variable must be declared in the declaration section of the PL/pgSQL block. Declaration syntax for a variable is: “ variable_name data_type [:=value/constant/expression]; ”

Variable_name: This can be any meaningful name or whatever the user wants.

Data_type: PostgreSQL supports data types like integer, numeric, varchar, and text, or it can be a %TYPE or %ROWTYPE. Here is a list of PostgreSQL supported data types: https://www.postgresql.org/docs/current/datatype.html .

Variable Assignment: Any value as accepted by data type, constant, or expression can be assigned to the variable. This part is optional. 

The user can print variable values by using RAISE NOTICE/EXCEPTION and “%” as a placeholder to be replaced by the variable value.

Let’s see an example for variable declaration and display:

The variable can also be of a column type or a row type of a table. These can be declared with data type as %TYPE and %ROWTYPE. Here is an example:

In this example the data type of the variable “eid_var” is declared by reference to the “eid” column’s data type in the “emp” table As output the user wants to return a complete row (all columns) of the “emp” table, so the variable “result” is declared as a reference to a whole row type of the “emp” table.

Another point to notice is that the “result” variable is assigned at runtime by using the result set of SELECT * INTO.

Another way to use %ROWTYPE in PostgreSQL variables is using RECORD as the data type of a variable. Below is the same example as above, but displaying “emp” table data using RECORD type.

In the same way, the user can use variables in other stored procedures like function and triggers.

Reference Links:

https://www.postgresql.org/docs/current/datatype.html

https://www.postgresql.org/docs/current/plpgsql-declarations.html

https://www.postgresql.org/docs/current/sql-createprocedure.html

Popular Links

  • Connecting PostgreSQL using psql and pgAdmin
  • How to use PostgreSQL with Django
  • 10 Examples of PostgreSQL Stored Procedures
  • How to use PostgreSQL with Laravel
  • How to use tables and column aliases...

Featured Links

  • PostgreSQL vs. SQL Server (MSSQL)...
  • The Complete Oracle to PostgreSQL Migration...
  • PostgreSQL vs. MySQL: A 360-degree Comparison...
  • PostgreSQL Replication and Automatic Failover...
  • Postgres on Kubernetes or VMs: A Guide...
  • Postgres Tutorials
  • The EDB Blog
  • White Papers
  • The EDB Docs

Tutorial

EDB Tutorial: How to Configure Databases for EDB JDBC SSL Factory Classes

Elephant Tutorial

EDB Tutorial: How To Run a Complex Postgres Benchmark Easily - Master TPC-C in 3 Short Steps

An overview of postgresql indexes.

Contact us on +86 13022832863 or [email protected].

  • Documentation

PostgreSQL Tutorial: PL/pgSQL Variables

August 4, 2023

Summary : in this tutorial, you will learn various techniques to declare PL/pgSQL variables.

Table of Contents

Introduction to variables in PL/pgSQL

A variable is a meaningful name of a memory location. A variable holds a value that can be changed through the block . A variable is always associated with a particular data type .

Before using a variable, you must declare it in the declaration section of the PL/pgSQL block .

The following illustrates the syntax of declaring a variable.

In this syntax:

  • First, specify the name of the variable. It is a good practice to assign a meaningful name to a variable. For example, instead of naming a variable i you should use index or counter .
  • Second, associate a specific data type with the variable. The data type can be any valid data type such as integer , numeric , varchar , and char .
  • Third, optionally assign a default value to a variable. If you don’t do so, the initial value of the variable is NULL .

Note that you can use either := or = assignment operator to initialize and assign a value to a variable.

The following example illustrates how to declare and initialize variables:

The counter variable is an integer that is initialized to 1

The first_name and last_name are varchar(50) and initialized to 'John' and 'Doe' string constants.

The type of payment is numeric and its value is initialized to 20.5

Variable initialization timing

PostgreSQL evaluates the default value of a variable and assigns it to the variable when the block is entered. For example:

Here is the output:

In this example:

  • First, declare a variable whose default value is initialized to the current time.
  • Second, print out the value of the variable and pass the execution in 10 seconds using the pg_sleep() function.
  • Third, print out the value of the created_at variable again.

As shown clearly from the output, the value of the created_at is only initialized once when the block is entered.

Copying data types

The %type provides the data type of a table column or another variable. Typically, you use the %type to declare a variable that holds a value from the database or another variable.

The following illustrates how to declare a variable with the data type of a table column:

And the following shows how to declare a variable with the data type of another variable:

See the following film table from the sample database:

img

This example uses the type copying technique to declare variables that hold values which come from the film table:

This example declared two variables:

  • The film_title variable has the same data type as the title column in the film table from the sample database .
  • The featured_title has the same data type as the data type of the film_title variable.

By using type copying feature, you get the following advantages:

  • First, you don’t need to know the type of the column or reference that you are referencing.
  • Second, if the data type of the referenced column name (or variable) changes, you don’t need to change the definition of the function.

Variables in block and subblock

When you declare a variable in a subblock which hs the same name as another variable in the outer block, the variable in the outer block is hidden in the subblock.

In case you want to access a variable in the outer block, you use the block label to qualify its name as shown in the following example:

  • First, declare a variable named counter in the outer_block .
  • Next, declare a variable with the same name in the subblock.
  • Then, before entering into the subblock, the value of the counter is one. In the subblock, we increase the value of the counter to ten and print it out. Notice that the change only affects the counter variable in the subblock.
  • After that, reference the counter variable in the outer block using the block label to qualify its name outer_block.counter .
  • Finally, print out the value of the counter variable in the outer block, its value remains intact.

In this tutorial, you have learned the various ways to declare PL/pgSQL variables.

PostgreSQL PL/pgSQL Tutorial

  • BUSINESS (4)
  • MIGRATION (13)
  • PRODUCT (53)
  • TUTORIAL (425)
  • administration
  • optimization
  • quick-start
  • troubleshooting

Copyright (c) 2017 - 2023, Redrock Data Services, Inc. All rights reserved.

PostgreSQL Tutorial

PL/pgSQL – Variables

In PostgreSQL’s PL/pgSQL language, you can declare and use variables for storing and manipulating data within stored procedures, functions, and triggers. PL/pgSQL supports various data types for variables, including the standard SQL data types and custom types defined in your database.

Here’s how you can declare and use variables in PL/pgSQL:

Declaration:

You can declare a variable using the DECLARE statement within the body of your PL/pgSQL code block. You should specify the variable name, data type, and optionally an initial value.

Initialization:

You can initialize a variable when you declare it, or you can set its value later using the := operator.

You can use variables in your PL/pgSQL code like any other SQL expression.

Here’s a simple PL/pgSQL function that demonstrates variable usage:

In this example:

  • We declare a variable result of type INT .
  • We assign the sum of a and b to the result variable.
  • We return the value of the result variable.

postgresql variable assignment

You can call this function like any other SQL function, passing values for a and b , and it will return the sum of the two values.

postgresql variable assignment

Similar Posts

Pl/pgsql – procedures.

In PostgreSQL, a PL/pgSQL procedure is a named block of code written in the PL/pgSQL language that performs a specific task or set of tasks. Procedures are similar to functions, but they do not return values like functions do. Instead, they may perform operations within the database or manipulate data in some way. PL/pgSQL is…

Programming in PostgreSQL Database

In PostgreSQL, you can write stored procedures, functions, and triggers using various programming languages. PostgreSQL supports multiple procedural languages, including: When you create a function or procedure in PostgreSQL, you can specify the language you want to use, and then write the code accordingly. Here’s a basic example of creating a function using PL/pgSQL: sqlCopy…

PL/pgSQL – Cursors

PL/pgSQL supports the use of cursors to retrieve and manipulate result sets from SQL queries in PostgreSQL database. Cursors are particularly useful when you need to work with large result sets or when you want to process rows one by one within a PL/pgSQL function or procedure. Here’s a basic overview of cursors in PL/pgSQL:…

PL/pgSQL – FOR LOOP

In PostgreSQL’s PL/pgSQL, you can use the FOR loop statement to iterate over a sequence of values. FOR loops are useful when you want to perform a specific action a known number of times or iterate over a set of values, such as a range or an array. PL/pgSQL provides several types of FOR loops,…

PL/pgSQL – LOOP Statement

In PostgreSQL’s PL/pgSQL, you can use loop statements to create loops and iterate over a sequence of statements. PL/pgSQL provides several types of loop statements, including LOOP, WHILE, and FOR, each with its own use cases. Here, we’ll focus on the LOOP statement, which creates an unconditional loop that continues until explicitly terminated using the…

PL/pgSQL – IF Statement

In PostgreSQL’s PL/pgSQL, you can use the IF statement to conditionally execute a block of code based on a specified condition. The IF statement allows you to branch your code flow, executing different code blocks depending on whether the condition is true or false. Here’s the basic syntax of the IF statement: IF condition THEN…


On-line Guides

How To Guides

  




 

 

Chapter 11. PL/pgSQL

Using Variables

Variables are used within PL/pgSQL code to store modifiable data of an explicitly stated type. All variables that you will be using within a code block must be declared under the DECLARE keyword. If a variable is not initialized to a default value when it is declared, its value will default to the SQL NULL type.

Note: As you will read later on in the Section called Controlling Program Flow ," there is a type of statement known as the FOR loop that initializes a variable used for iteration. The FOR loop's iteration variable does not have to be pre-declared in the DECLARE section for the block the loop is located within; hence, the FOR loop is the only exception to the rule that all PL/pgSQL variables must be declared at the beginning of the block they are located within.

Variables in PL/pgSQL can be represented by any of SQL's standard data types, such as an INTEGER or CHAR . In addition to SQL data types, PL/pgSQL also provides the additional RECORD data type, which is designed to allow you to store row information without specifying the columns that will be supplied when data is inserted into the variable. More information on using RECORD data types is provided later in this chapter. For further information on standard SQL data types, see the Section called Data Types in Chapter 3 " in Chapter 3; the following is a brief list of commonly used data types in PL/pgSQL:

double precision

Declaration

For variables to be available to the code within a PL/pgSQL code block, they must be declared in the declarations section of the block, which is denoted by the DECLARE keyword at the beginning of the block. Variables declared in a block will be available to all sub-blocks within it, but remember that (as mentioned in the Section called Language Structure " earlier in this chapter) variables declared within a sub-block are destroyed when that sub-block ends, and are not available for use by their parent blocks. The format for declaring a variable is shown in Example 11-11 .

Example 11-11. Declaring a PL/pgSQL variable

As you can see by Example 11-11 , you declare a variable by providing its name and type (in that order), then end the declaration with a semicolon.

Example 11-12 shows the declaration of a variable of the INTEGER data type, a variable of the VARCHAR data type (the value in parentheses denotes that this variable type holds ten characters), and a variable of the FLOAT data type.

Example 11-12. Variable Declarations

You may also specify additional options for a variable. Adding the CONSTANT keyword indicates that a variable will be created as a constant. Constants are discussed later in this section.

The NOT NULL keywords indicate that a variable cannot be set as NULL . A variable declared as NOT NULL will cause a run-time error if it is set to NULL within the code block. Due to the fact that all variables are set to NULL when declared without a default value, a default value must be provided for any variable that is declared as NOT NULL .

The DEFAULT keyword allows you to provide a default value for a variable. Alternatively, you can use the := operator without specifying the DEFAULT keyword, to the same effect.

The following illustrates the use of these options within a variable declaration:

Example 11-13 shows the declaration of a constant variable with the default value of 5, the declaration of a variable with the value of 10 which cannot be set to NULL , and the declaration of a character with the default value of one a .

Example 11-13. Using variable declaration options

The keyword covered in online documentation for PL/pgSQL, which is intended to rename existing variables to new names, does not work at all in PL/pgSQL (as of PostgreSQL 7.1.x). The use of this keyword on an existing variable indiscriminately causes a parsing error. It is therefore not recommended, nor documented in this chapter.

Variable assignment is done with PL/pgSQL's assignment operator ( := ), in the form of left_variable := right_variable , in which the value of the right variable is assigned to the left variable. Also valid is left_variable := expression , which assigns the left-hand variable the value of the expression on the right side of the assignment operator.

Variables can be assigned default values within the declaration section of a PL/pgSQL code block. This is known as default value assignment , and is done by using the assignment operator ( := ) on the same line as the variable's declaration. This topic is discussed in more detail later in this section, but Example 11-14 provides a quick demonstration.

Example 11-14. Default value assignment

It is also possible to use a SELECT INTO statement to assign variables the results of queries. This use of SELECT INTO is different from the SQL command SELECT INTO , which assigns the results of a query to a new table.

Note: To assign the results of a query to a new table within PL/pgSQL, use the alternative SQL syntax CREATE TABLE AS SELECT ).

SELECT INTO is primarily used to assign row and record information to variables declared as %ROWTYPE or RECORD types. To use SELECT INTO with a normal variable, the variable in question must be the same type as the column you reference in the SQL SELECT statement provided. The syntax of SELECT INTO statement is shown in the following syntax:

In this syntax, target_variable is the name of a variable that is being populated with values, and select_clauses consists of any supported SQL SELECT clauses that would ordinarily follow the target column list in a SELECT statement.

Example 11-15 shows a simple function that demonstrates the use of a SELECT INTO statement. The ALIAS keyword is described in the Section called Argument Variables ," later in this chapter. See the Section called Controlling Program Flow " for examples of using SELECT INTO with RECORD and %ROWTYPE variables.

Example 11-15. Using the SELECT INTO statement

Example 11-16 shows the results of the get_customer_id() function when passed the arguments Jackson and Annie . The number returned is the correct ID number for Annie Jackson in the customers table.

Example 11-16. Result of the get_customer_id( ) function

If you wish to assign multiple column values to multiple variables, you may do so by using two comma-delimited groups of variable names and column names, separated from one another by white space. Example 11-17 creates essentially an inverse function to the get_customer_id() function created in Example 11-15 .

Example 11-17. Using SELECT INTO with multiple columns

Example 11-18 shows the results of the get_customer_name() function, when passed an argument of 107.

Example 11-18. Result of the get_customer_name( ) function

Use the special FOUND Boolean variable directly after a SELECT INTO statement to check whether or not the statement successfully inserted a value into the specified variable. You can also use ISNULL or IS NULL to find out if the specified variable is NULL after being selected into (in most situations, this would mean the SELECT INTO statement failed).

FOUND, IS NULL , and ISNULL should be used within a conditional ( IF/THEN ) statement. PL/pgSQL's conditional statements are detailed in the "Controlling Program Flow" section of this chapter. Example 11-19 is a basic demonstration of how the FOUND Boolean could be used with the get_customer_id() function.

Example 11-19. Using the FOUND boolean in get_customer_id( )

Example 11-20 shows that get_customer_id( ) now returns a –1 value when passed the name of a non-existent customer.

Example 11-20. Result of the new get_customer_id( ) function

Argument Variables

PL/pgSQL functions can accept argument variables of different types. Function arguments allow you to pass information from the user into the function that the function may require. Arguments greatly extend the possible uses of PL/pgSQL functions. User input generally provides a function with the data it will either operate on or use for operation. Users pass arguments to functions when the function is called by including them within parentheses, separated by commas.

Arguments must follow the argument list defined when the function is first created. Example 11-21 shows a pair of example function calls from psql .

Example 11-21. Function call examples

Note: The get_author(text) and get_author(integer) functions are discussed later in this chapter.

Each function argument that is received by a function is incrementally assigned to an identifier that begins with the dollar sign ( $ ) and is labeled with the argument number. The identifier $1 is used for the first argument, $2 is used for the second argument, and so forth. The maximum number of function arguments that can be processed is sixteen, so the argument identifiers can range from $1 to $16 . Example 11-22 shows a function that doubles an integer argument variable that is passed to it.

Example 11-22. Directly using argument variables

Referencing arguments with the dollar sign and the argument's order number can become confusing in functions that accept a large number of arguments. To help in functions where the ability to better distinguish argument variables from one another is needed (or just when you wish to use a more meaningful name for an argument variable), PL/pgSQL allows you to create variable aliases .

Aliases are created with the ALIAS keyword and give you the ability to designate an alternate identifier to use when referencing argument variables. All aliases must be declared in the declaration section of a block before they can be used (just like normal variables). Example 11-23 shows the syntax of the ALIAS keyword.

Example 11-23. Syntax of the ALIAS keyword

Example 11-24 creates a simple function to demonstrate the use of aliases in a PL/pgSQL function. The triple_ price() function accepts a floating point number as the price and returns that number multiplied by three.

Example 11-24. Using PL/pgSQL aliases

Now, if we use the triple_ price function within a SQL SELECT statement in a client such as psql , we receive the results shown in Example 11-25 .

Example 11-25. Result of the triple_price( ) function

Returning Variables

PL/pgSQL functions must return a value that matches the data type specified as their return type in the CREATE FUNCTION command that created them. Values are returned with a RETURN statement. A RETURN statement is typically located at the end of a function, but will also often be located within an IF statement or other statement that directs the flow of the function. If a function's RETURN statement is located within one of these control statements, you should still include a return statement at the end of the function (even if the function is designed to never reach that last RETURN statement). The syntax of a RETURN statement is shown in Example 11-26 .

Example 11-26. Syntax of the RETURN statement

For a demonstration of the RETURN statement, examine any PL/pgSQL function example within this chapter.

PL/pgSQL provides variable attributes to assist you in working with database objects. These attributes are %TYPE and %ROWTYPE . Use attributes to declare a variable to match the type of a database object (using the %TYPE attribute) or to match the row structure of a row (with the %ROWTYPE attribute). A variable should be declared using an attribute when it will be used within the code block to hold values taken from a database object. Knowledge of the database object's type is not required when using attributes to declare variables. If an object's type changes in the future, your variable's type will automatically change to that data type without any extra code.

The %TYPE attribute

The %TYPE attribute is used to declare a variable with the data type of a referenced database object (most commonly a table column). The format for declaring a variable in this manner is shown in Example 11-27 .

Example 11-27. Declaring a variable using %TYPE

Example 11-28 shows the code for a function that uses %TYPE to store the last name of an author. This function uses string concatenation with the concatenation operator ( || ), which is documented in a later section. The use of the SELECT INTO statement was discussed earlier in this chapter.

Focus on the use of the %TYPE attribute in Example 11-28 . Essentially, a variable is declared as being the same type as a column within the authors table. SELECT is then used to find a row with a first_name field that matches the name the user passed to the function. The SELECT statement retrieves the value of that row's last_name column and insert it into the l_name variable. An example of the user's input to the function is shown right after Example 11-28 , in Example 11-29 , and more examples of user input can be found later in this chapter.

Example 11-28. Using the %TYPE attribute

Example 11-29 shows the results of using the get_author() function.

Example 11-29. Results of the get_author( ) function

The %ROWTYPE Attribute

%ROWTYPE is used to declare a PL/pgSQL record variable with the same structure as the rows in a table you specify. It is similar to the RECORD data type, but a variable declared with %ROWTYPE will have the exact structure of a table's row, whereas a RECORD variable is not structured and will accept a row from any table.

Example 11-30 overloads the get_author() function that was created in Example 11-28 to accomplish a similar goal. Notice, though, that this new version of get_author() accepts an argument of type integer rather than text , and checks for the author by comparing their id against the passed integer argument.

Notice also that this function is implemented using a variable declared with %ROWTYPE . The use of %ROWTYPE to accomplish a simple task such as this may make it seem overly complicated, but as you learn more about PL/pgSQL, the importance of %ROWTYPE will become more apparent.

The use of the dot ( . ) within the found_author variable in Example 11-30 references a named field value in found_author .

Example 11-30. Using the %ROWTYPE attribute

Observe the use of the asterisk ( * ) for the column list in Example 11-30 . Since found_author is declared with the %ROWTYPE attribute on the authors table, it is created with the same data structure as the authors table. The asterisk can therefore be used to populate the found_author variable with each column value selected from the SELECT INTO statement in Example 11-31 .

Example 11-31. Results of the new get_author( ) function

Concatenation

Concatenation is the process of combining two (or more) strings together to produce another string. It is a standard operation built into PostgreSQL, and may therefore be used directly on variables within a PL/pgSQL function. When working with several variables containing character data, it is an irreplaceable formatting tool.

Concatenation can only be used with character strings. Strings are concatenated by placing the concatenation operator ( || ) between two or more character strings (string literal or a character string variable) that you wish to be combined. This can be used to combine two strings together to form a compound word, and to combine multiple strings together to form complex character string combinations.

Concatenation can only be used in situations where your function requires a string value, such as when a string must be returned (as shown in Example 11-32 ), or when you are assigning a new value to a string variable (as shown in Example 11-33 ).

Example 11-32. Returning a concatenated string

When the words break and fast are passed as arguments to the compound_word() function, the function returns breakfast as the concatenated string:

Example 11-33. Assigning a concatenated value to a string

If you pass the strings Practical PostgreSQL and Command Prompt, Inc. to the function created in Example 11-33 , the function returns Practical PostgreSQL, by Command Prompt, Inc. :

Language Structure Controlling Program Flow

postgresql variable assignment

  Published courtesy of O'Reilly   

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

How to use a postgres variable in the select clause

With MSSQL it's easy, the @ marking the start of all variable names allows the parser to know that it is a variable not a column.

This is useful for things like injecting constant values where a select is providing the input to an insert table when copying from a staging table.

How do you express this for postgres?

Peter Wone's user avatar

2 Answers 2

PostgreSQL isn't as flexible in where and how it allows usage of variables. The closest thing for what you're trying to accomplish likely would be surrounding it in a DO block like so:

Note this is context dependent, and you can find more information in this StackOverflow answer .

Additionally you can create a function that declares variables and returns a value like so:

More information on this approach here .

J.D.'s user avatar

  • 2 This doesn't work, an anonymous DO block cannot return anything. –  user1822 Commented Jan 15, 2021 at 6:53
  • @a_horse_with_no_name I'm not a PostgreSQL expert so I could be wrong, but the answer I linked and referenced it from with 139 upvoted is also wrong? –  J.D. Commented Jan 15, 2021 at 13:57
  • Well, that answer is wrong as well and I am surprised it got so many upvotes despite throwing the error mentioned in one of the comments: " ERROR: query has no destination for result data " –  user1822 Commented Jan 15, 2021 at 14:10
  • @a_horse_with_no_name Interesting, thanks. I'll look for an alternative to correct my answer. –  J.D. Commented Jan 15, 2021 at 14:19
  • 1 Actually it does work for my intended use case. The select statement will be providing rows to an insert statement and in fact this answer leads directly to a useful outcome, so I'll accept it provided JD qualifies it with the extra info and mentions the use case. Also, I have since found that if I create a function around the code this can't return a value BS goes away. –  Peter Wone Commented Jan 16, 2021 at 11:44

SQL has no support for variables, this is only possible in procedural languages (in Postgres that would e.g. be PL/pgSQL).

The way to to this in plain SQL is to use a CTE (which is also a cross platform solution and not tied to any SQL dialect):

like injecting constant values where a select is providing the input to an insert table when copying from a staging table.

Well you don't need a variable for that:

  • Does your second expression work if 'some value' is text? I think it just gets interpreted as a column, no? –  MikeB2019x Commented Mar 8, 2022 at 21:58
  • 'some value' is a text (string) value –  user1822 Commented Mar 8, 2022 at 22:44
  • In case if you still want to use a variable instead of 'some value' (e.g. to re-use it in multiple queries), you can put it like this: select col1, col2, :'my_var' from mytable; - note the single quotes, otherwise it will fail if the value is not alphanumeric word. –  RAM237 Commented Jul 11 at 13:22

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Database Administrators Stack Exchange. Learn more

Sign up or log in

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 .

Not the answer you're looking for? Browse other questions tagged postgresql or ask your own question .

  • The Overflow Blog
  • Battling ticket bots and untangling taxes at the frontiers of e-commerce
  • Ryan Dahl explains why Deno had to evolve with version 2.0
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Do statistical properties of particles violate conservation of energy?
  • In a doubly robust learner, do the covariates need to be the same for the outcome model and the propensity model?
  • Trigger (after delete) restricts from deleting records
  • What prevents applications from misusing private keys?
  • Pressure of water in a pipe submerged in a draining tank
  • What do all branches of Mathematics have in common to be considered "Mathematics", or parts of the same field?
  • How to stop Windows from changing date modified when copying files from network?
  • Why is "the paths" plural in Acts 2:28?
  • On bounded implying totally bounded; Gamelin and Greene
  • Did the French janitor at the University of Hanoi receive a higher base pay than a Vietnamese professor?
  • Capacitor package selection for DC-DC convertor
  • Rearrange these numbers and symbols to make a true equation
  • Time travel, with compensation for planetary position and velocity
  • What is this surface feature near Shackleton crater classified as?
  • Is "UN law" a thing?
  • Arranging people in a jeep.
  • How old were Phineas and Ferb? What year was it?
  • For applying to a STEM research position at a U.S. research university, should a resume include a photo?
  • Ecuador: what not to take into the rainforest due to humidity?
  • Möbius square root function: existence of multiplicative and bounded function
  • Why are swimming goggles typically made from a different material than diving masks?
  • Electric moped PWM MOSFETs failure
  • Creating a deadly "minimum altitude limit" in an airship setting
  • Which materials did Donfeld use to create Wonder Woman's golden lasso in "The Queen and the Thief"?

postgresql variable assignment

Declare Variables in PostgreSQL

Declaring and Assigning Variables in PostgreSQL: A Troubleshooting Guide

Abstract: Having trouble declaring and assigning variables in PostgreSQL? Learn about common error messages and how to troubleshoot them in this guide.

Declaring and Assigning Variables in PostgreSQL: Troubleshooting Guide

In this article, we will explore how to declare and assign variables in PostgreSQL, as well as troubleshoot common issues that may arise. We will cover key concepts, applications, and the significance of declaring and assigning variables in PostgreSQL. This guide is aimed at those who have some experience with PostgreSQL and are looking to deepen their understanding of this important feature.

Key Concepts

In PostgreSQL, variables are used to store values that can be referenced and used in SQL statements. There are two types of variables in PostgreSQL: plpgsql variables and sql variables. plpgsql variables are used in PL/pgSQL functions and procedures, while sql variables are used in SQL statements.

To declare a variable in PostgreSQL, you can use the DECLARE statement followed by the variable name and data type. For example:

To assign a value to a variable, you can use the := operator. For example:

Troubleshooting Common Issues

One common issue that may arise when trying to declare and assign a variable in PostgreSQL is the following error message:

This error occurs because the := operator is not supported in sql variables. Instead, you should use the = operator. For example:

Applications and Significance

Declaring and assigning variables in PostgreSQL is an important feature that has many applications. For example, you can use variables to store intermediate results in complex queries, or to pass values between different parts of a PL/pgSQL function or procedure. By understanding how to declare and assign variables in PostgreSQL, you will be able to write more efficient and effective SQL statements.

  • Variables in PostgreSQL are used to store values that can be referenced and used in SQL statements.
  • There are two types of variables in PostgreSQL: plpgsql variables and sql variables.
  • To declare a variable in PostgreSQL, use the DECLARE statement followed by the variable name and data type.
  • To assign a value to a variable, use the = operator for sql variables and the := operator for plpgsql variables.
  • Understanding how to declare and assign variables in PostgreSQL is important for writing efficient and effective SQL statements.
  • PostgreSQL PL/pgSQL Declarations
  • PostgreSQL PL/pgSQL Variables
  • PostgreSQL PL/pgSQL SQL Statements

Tags: :  PostgreSQL variables SQL database development

Latest news

  • Using custom functions with apply() in Pandas DataFrame
  • Python: Reading CSV File with Link and Timestamp
  • Resending Requests: Handling Non-POST Methods on Your Website
  • Clear Clipboard Data in Excel using VBA: The Need for VBACode
  • Creating Two Azure Functions with One Param and Another Without
  • Setting up Bi-directional Replication between Two PostgreSQL Servers on Windows OS
  • Instagram API: Unable to Get Code for Business Login
  • Managing Clothing Items in Next.js Project: Add, Remove, Update
  • Elementor Lightbox Conflict with GTM: Image Click Not Working Correctly
  • Restricting Access to Specific Azure DevOps Boards for External Consultants
  • Handling CircuitBreaker and Valid Request Body Exceptions in Small Spring API Project
  • Migrating MariaDB 10.4.24 Server: Local Computer, Different Sizes Rows
  • Spring Kafka Listener: Handling Offsets with Manual Immediate Acknowledgement in Batch Mode
  • Converting MaxPool Big Kernels to Equivalent Stacks of MaxPool Small Kernels: A Solution for ONNX Models
  • Remove Duplicates from Nested JSON Array using Jolt Spec
  • Reducing Inferencing Costs in LLM Applications: A Translation from Hindi
  • Building a POC: Converting Natural Language Queries to Elasticsearch Query DSL using Open-Source LLM Model
  • Customizing DxSimpleItem in Devextreme: A Guide to v-my-directive
  • Upgrading from Version 2.2.16 to 2.4.8 of Your Software: The Best Way to Migrate and Utilize MilvusPlus Features
  • Backup Room Entity with Date Type in Firebase Realtime Database using Kotlin
  • Spring Boot: Unable to Resolve Dependencies with webFlux and Project Reactor on macOS M2
  • Viewing Installed Python Library Versions in Docker Terminal: An Alternative to Docker Desktop GUI
  • Error Resolving Type Entity i10 in Angular: Upgrading from Version 16 to 17.3.8
  • Step-by-Step Guide: Deploying a MERN Stack Application with Specific Project Structure
  • Identifying Palindromes: Overcoming Heap Buffer Overflow Runtime Errors on Leetcode
  • Simulating a FIFO (First-In-First-Out) Queue in R
  • Deploying Databricks using Microsoft-Hosted Agent with Private Endpoint
  • Fixing Inaccessible Image in Azure Container Instance using az-cli
  • Creating Custom Highlight Text Search in QML PDF Reader using Qt and PdfMultiPageView
  • JAXB2-Maven-Plugin fails to generate Enums: A Solution
  • Using Git: Operators for Specifying Commit Message
  • Next.js 14: Static Site Generation (SSG) Authentication using Clerk
  • Fixing VideoCompressionFailedError in Flutter using VideoCompressionPlus
  • Extracting Day, Week, and DateTime from GeneralDate in Data Bricks
  • Understanding PostgreSQL MVCC: Xmin and Xmax

Home » PostgreSQL PL/pgSQL » PL/pgSQL Select Into

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:

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:

In this example:

  • First, declare a variable called actor_count that stores the number of actors from the actor table.
  • Second, assign the number of actors to the actor_count using the select into statement.
  • Third, display a message that shows the value of the actor_count variable using the raise notice statement.

2) Using the select into with multiple variables

The following example uses the select into statement to assign the first and last names of the actor id 1 to two variables:

How it works.

First, declare two variables v_first_name and v_last_name with the types varchar :

Second, retrieve the first_name and last_name of the actor id 1 from the actor table and assign them to the v_first_name and v_last_name variables:

Third, show the values of v_first_name and v_last_name variables:

Because we assign data retrieved from the first_name and last_name columns of the actor table, we can use the type-copying technique to declare the v_first_name and v_last_name variables:

  • Use the select into statement to select data from the database and assign it to a variable.
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Declaring and assigning values to variables in PostgreSQL

First of all, I'm a total beginner in SQL. I have a table with 50+ columns, and now I'm doing calculations (on created temp table), but in some formulas, I got parameters, for example: A = 3

(A*(Column5 + Column7))/2

So, what is the best way to assign a value to a parameter?

This is what I was thinking about

But I don't know how implementing it.

user272735's user avatar

  • "assign a value to a parameter and use it later". I don't understand this. Are you asking about the scripting language? Are you asking about a way to define a function? When you are executing a single query, there is no "later". –  Gordon Linoff Commented Jul 20, 2017 at 10:58
  • My bad, sorry. I need to use it in a query or multiple queries, but I'm not sure if I need it assign for each query again or not. As I said, I'm a total beginner. I need help with calculating that formula with parameters, there would be everything from start to the end. –  jovicbg Commented Jul 20, 2017 at 11:04

2 Answers 2

The with option essentially creates a temp table that you can reference in a sql statement within the same transaction.

Your best bet is to create a function and then pass it the value of the parameter at run time. eg.

Then use this in your query like:

Gurmokh's user avatar

As I could understand you want to store values using variables. This is already answered here : How to declare a variable in a PostgreSQL query

There are many solutions there, but I particularly like using a WITH clause as pointed in one of the answers, when using plain SQL. For more fancy things, you should write proper stored procedures.

Pedreiro's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

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 .

Not the answer you're looking for? Browse other questions tagged sql postgresql parameters or ask your own question .

  • The Overflow Blog
  • Battling ticket bots and untangling taxes at the frontiers of e-commerce
  • Ryan Dahl explains why Deno had to evolve with version 2.0
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • What if something goes wrong during the seven minutes of terror?
  • Is math a bad discipline for teaching jobs or is it just me?
  • Is "UN law" a thing?
  • Möbius square root function: existence of multiplicative and bounded function
  • Structure of ~から~と
  • Which materials did Donfeld use to create Wonder Woman's golden lasso in "The Queen and the Thief"?
  • Results from Strahler order/Stream rank (order) "cut" into squares - why?
  • If a body in free fall, according to general relativity is weightless, that is, not experiencing force, how does the object gain kinetic energy?
  • Choosing a relative large density subsequence from a low density sequence
  • Cryptic crossword: London calling
  • Is this misleading "convenience fee" legal?
  • Easyjet denied EU261 compensation for flight cancellation during Crowdstrike: Any escalation or other recourse?
  • How can I understand op-amp operation modes?
  • Difference of infinite measures
  • Trigger (after delete) restricts from deleting records
  • What do all branches of Mathematics have in common to be considered "Mathematics", or parts of the same field?
  • Is there a way to search by Middle Chinese rime?
  • In a doubly robust learner, do the covariates need to be the same for the outcome model and the propensity model?
  • Is there a good explanation for the existence of the C19 globular cluster with its very low metallicity?
  • Rearrange these numbers and symbols to make a true equation
  • Adverb for Lore?
  • White to play and mate in 3 moves..what are the moves?
  • Why do only 2 USB cameras work while 4 USB cameras cannot stream at once?
  • Does a cube under high pressure transform into a ball?

postgresql variable assignment

How to Declare a Variable in a PostgreSQL Query

  • PostgreSQL Howtos
  • How to Declare a Variable in a …

Declare a Variable in a PostgreSQL Query

Use with clause to declare a variable in a postgresql query, use postgresql procedural language to declare a variable in a postgresql query, use dynamic config settings to declare a variable in a postgresql query.

How to Declare a Variable in a PostgreSQL Query

A variable is a temporary allocation of memory in a program to store data that is declared using a particular data type. The data on the variable is discarded once the execution is complete and persistent storage is required to retrieve the data when required.

In this tutorial, we will learn the different ways we can use to create a variable in PostgreSQL and use the variable to execute a query on the database.

Use the command below to log in to the PostgreSQL server.

Enter your password on the prompt that opens and press the Enter button on your keyboard.

Create a database with the name variable_db , which we will use to create a table for testing purposes.

Connect to the database we have just created using the following command.

Connecting to the database, we have just created ensures that any data definition language or manipulation language we execute affects only the variable_db database.

Create a table named vehicle that contains the fields id , vehicle_name , vehicle_type , vehicle_model , and vehicle_price .

The vehicle_name , vehicle_type , and vehicle_model fields are type string , while id and vehicle_price fields are type integer .

Insert three records into the table providing the name, type, model, and price for each instance of a vehicle you add.

Copy and paste the SQL command below on your terminal and press Enter on your keyboard.

We will use the data in the table we have created above to learn the different ways we can create a variable and use the variable to execute queries.

Copy and paste the following code on your terminal and press the Enter button on your keyboard.

The WITH clause allows us to create temporary tables and add a select query combined with an alias to create a temporary variable of a column.

The alias uses the keyword AS followed by a variable name containing a descriptive name to avoid confusion during execution.

The temporary table prices contain a temporary variable holding the value 7000000 ; we use the temporary variable to find which vehicles have that price in all the tables. The following is the result of the query.

To create a procedural language, create a file named procedure.sql and write the following procedure into the file. You can copy and paste the code into the file.

The procedure creates a variable named price that holds a value of 70000000 . We will use this variable to filter the vehicles priced at that value.

The query result will be stored in a temporary table named expvehicles . The final statement of the procedure executes a select query that returns all the vehicles priced at 7000000 .

Copy and paste the command below into your terminal to execute this file, and press the Enter button on your keyboard.

The above command returns a table containing names of vehicles but not that the table is temporary, and the data will be lost after the execution.

We use the set keyword to declare variables at the session level or local level in dynamic config settings.

A variable declared at the session-level uses the session keyword, while a variable set at the local level uses the local keyword.

Set a session variable named price using the following command. Copy and paste the code into your terminal and press the Enter button.

Execute a query that uses the variable we have declared to find vehicles priced at 7000000 . Use the following code to realize the above task.

The following is the result of executing the above query.

David Mbochi Njonge avatar

David is a back end developer with a major in computer science. He loves to solve problems using technology, learning new things, and making new friends. David is currently a technical writer who enjoys making hard concepts easier for other developers to understand and his work has been published on multiple sites.

Related Article - PostgreSQL Variable

  • How to Print Variable in PostgreSQL
  • How to Use Variables in PostgreSQL

EDUCBA

PostgreSQL Variables

Sohel Sayyad

Updated May 12, 2023

PostgreSQL Variables

Introduction to PostgreSQL Variables

The PostgreSQL variable is a convenient name or an abstract name given to the memory location. The variable always has a particular data-type give to it, like boolean, text, char, integer, double precision, date, time, etc. They are used to store the data which can be changed. The PostgreSQL variables are initialized to the NULL value if they are not defined with a DEFAULT value. We can modify the value stored within the variable by using the function or code block. We can store the data temporarily in the variable during the function execution.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Consider the following syntax to declare a variable:

Explanation:

  • var_name: The variable name to assign.
  • CONSTANT: This is an optional component. If we have defined the CONSTANT, we can not change the variable’s value once the variable has been initialized.
  • data-type: The variable data-type to assign.
  • NOT NULL: This is an optional component. If we have defined the NOT NULL, then the variable can not have a NULL value.
  • initial_value: This is an optional component. By using this, we can initialize the variable while creating the variable. If we have not defined the initial_value, then the variable will be assigned with the NULL value.

How to Initialize Variables in PostgreSQL?

There are various ways to initialize the variables that are given as follows:

1. While the creation

We can initialize the variable while creating the variable by giving an initial value.

Consider the following example to understand the variable initialization.

The above example would declare a PostgreSQL variable of name num_of_students having initial_value as 100 and data-type as an integer.

2. After creation

We can declare a variable first, and then we can initialize the variable.

Consider the following example to understand the variable initialization after creation.

The above example would declare a PostgreSQL variable of name num_of_students having data-type as an integer.

Now we will initialize the variable by using the following statement:

The above statement would initialize a PostgreSQL variable of name num_of_students with a value of 300.

How to Declare Variables in PostgreSQL?

There are various ways to declare the variable that is given as follows:

1. DECLARE with initial_value

Consider the following example to understand the variable declaration with initial_value.

The above example would declare a PostgreSQL variable of name name_of_student having data-type as VARCHAR and initial_value as ‘John’.

2. DECLARE without initial_value

Consider the following example to understand the variable declaration without an initial value.

The above example would declare a PostgreSQL variable of name name_of_student having data-type as VARCHAR.

3. DECLARE CONSTANT variable

Consider the following example to understand the variable declaration with an initial value and as a CONSTANT.

The above example would declare a PostgreSQL variable of name name_of_student having data-type as VARCHAR and having an initial value as ‘John’, which will be changed further as it is specified as CONSTANT.

How do Variables work?

  • All of the PostgreSQL variables we use in the function must be defined within the DECLARE keyword.
  • During the execution of the function, we can temporarily store the data in the variable.
  • We can modify the data stored within the variable.
  • We cannot change the variable’s value if any of the PostgreSQL variables is defined as the CONSTANT.
  • If a PostgreSQL variable is not specified as CONSTANT, we can declare it with a default value and change it later as necessary.

Examples of PostgreSQL Variables

Given below are the examples:

Gives initial value to a PostgreSQL variable.

a. Without DEFAULT keyword

Consider the following function of the name:

Now we will execute the above function.

Illustrate the following SQL statement and snapshot the result of the above function.

postgreSQL Variables 1

b. With default keyword

With default keyword

c. CONSTANT variable

  • without DEFAULT keyword

without default keyword

  • With default keyword

Illustrate the following SQL statement and snapshot to understand the result of the above function:

postgreSQL Variables 3

Gives a value to a PostgreSQL variable after declaration.

Illustrate the following SQL statement and a snapshot of the above function:

postgreSQL Variables 4

Recommended Articles

We hope that this EDUCBA information on “PostgreSQL Variables” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  • PostgreSQL Triggers
  • HAVING PostgreSQL
  • PostgreSQL SPLIT_PART()
  • PostgreSQL EXTRACT()

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy .

Forgot Password?

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Quiz

Explore 1000+ varieties of Mock tests View more

Submit Next Question

🚀 Limited Time Offer! - 🎁 ENROLL NOW

IMAGES

  1. How to Declare a Variable in PostgreSQL

    postgresql variable assignment

  2. How to Declare a Variable in PostgreSQL

    postgresql variable assignment

  3. PostgreSQL

    postgresql variable assignment

  4. How to Declare a Variable in PostgreSQL

    postgresql variable assignment

  5. How to Declare a Variable in PostgreSQL

    postgresql variable assignment

  6. SQL : How to declare a variable in a PostgreSQL query

    postgresql variable assignment

COMMENTS

  1. PL/pgSQL Variables

    variable_name data_type [= expression]; Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql) In this syntax: First, specify the name of the variable. It is a good practice to assign a meaningful name to a variable. For example, instead of naming a variable i you should use index or counter. Second, associate a specific data type with the ...

  2. PostgreSQL: Documentation: 16: 43.5. Basic Statements

    An assignment of a value to a PL/pgSQL variable is written as:. variable { := | = } expression; . As explained previously, the expression in such a statement is evaluated by means of an SQL SELECT command sent to the main database engine. The expression must yield a single value (possibly a row value, if the variable is a row or record variable).

  3. How do you use variables in a simple PostgreSQL script?

    16. Here's an example of using a variable in plpgsql: create table test (id int); insert into test values (1); insert into test values (2); insert into test values (3); create function test_fn() returns int as $$. declare val int := 2; begin.

  4. PostgreSQL: Documentation: 16: 43.3. Declarations

    newname ALIAS FOR oldname; . The ALIAS syntax is more general than is suggested in the previous section: you can declare an alias for any variable, not just function parameters. The main practical use for this is to assign a different name for variables with predetermined names, such as NEW or OLD within a trigger function.. Examples: DECLARE prior ALIAS FOR old; updated ALIAS FOR new;

  5. PostgreSQL: Declaring Variables

    This PostgreSQL tutorial explains how to declare variables in PostgreSQL with syntax and examples. In PostgreSQL, a variable allows a programmer to store data temporarily during the execution of code. ... The name to assign to the variable. CONSTANT Optional. If specified, the value of the variable can not be changed after the variable has been ...

  6. PostgreSQL

    Default Value: Optionally assign a default value to a variable. If you don't, the initial value of the variable is initialized to NULL. PostgreSQL Variables Examples. Let us take a look at some of the examples of Variables in PostgreSQL to better understand the concept. Example 1: Basic Variable Declaration and Usage

  7. How to declare variables in PL/pgSQL stored procedures

    Variable Assignment: Any value as accepted by data type, constant, or expression can be assigned to the variable. This part is optional. ... Another way to use %ROWTYPE in PostgreSQL variables is using RECORD as the data type of a variable. Below is the same example as above, but displaying "emp" table data using RECORD type. ...

  8. PostgreSQL Tutorial: PL/pgSQL Variables

    The counter variable is an integer that is initialized to 1. The first_name and last_name are varchar(50) and initialized to 'John' and 'Doe' string constants.. The type of payment is numeric and its value is initialized to 20.5. Variable initialization timing. PostgreSQL evaluates the default value of a variable and assigns it to the variable when the block is entered.

  9. PL/pgSQL

    Here's how you can declare and use variables in PL/pgSQL: Declaration: You can declare a variable using the DECLARE statement within the body of your PL/pgSQL code block. You should specify the variable name, data type, and optionally an initial value. Initialization: You can initialize a variable when you declare it, or you can set its value ...

  10. Practical PostgreSQL

    Variable assignment is done with PL/pgSQL's assignment operator (:=), ... It is a standard operation built into PostgreSQL, and may therefore be used directly on variables within a PL/pgSQL function. When working with several variables containing character data, it is an irreplaceable formatting tool.

  11. postgresql

    With MSSQL it's easy, the @ marking the start of all variable names allows the parser to know that it is a variable not a column. This is useful for things like injecting constant values where a select is providing the input to an insert table when copying from a staging table. declare @foo varchar(50) = 'bar'; select @foo;

  12. Declaring and Assigning Variables in PostgreSQL: A Troubleshooting Guide

    To declare a variable in PostgreSQL, use the DECLARE statement followed by the variable name and data type. To assign a value to a variable, use the = operator for sql variables and the := operator for plpgsql variables. Understanding how to declare and assign variables in PostgreSQL is important for writing efficient and effective SQL statements.

  13. PL/pgSQL SELECT INTO Statement

    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.

  14. Declaring and assigning values to variables in PostgreSQL

    1. The with option essentially creates a temp table that you can reference in a sql statement within the same transaction. Your best bet is to create a function and then pass it the value of the parameter at run time. eg. CREATE FUNCTION addColumns(. A integer,

  15. How to Declare a Variable in a PostgreSQL Query

    Use WITH Clause to Declare a Variable in a PostgreSQL Query. Copy and paste the following code on your terminal and press the Enter button on your keyboard. The WITH clause allows us to create temporary tables and add a select query combined with an alias to create a temporary variable of a column.

  16. How to Initialize, Declare Variables in PostgreSQL?

    We can initialize the variable while creating the variable by giving an initial value. Consider the following example to understand the variable initialization. Code: DECLARE num_of_students integer : = 100; or. DECLARE num_of_students integer DEFAULT 100; The above example would declare a PostgreSQL variable of name num_of_students having ...