Just Learn Code

PostgreSQL Variable Declaration: Mastering Query Flexibility

PostgreSQL Variable Declaration: A Comprehensive Guide

PostgreSQL, also known as Postgres, is a powerful, open-source relational database management system. It is used by organizations of all sizes for its scalability, reliability, and advanced features.

In this article, we will explore the different ways to declare variables in PostgreSQL and how to use them in queries.

Creating a Database and Table

The first step in using PostgreSQL is creating a database and table. A database is a collection of data that is organized in a systematic way, while a table is a collection of related data that is organized into rows and columns.

To create a database in PostgreSQL, you can use the following SQL statement:




To create a table in the newly created database, you can use the following SQL statement:


CREATE TABLE mytable (


name VARCHAR(50),

price NUMERIC(10,2)



This creates a table with three columns: id, name, and price. The id column is of type SERIAL, which means it will automatically generate a unique value for each row inserted into the table.

Inserting Records

Now that we have created a database and table, we can insert records into the table using the INSERT statement:


INSERT INTO mytable (name, price)

VALUES (‘Product 1’, 19.99),

(‘Product 2’, 29.99),

(‘Product 3’, 39.99);


This inserts three records into the table with the names Product 1, Product 2, and Product 3 and their respective prices.

WITH Clause to Declare a Variable

The WITH clause, also known as Common Table Expressions (CTE), can be used in PostgreSQL to declare a variable. The WITH clause allows you to define one or more subqueries that can be referenced within the main query.

The subqueries are materialized into a temporary table, which can then be used as an alias in the main query. Here’s an example of how to use the WITH clause to declare a variable:


WITH mytable_alias AS (

SELECT * FROM mytable

WHERE price > 30


SELECT * FROM mytable_alias;


This creates a temporary table called mytable_alias that contains all records from the mytable table where the price is greater than 30. The SELECT statement then references the mytable_alias table to retrieve the filtered records.

Procedural Language to Declare a Variable

Another way to declare a variable in PostgreSQL is to use a procedural language such as PL/pgSQL. PL/pgSQL is a procedural language that is similar to the SQL language but provides additional features such as control structures and variables.

To declare a variable using PL/pgSQL, you can define a function that returns a single value:





total_price NUMERIC;


SELECT SUM(price) INTO total_price FROM mytable;

RETURN total_price;


$$ LANGUAGE plpgsql;


This creates a function called get_total_price that calculates the total price of all records in the mytable table and returns the value as a numeric data type.

Dynamic Config Settings to Declare a Variable

PostgreSQL also allows you to declare variables using dynamic config settings. Dynamic config settings are session-level or local-level settings that can be set using the SET keyword.

These settings are used to control the behavior of the database server or the client application. Here’s an example of how to declare a variable using dynamic config settings:


SET myvar = ‘hello world’;


This sets a session-level variable called myvar to the value ‘hello world’.

The variable can then be referenced in subsequent queries using the syntax $variable_name.

Using Variables in PostgreSQL Queries

Now that we have declared variables in PostgreSQL, let’s explore how to use them in queries.

Querying with a Declared Variable

To execute a query using a declared variable, you can use the EXECUTE statement. The EXECUTE statement allows you to dynamically execute a query that is stored in a string variable.

Here’s an example of how to filter records by price using a declared variable:


DO $$


min_price NUMERIC := 20;


EXECUTE ‘SELECT name, price FROM mytable WHERE price > $1’ USING min_price;

END $$;


This declares a variable called min_price with a value of 20 and then executes a SELECT statement that retrieves all records from the mytable table where the price is greater than the value of min_price.

Result and Output Formatting

Finally, let’s explore how to format the result and output of PostgreSQL queries. The most common way to format query results is to use the psql command-line tool.

The psql tool allows you to format query results in various ways, such as tabular, CSV, or HTML. To format the result of a query in tabular format, you can use the pset command:


pset format aligned

SELECT * FROM mytable;


This formats the query result in an aligned tabular format where each column is aligned.


In conclusion, PostgreSQL provides various ways to declare variables and use them in queries. We explored the different ways to declare variables, including using the WITH clause, procedural language, and dynamic config settings.

We also learned how to use variables in queries using the EXECUTE statement and how to format query results using the psql tool. With this knowledge, you can leverage the power of PostgreSQL to create powerful and efficient database applications.

PostgreSQL Variable Declaration: A Comprehensive Guide explains the different ways to declare variables in PostgreSQL and how to use them in queries. The article covers creating a database and table, inserting records, declaring variables using the WITH clause, procedural language, and dynamic config settings, using variables in queries, and formatting query results.

The article emphasizes the importance of understanding how to declare and use variables to create powerful and efficient applications in PostgreSQL. By using the techniques outlined in the article, developers can take full advantage of the capabilities of PostgreSQL.

Popular Posts