Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
PostgreSQL - Function Parameter Modes
Next article icon

PostgreSQL - Function Parameter Modes

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

PostgreSQL provides powerful features that allow developers to pass data between a calling program and a procedure or function. This is achieved through the use of parameters, which are essential for flexible and dynamic database operations. Parameters enable you to supply data to a function or procedure and receive data back, making your database interactions more efficient and versatile.

What are Parameters?

Parameters in PostgreSQL functions and procedures are variables that pass data from the calling program to the function or procedure. There are two types of parameters:

  • Formal Parameters: These are the parameters declared in the function or procedure definition. They define what kind of data the function or procedure will accept and return.
  • Actual Parameters: These are the actual values or variables the calling program passes when invoking the function or procedure.

Parameter Modes in PostgreSQL

A Parameter mode is used to decide the behavior of the parameters. PL/pgSQL supports three parameter modes: 'in', 'out', and 'inout'. By default, a parameter uses the IN mode. 

1. The IN Mode

  • Purpose: The IN mode is used to pass a value to the function or procedure.
  • Behavior: Parameters in IN mode act like constants; they cannot be assigned a new value within the function or procedure.
  • Default Mode: If no mode is specified, PostgreSQL assumes the parameter is in IN mode.

2. The OUT Mode:

  • Purpose: The OUT mode is used to return a value from the function or procedure.
  • Behavior: Parameters in OUT mode act like uninitialized variables that must be assigned a value during the function's execution.
  • Usage: This mode is particularly useful for functions that need to return multiple values.

3. THE INOUT MODE:

  • Purpose: The INOUT mode is a combination of IN and OUT modes.
  • Behavior: Parameters in INOUT mode are initialized with a value passed by the caller and return a possibly modified value after the function's execution. These parameters act like initialized variables.

The following table illustrates the three parameter mode:

INOUTINOUT
Taken by defaultNeed to be specified explicitlyNeed to be specified explicitly
Values are passed to a functionValue is returned by a functionA value is passed to the function which returns another updated value
Behaves like constantsBehaves like an uninitialized variableBehaves like an initialized variable
Values cannot be assignedMust assign a valueShould assign a value

PostgreSQL Function Parameter Modes Examples

Let us look at some of the examples of Function Parameter Modes in PostgreSQL to better understand the concept. For testing, we create a sample table using the below commands to perform examples:

PostgreSQL
CREATE TABLE employees (
   employee_id serial PRIMARY KEY,
   full_name VARCHAR NOT NULL,
   manager_id INT
);
INSERT INTO employees (
   employee_id,
   full_name,
   manager_id
)
VALUES
   (1, 'M.S Dhoni', NULL),
   (2, 'Sachin Tendulkar', 1),
   (3, 'R. Sharma', 1),
   (4, 'S. Raina', 1),
   (5, 'B. Kumar', 1),
   (6, 'Y. Singh', 2),
   (7, 'Virender Sehwag ', 2),
   (8, 'Ajinkya Rahane', 2),
   (9, 'Shikhar Dhawan', 2),
   (10, 'Mohammed Shami', 3),
   (11, 'Shreyas Iyer', 3),
   (12, 'Mayank Agarwal', 3),
   (13, 'K. L. Rahul', 3),
   (14, 'Hardik Pandya', 4),
   (15, 'Dinesh Karthik', 4),
   (16, 'Jasprit Bumrah', 7),
   (17, 'Kuldeep Yadav', 7),
   (18, 'Yuzvendra Chahal', 8),
   (19, 'Rishabh Pant', 8),
   (20, 'Sanju Samson', 8);

The table is:

Sample Table

Example 1: Using IN, OUT and INOUT Parameters

The following function is created to find the name of the employee along with its manager id given the employee id and its manager id. 

Query:

CREATE OR REPLACE FUNCTION get_stats(
  IN eid INT,
  OUT name VARCHAR,
  INOUT mid INT)
LANGUAGE plpgsql
AS $$
BEGIN
  SELECT full_name, manager_id
  INTO name, mid
  FROM employees
  WHERE employee_id = eid
    AND manager_id = mid;
END; $$;

To call this function, we need to provide employee id and then manager id. As an example,

SELECT * FROM get_stats(2,1);

Output:

PostgreSQL Function Parameter Modes Example

Explanation:

  • IN: 'eid' is an IN parameter because it is only used to pass the employee's ID to the function.
  • OUT: 'name' is an OUT parameter because the function will return the employee's name.
  • INOUT: 'mid' is an INOUT parameter because it is both used as an input and returned as an output.

Example 2: Counting Employees Using an OUT Parameter

The following function is used to get the count of employees in the employee table.

Query:

CREATE OR REPLACE FUNCTION empcount(
  OUT ecount INT)
LANGUAGE plpgsql
AS $$
BEGIN
  SELECT COUNT(*)
  INTO ecount
  FROM employees;
END; $$;

To call this function:

SELECT * FROM empcount();

Output:

PostgreSQL Function Parameter Modes Example

Explanation: The function will return the total count of employees in the table.

Example 3: Swapping Values Using INOUT Parameters

The following function is used to swap the contents of 2 variables

CREATE OR REPLACE FUNCTION swapper(
  INOUT x INT,
  INOUT y INT)
LANGUAGE plpgsql
AS $$
BEGIN
  SELECT x, y INTO y, x;
END; $$;

To call this function :

SELECT * FROM swapper(198, 457);

Output:

PostgreSQL Function Parameter Modes Example

As we need to change the values and then display the changed values, we use INOUT mode.

Explanation: The function will return the swapped values of 'x' and 'y'.


Next Article
PostgreSQL - Function Parameter Modes

A

ashutoshrathi
Improve
Article Tags :
  • Technical Scripter
  • PostgreSQL
  • Technical Scripter 2020
  • PostgreSQL-function

Similar Reads

    PostgreSQL - Function Parameters
    In PostgreSQL, functions provide an efficient way to encapsulate logic, perform calculations, and handle complex tasks within a database. A thorough understanding of PostgreSQL function parameters is essential for writing flexible and optimized functions.In this article, we will analyze different ty
    5 min read
    PostgreSQL - Function Overloading
    In PostgreSQL, it's possible to create multiple functions with the same name, provided that each function has different arguments. This feature, known as function overloading, allows you to define functions that perform similar operations but handle different types or numbers of inputs. PostgreSQL d
    3 min read
    Parameterize an PostgreSQL IN clause
    In PostgreSQL, the IN clause is a powerful tool for filtering data based on a set of specified values. However, when dealing with dynamic values or user input, it's essential to parameterize the IN clause to prevent SQL injection vulnerabilities and improve query performance. In this article, we'll
    4 min read
    PostgreSQL - NULLIF() Function
    Effectively handling NULL values is important in database management, especially for ensuring data integrity and avoiding errors. PostgreSQL offers several powerful functions, such as NULLIF and COALESCE, to help manage NULL and empty values efficiently. In this article, we will guide us through the
    4 min read
    PostgreSQL String Functions
    PostgreSQL is a powerful, open-source relational database management system that offers a rich set of functions and operators for working with string data. String manipulation is an essential task in many applications, and PostgreSQL provides a variety of built-in functions to make working with text
    8 min read
    PostgreSQL - Generate Columns
    When working with databases, there are scenarios where you need a column’s value to be automatically computed based on other columns. In PostgreSQL, this can be achieved through generated columns. These special columns are calculated based on an expression using other columns in the table. The value
    3 min read
    PostgreSQL - Drop Function
    In PostgreSQL, the DROP FUNCTION statement is essential for removing functions from your database. Let us learn more about the syntax and the detailed examples to ensure you understand how to use this statement effectively.SyntaxDROP FUNCTION [IF EXISTS] function_name(argument_list) [CASCADE | RESTR
    4 min read
    PostgreSQL - ASCII Function
    When working with PostgreSQL, you might need to derive the ASCII (American Standard Code for Information Interchange) code of a character. The PostgreSQL ASCII() function is a handy tool for this purpose. In the case of UTF-8 encoding, the ASCII() function returns the Unicode code point of the chara
    2 min read
    PostgreSQL - FORMAT Function
    The PostgreSQL format() function is a powerful tool for string formatting by allowing developers to insert variables into strings using format specifiers like %s, %I, and %L. This function is especially useful for building dynamic SQL queries and ensuring proper formatting of identifiers. It simplif
    3 min read
    PostgreSQL - Constants
    In PostgreSQL, constants are similar to variables but with a crucial difference: once their value is initialized, it cannot be altered. This immutability is beneficial for several reasons, enhancing both, the readability of SQL queries and reducing maintenance efforts. Here we will look into the syn
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `${editorValue}`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('.suggest-bottom-btn').css("display","none"); $('#suggestion-section-textarea').hide() $('.thank-you-message').css('display', 'flex'); $('.suggestion-section').css('display', 'none'); jQuery('#suggestion-modal-alert').hide(); }, error:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 4 Words and Maximum Words limit is 1000."); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences