Functions in Postgres
-
Functions
Functions are reusable blocks of code that can accept parameters and return a value.
Functions cannot modify data inside database but they can be used to perform calculations, display data etc Advantages:
1. Code Reusability: Functions allow you to write code once and reuse it multiple times, reducing redundancy.
2. Modularity: Functions help in breaking down complex tasks into smaller, manageable pieces.
3. Improved Readability: Functions can make the code more readable and easier to understand.
4. Performance: Functions can optimize performance by reducing the amount of data transferred between the database and application.
5. Security: Functions can encapsulate sensitive logic and restrict direct access to underlying tables.
Examples
Print all data from employee table
CREATE OR REPLACE FUNCTION print_employee()
RETURNS TABLE (id INT, name TEXT, age INT, department TEXT) AS $$
BEGIN
RETURN (SELECT * FROM employee);
END;
$$ LANGUAGE plpgsql;
-- Call as:
SELECT get_employee_count();
Call Function/Procedure from C++
C Code | CPP Code |
---|---|
|
|