Updated May 22, 2023
Introduction to PostgreSQL EXECUTE
PostgreSQL EXECUTE statement is used to execute the previously created prepared statement, to execute that statement using execute the command, we need to give the name of the prepared statement and the parameter. Prepare statement in PostgreSQL only exist duration of the current session we have used, after session disconnection prepare statement will automatically remove from the database server. We can use the execute command in the prepared statement to select, delete, and insert statement.
Execute (name of prepared statement) [(parameter)]
Parameter
Below is the parameter description syntax of EXECUTE statement in PostgreSQL:
How PostgreSQL EXECUTE Statement works?
Below is the working of EXECUTE statement :
In the below example, we need first to create a prepared statement.
Code:
EXECUTE exe_test(1, 'ABC', 'Mumbai');
PREPARE exe_test (int, text, text) AS INSERT INTO exe_test VALUES($1, $2, $3);
EXECUTE exe_test(1, 'ABC', 'Mumbai');
select * from exe_test;
Output:
In the next example, we will see the prepare statement is only valid in the current session, which we have connected, after disconnecting from the session prepare statement is automatically removed from the database server.
Code:
PREPARE exe_test (int, text, text) AS INSERT INTO exe_test VALUES($1, $2, $3);
EXECUTE exe_test(1, 'ABC', 'Mumbai');
select * from exe_test;
psql -U postgres
EXECUTE exe_test(1, 'ABC', 'Mumbai');
Output:
Examples of PostgreSQL EXECUTE
Given below are the examples mentioned :
Example #1
Insert data into the table by using execute statement.
Below example shows how to insert the data into the table by using execute statement in PostgreSQL.
Code:
PREPARE exe_test (int, text, text) AS INSERT INTO exe_test VALUES($1, $2, $3);
EXECUTE exe_test(2, 'PQR', 'Delhi');
EXECUTE exe_test(3, 'XYZ', 'Pune');
select * from exe_test;
Output:
Example #2
Select data from the table by using execute statement.
Below example shows how to select the data from the table by using execute statement in PostgreSQL.
Code: