EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL Stored Procedures
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

PostgreSQL Stored Procedures

By Priya PedamkarPriya Pedamkar

PostgreSQL Stored Procedures

Introduction to PostgreSQL Stored Procedures

PostgreSQL stored procedures allow us to extend the database’s functionality by creating the user-defined functions using the various languages; it is called a stored procedure in PostgreSQL. A stored procedure is beneficial and important to create our own user-defined functions after creating the function we are using later in applications. We can insert the commit and rollback statement in our procedure, also stored procedure is used to convert into other databases or other databases to PostgreSQL database. The stored procedure does not return any value, or it will return one or more result set.

Syntax of PostgreSQL Stored Procedures

Given below is the syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

1. Syntax of creating a stored procedure in PostgreSQL

CREATE [OR REPLACE] PROCEDURE stored_procedure_name
( [ [ mode_of_argument ] [argument_name] argument_type [ { DEFAULT | } default_expression ] [……………. ,]]}
{ LANGUAGE language_name  | TRANSFORM { FOR TYPE type_name } [ …..,] | [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER
| SET config_parameter { TO value | = value | FROM CURRENT } | AS ‘definition’
| AS ‘object_file’, ‘link_symbol’
}

2. Syntax of call stored procedure in PostgreSQL.

Call stored_procedure_name(parameter list);     -- stored Procedure name which we have calling.

3. Syntax of drop/delete stored procedure in PostgreSQL.

Drop procedure stored_procedure_name();

Below is the parameter description:

  • Create or replace procedure: This is defined as creating a new stored procedure. Replace keyword is used to replace the existing stored procedure with the same name and create a new parameter list.
  • Stored procedure name: Stored procedure name is defined as the name of the stored procedure which we are creating.
  • Mode of argument: This parameter is defined as which mode we are using to create a new stored procedure.
  • Argument name: This is defined as the name of the argument which we have used while creating a stored procedure.
  • Argument type: This is defined as the name of the data type, which we have defined as stored procedure variable.
  • Language name: This parameter is defined as the name of the language we have used at stored procedure creation. Basically, we are using pl/pgsql language to create a stored procedure.
  • Config parameter: This parameter is defined as a set of configuration parameter which we have used at the time of stored procedure creation.
  • Object file: This is nothing but the shared library, which contains the compiled C procedure language.
  • Call: This keyword is used to call the stored procedure in PostgreSQL. We can call a single stored procedure multiple time.
  • Drop: Using the drop keyword, we have dropped the stored procedure.

How Stored Procedures work in PostgreSQL?

  • The main use stored procedure in PostgreSQL is to create a user-defined function; it does not allow to execute of transaction under the function.
  • To overcome the drawback of executing the transaction under the function, we have created a stored procedure.
  • We have executed the transaction in a stored procedure by creating the stored procedure.
  • To create a new stored procedure, we are using a create procedure statement in it.
  • We cannot use commit and rollback in the function; we have used this command in a stored procedure.
  • It does not return any value; if we want to end the stored procedure, we use the RETURN keyword without expressions.
  • If we want to return the value from the stored procedure, we need to use an output parameter in it. The final result of the output parameter will be returned to the caller who was calling the stored procedure.
  • It contains the two-block sections that are declaration and body.
  • The Declaration section is optimal or no need to define, but the body section must be defined in a stored procedure.
  • The body section is always ended with a semicolon (;) after the END keyword in a stored procedure.
  • This block is an optimal label ($$) located at the beginning and ending of the stored procedure.
  • It is created using create a statement and call the stored procedure using the call keyword. Also, we have drop the stored procedure using a drop statement.

Examples

Given below are the examples mentioned:

We are using proc_test table to describe an example of a stored procedure in PostgreSQL as follows.

Below is the data description of the proc_test table.

Code:

\d+ proc_test;
select * from proc_test;

Output:

postgreSQL Stored Procedures 1

Example #1

Create stored procedure using transaction control.

The below example shows that create a new procedure in PostgreSQL are as follows. We have to create the procedure name as sp_test.

Code:

CREATE OR REPLACE PROCEDURE sp_test ()
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO proc_test (company_id, name, address, phone, country) VALUES (1, 'PQR', 'Mumbai', '1234567890', 'India');
INSERT INTO proc_test (company_id, name, address, phone, country) VALUES (2, 'ABC', 'Pune', '1234567890', 'India');
COMMIT;
INSERT INTO proc_test (company_id, name, address, phone, country) VALUES (3, 'XYZ', 'Pune', '1234567890', 'India');
ROLLBACK;
END;
$$;

Output:

postgreSQL Stored Procedures 2

Example #2

Create stored procedure without using transaction control.

The below example shows that create a stored procedure without using the transaction control.

Code:

CREATE OR REPLACE PROCEDURE sp_test1 ()
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO proc_test (company_id, name, address, phone, country) VALUES (11, 'ABC', 'Mumbai', '1234567890', 'India');
INSERT INTO proc_test (company_id, name, address, phone, country) VALUES (12, 'PQR', 'Pune', '1234567890', 'India');
END;
$$;

Output:

postgreSQL Stored Procedures 3

Example #3

Drop stored procedure.

We are dropping a stored procedure name as sp_test1.

Code:

\df
drop procedure sp_test1;

Output:

drop

Example #4

Call stored procedure.

We are calling a stored procedure name as sp_test.

Code:

call sp_test();
select * from proc_test;

Output:

call

Recommended Articles

This is a guide to PostgreSQL Stored Procedures. Here we discuss how stored procedures work in PostgreSQL with programming examples, respectively. You may also have a look at the following articles to learn more –

  1. PostgreSQL ARRAY_AGG()
  2. PostgreSQL UPDATE JOIN
  3. PostgreSQL Like
  4. PostgreSQL CTE
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

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

Let’s Get Started

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

EDUCBA

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

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

Forgot Password?

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

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

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more