Sunday, 20 August 2023

How To Call A Stored Procedure/Function From A Trigger Function In Postg...


In this tutorial, you will learn how to call a stored procedure or function from a trigger function in PostgreSQL. This video is designed for developers and database administrators who want to automate tasks or enforce business rules by leveraging the power of triggers in PostgreSQL. We'll begin by explaining what triggers are and how they work within a PostgreSQL database. Next, we'll walk you through the process of creating a trigger function that can invoke a stored procedure or function whenever a specific event occurs in your database, such as an insert, update, or delete operation. You'll see practical examples and gain insights into how this powerful feature can enhance your database applications. By the end of this tutorial, you'll be confident in your ability to implement triggers that call stored procedures or functions, adding a new level of automation and functionality to your PostgreSQL projects.

PostgreSQL triggers, stored procedure PostgreSQL, function PostgreSQL, call stored procedure from trigger, PostgreSQL tutorial, trigger function PostgreSQL, PostgreSQL automation, database triggers, SQL tutorial, PostgreSQL functions, PostgreSQL stored procedures, PostgreSQL 16, SQL triggers, PostgreSQL trigger examples, database management, PostgreSQL development, SQL server, trigger stored procedure, PostgreSQL database, PostgreSQL trigger function tutorial

Please Like, Comment, and Subscribe to my channel. ❤

Working with triggers is fun and learning. There are endless possibilities that can be achieved through Triggers.

This time, I have explained the usage of Triggers to call other stored procedures or functions in PostgreSQL Trigger Functions.


#trigger #procedure #function #postgresql #database


CREATE TABLE students
(
    roll numeric(10,0),
    name character varying(30),
    course character varying(30)
);


CREATE OR REPLACE PROCEDURE 
trigger_proc(in_value1 IN numeric, in_value2 IN numeric, out_result OUT numeric)
LANGUAGE 'plpgsql'
AS $BODY$
Declare
lv_msg CHARACTER varying(100);
Begin
  out_result := in_value1 + in_value2;
exception
when others then
lv_msg := 'Error : '||sqlerrm;
raise notice '%',lv_msg;
end;
$BODY$;


CREATE OR REPLACE FUNCTION 
trigger_func(in_value1 IN numeric, in_value2 IN numeric) returns numeric
LANGUAGE 'plpgsql'
AS $BODY$
Declare
lv_msg CHARACTER varying(100);
out_result numeric (10);
Begin
  out_result := in_value1 + in_value2;
return out_result;
exception
when others then
lv_msg := 'Error :'||sqlerrm;
raise notice '%',lv_msg;
end;
$BODY$;


CREATE OR REPLACE FUNCTION student_logs_trg_func()
    RETURNS TRIGGER
    LANGUAGE 'plpgsql'
AS $BODY$
declare
lv_out_proc numeric(10);
lv_out_func numeric(10);
begin
call trigger_proc(50, 50, lv_out_proc);
lv_out_func := trigger_func(100, 100);
raise notice 'Proc Output: %',lv_out_proc;
raise notice 'Func Output: %',lv_out_func;
return new;
end;
$BODY$;


CREATE TRIGGER student_trg
    BEFORE INSERT OR DELETE OR UPDATE 
    ON students
    FOR EACH ROW
    EXECUTE FUNCTION student_logs_trg_func();

Insert into students values (1, 'Akram', 'MCA');


How To Call A Stored Procedure/Function From A Trigger Function In PostgreSQL
How To Call A Stored Procedure From A Trigger Function
Trigger Function In PostgreSQL
How To Call Stored Function From Trigger Function
Trigger In PostgreSQL
Call Procedure From Trigger
Call Function From Trigger
Procedure Call From Trigger In PostgreSQL
Function Call From Trigger In PostgreSQL
PostgreSQL Triggers
Triggers
Trigger Example PostgreSQL
How To Triggers PostgreSQL

Sunday, 13 August 2023

How To Use/Create Temporary/Temp Tables In PostgreSQL Procedure/Function...



🚀 Master PostgreSQL Temp Tables with this comprehensive guide! Temporary tables are a game-changer when handling intermediate data or complex queries in PostgreSQL. In this video, I'll walk you through:

🔸 Creating Temporary Tables in PostgreSQL
🔸 The differences between local and global temp tables
🔸 How to effectively use temp tables within procedures and functions
🔸 Best practices for managing and dropping temp tables
🔸 Real-world examples to enhance your SQL skills

Whether you're a seasoned database administrator or a developer looking to optimize your SQL queries, this tutorial will give you the tools you need to handle temporary data with ease.

💡 Don't miss out! Boost your database management skills today by learning how to leverage temp tables in PostgreSQL.

Got questions? 🤔 Drop them in the comments below, and let’s discuss!

#PostgreSQL #SQL #DatabaseManagement #TempTables #GlobalTempTables #Programming #TechTips #Coding #SoftwareDevelopment #DataManagement


PostgreSQL, temp tables, temporary tables, global temp tables, SQL, stored procedures, functions, database management, SQL performance, PostgreSQL tutorial, database optimization, SQL best practices, SQL queries, PostgreSQL procedures

Please Like, Comment, and Subscribe to my channel. ❤



-- Global Temporary Tables Usage In PostgreSQL Procedure/Function
-- How To Use Temporary Tables In PostgreSQL Procedure/Function
create or replace procedure temp_tables_proc()
    language plpgsql
    as $$
declare
v_count numeric(10);
begin
create temp table temp_tables(name character varying(100)) on commit preserve rows;
insert into temp_tables values ('Mumbai');
insert into temp_tables values ('Pune');
select count(*) into v_count from temp_tables;
raise notice 'Records : %', v_count;
drop table temp_tables;

exception
when others then
raise notice 'Error : %', substr (sqlerrm, 1, 100);
end;
$$;

call temp_tables_proc();

Saturday, 12 August 2023

What Are Global Temporary Tables And Temp Tables In PostgreSQL Database ...


🔍 Curious about Temporary Tables in PostgreSQL? Whether you're dealing with complex data processing or just need a temporary storage solution, understanding temp tables can significantly boost your database management skills.

In this video, we’ll cover:

  • 🤔 What are Global Temporary Tables and how they differ from standard temp tables.
  • 🛠️ Step-by-step guide on creating and using temp tables in PostgreSQL.
  • 🚀 Best practices for using temp tables effectively within your database environment.
  • 💼 Real-life examples to demonstrate the use cases of temp tables.

This tutorial is perfect for developers, database administrators, and anyone looking to optimize their PostgreSQL database performance.

📈 Level up your PostgreSQL knowledge and start using temp tables like a pro. Don’t forget to leave your thoughts and questions in the comments below!

#PostgreSQL #SQL #Database #TempTables #GlobalTempTables #DataManagement #Programming #SoftwareDevelopment #TechTips


PostgreSQL, Temp Tables, Global Temporary Tables, SQL Tutorial, Database, Database Tips, SQL Functions, Temporary Tables



Please Like, Comment, and Subscribe to my channel. ❤




-- Global Temporary Tables In PostgreSQL Database

create temporary table temp_location
(
city varchar(50),
street varchar(40)
) on commit delete rows;

select * from temp_location;


create temp table temp_cities
(
name character varying(100)
) on commit delete rows;


select * from temp_cities;

drop table temp_cities;

begin transaction;

insert into temp_cities values ('Mumbai');

insert into temp_cities values ('Pune');

commit;


create temp table temp_cities
(
name character varying(100)
) on commit preserve rows;

begin transaction;
create temp table temp_cities
(
name character varying(100)
) on commit drop;

select * from temp_cities;

Sunday, 23 July 2023

Why pgAgent Job Is Not Working || How To Check pgAgent Job Working Or No...



Are your pgAgent jobs in PostgreSQL not working as expected? This video is designed to help you diagnose and resolve issues related to pgAgent job failures. We walk you through the most common reasons why pgAgent jobs might not be running and provide detailed steps on how to check their status using pgAdmin.

First, we explore the various factors that can cause pgAgent jobs to fail, such as configuration errors, permission issues, and server-side problems. Then, we demonstrate how to verify whether your jobs are running correctly by inspecting job logs, job schedules, and job definitions.

Additionally, this tutorial offers troubleshooting tips to fix common issues and ensure that your jobs execute reliably. We also share best practices for monitoring and maintaining your pgAgent jobs, so you can automate your PostgreSQL tasks with confidence.

Whether you're a database administrator, developer, or PostgreSQL enthusiast, this video will equip you with the knowledge you need to keep your pgAgent jobs running smoothly.


pgAgent job not working, check pgAgent job, PostgreSQL pgAgent, troubleshoot pgAgent job, pgAdmin job scheduling, pgAgent job failure, pgAgent troubleshooting, PostgreSQL automation, pgAgent best practices, PostgreSQL job monitoring
Please Like, Comment, and Subscribe to my channel. ❤


create table test_job (id numeric, time_stamp timestamp default current_timestamp);

SELECT * FROM test_job;

delete FROM test_job;

call public.testing_job_proc();

CREATE OR REPLACE PROCEDURE public.testing_job_proc()
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
lv_id numeric;
BEGIN
begin
select coalesce(max(id),0)+1 into lv_id from test_job;
exception when others then 
lv_id := 0;
end;
Insert into test_job(id) values(lv_id);
END;
$BODY$;


DO $$
DECLARE
    jid integer;
    scid integer;
BEGIN
-- Creating a new job
INSERT INTO pgagent.pga_job(
    jobjclid, jobname, jobdesc, jobhostagent, jobenabled
) VALUES (
    1::integer, 'Test_Job'::text, 'Test Job'::text, ''::text, true
) RETURNING jobid INTO jid;

-- Steps
-- Inserting a step (jobid: NULL)
INSERT INTO pgagent.pga_jobstep (
    jstjobid, jstname, jstenabled, jstkind,
    jstconnstr, jstdbname, jstonerror,
    jstcode, jstdesc
) VALUES (
    jid, 'Step1'::text, true, 's'::character(1),
    ''::text, 'postgres'::name, 'f'::character(1),
    'call public.testing_job_proc();'::text, 'Step1 Test Job Proc'::text
) ;

-- Schedules
-- Inserting a schedule
INSERT INTO pgagent.pga_schedule(
    jscjobid, jscname, jscdesc, jscenabled,
    jscstart, jscend,    jscminutes, jschours, jscweekdays, jscmonthdays, jscmonths
) VALUES (
    jid, 'Scheduler1'::text, ''::text, true,
    '2023-07-23 20:00:00+05:30'::timestamp with time zone, '2023-07-31 20:00:00+05:30'::timestamp with time zone,
    -- Minutes
    '{t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t}'::bool[]::boolean[],
    -- Hours
    '{t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t}'::bool[]::boolean[],
    -- Week days
    '{t,t,t,t,t,t,t}'::bool[]::boolean[],
    -- Month days
    '{t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t}'::bool[]::boolean[],
    -- Months
    '{t,t,t,t,t,t,t,t,t,t,t,t}'::bool[]::boolean[]
) RETURNING jscid INTO scid;
END
$$;

Friday, 21 July 2023

How To Resolve/Fix The pgAdmin 4 server could not be contacted || Postgr...


Are you encountering the frustrating "pgAdmin 4 server could not be contacted" error when trying to connect to your PostgreSQL database? This video is designed to help you troubleshoot and resolve this common issue, ensuring that you can access your database without any hitches.

In this tutorial, we delve into the most common reasons why this error occurs, from server configuration issues to network-related problems. We provide you with step-by-step instructions to diagnose the root cause and offer practical solutions to get your pgAdmin 4 server back online.

You'll learn how to check and adjust server settings, verify network connections, and address any potential conflicts that might be causing the server to become unreachable. We also share tips on how to prevent this issue from happening in the future, so you can maintain a stable and reliable PostgreSQL environment.

Whether you're a database administrator, developer, or just someone working with PostgreSQL, this video will equip you with the knowledge and tools to solve the "pgAdmin 4 server could not be contacted" error quickly and effectively.


pgAdmin 4 server error, server could not be contacted pgAdmin, fix pgAdmin server issue, PostgreSQL server connection, troubleshoot pgAdmin 4, pgAdmin connectivity issue, PostgreSQL database error, pgAdmin 4 troubleshooting, fix PostgreSQL connection, pgAdmin server fix



How To Resolve/Fix The pgAdmin 4 server could not be contacted || PostgreSQL Database || pgAdmin 4
How To Resolve/fix The Pgadmin 4 Server Connection Problem How To Fix The Pgadmin 4 Server Could Not Be Contacted || Postgresql Database || Pgadmin 4 How To Fix Pgadmin 4 Server Connection Problems How To Fix Pgadmin 4 Server Could Not Be Contacted Error Pgadmin 4: How To Fix The "Server Could Not Be Contacted" Error How To Fix When The Pgadmin 4 Server Can't Be Contacted Resolving The "pgAdmin 4 Server Could Not Be Contacted" Error For Postgresql Databases 1. Restart the Services 2. Restart The PC/Laptop 3. Configure the pgAdmin 4. Relaunch pgAdmin


Please Like, Comment, and Subscribe to my channel. ❤

How To Resolve pgAdmin 4 server could not be contacted, How To Fix pgAdmin 4 server could not be contacted, pgAdmin server could not be contacted, Fix pgAdmin 4 server could not be contacted, PostgreSQL, pgAdmin 4, pgAdmin, the application server could not be contacted pgAdmin 4, PostgreSQL tutorial, connection refused, Pgadmin 4 Server Connection Problems, Pgadmin 4 Server Could Not Be Contacted Error, Pgadmin 4 Server Connection Problem, connection refused error, fix pgAdmin 4

Thursday, 25 May 2023

How To Create And Call A Stored Procedure/Function With Refcursor As OUT...



In this video, we dive deep into the process of creating and calling stored procedures or functions with REFCURSOR as an OUT parameter in PostgreSQL. REFCURSOR is a powerful feature in PostgreSQL that allows you to return a cursor from a stored procedure, enabling you to handle result sets more flexibly.

First, we guide you through the process of defining a stored procedure or function with a REFCURSOR OUT parameter. You'll learn how to structure your SQL code to create a procedure that can return query results via a cursor.

Next, we demonstrate how to call this procedure or function from your PostgreSQL environment, retrieving the data returned by the REFCURSOR. We provide step-by-step examples to ensure you can follow along and implement these techniques in your own projects.

We also cover best practices for managing stored procedures with cursors, including tips on optimizing performance and avoiding common pitfalls. Whether you're a database administrator, developer, or just getting started with PostgreSQL, this video will help you unlock new capabilities in your database management.


PostgreSQL stored procedure, REFCURSOR in PostgreSQL, PostgreSQL function with cursor, create stored procedure PostgreSQL, call stored procedure PostgreSQL, PostgreSQL REFCURSOR example, PostgreSQL stored function, PostgreSQL cursor management, SQL stored procedures, database function with cursor



create or replace function refcur_function
(in_actor_id IN numeric, refcur_output refcursor)
returns refcursor
language plpgsql
as $$
begin
open refcur_output for
Select title from film, film_actor
where film.film_id = film_actor.film_id
and film_actor.actor_id = in_actor_id;
return refcur_output;
exception when others then
raise notice 'Something Went Wrong';
end; $$

select refcur_function(1, 'refcur_output');
fetch all in refcur_output;

select refcur_function(2, 'refcur_output');
fetch all in refcur_output;


How To Create And Call A Stored Procedure Function With Refcursor As OUT Parameter In PostgreSQL
,Function With Refcursor OUT Parameter
,Procedure With Refcursor OUT Parameter
,Create A Function With Refcursor OUT Parameter
,Create A Procedure With Refcursor OUT Parameter
,Call A Stored Function With Refcursor OUT Parameter
,PLpgSQL Language
,PostgreSQL PLpgSQL Language
,Refcursor OUT
,Function Refcursor OUT
,Procedure Refcursor OUT

Tuesday, 23 May 2023

How To Create And Call A Stored Procedure With Multiple/Many OUT Paramet...


In this comprehensive tutorial, we explore the process of creating and calling stored procedures with multiple OUT parameters in PostgreSQL using PL/pgSQL. Handling multiple outputs from a single stored procedure can greatly enhance the efficiency and flexibility of your database operations.

We begin by showing you how to define a stored procedure with several OUT parameters, explaining the syntax and logic behind the PL/pgSQL code. This allows you to return multiple pieces of data from a single procedure call, which is especially useful for complex operations that involve multiple result sets or calculations.

Next, we demonstrate how to call the stored procedure and retrieve the multiple outputs effectively. Through detailed examples, you'll learn how to handle and use these outputs in your PostgreSQL environment, enabling you to perform more sophisticated database operations.

We also cover best practices for managing and optimizing stored procedures with multiple OUT parameters, including tips for maintaining performance and avoiding common pitfalls. This tutorial is perfect for database administrators, developers, and anyone looking to deepen their understanding of PostgreSQL's powerful features.


PostgreSQL stored procedure, multiple OUT parameters PostgreSQL, PL/pgSQL stored procedure, PostgreSQL function with multiple outputs, create stored procedure PostgreSQL, call stored procedure PostgreSQL, PostgreSQL PL/pgSQL examples, SQL stored procedures, database functions PostgreSQL, PostgreSQL advanced tutorial

CREATE OR REPLACE PROCEDURE public.two_out_param_proc(
IN in_customer_name character varying,
IN in_address_id numeric,
OUT out_payment_amount numeric,
OUT out_max_payment_date date
)
LANGUAGE 'plpgsql'
AS $BODY$
 
 Declare
 Begin
  Select sum(amount), max(payment_date) 
into out_payment_amount, out_max_payment_date
From payment
where customer_id = (select customer_id from customer
where first_name = in_customer_name
and address_id = in_address_id);
exception
when others then
raise notice 'Something went wrong';
end;
$BODY$;
ALTER PROCEDURE public.two_out_param_proc(character varying, numeric, numeric, date)
    OWNER TO postgres;

select sum(amount) from payment where customer_id = 341;

select * from customer where customer_id = 341;

do $$
declare

v_payment_amount numeric(10,2);
v_max_payment_date date;

begin
call two_out_param_proc('Peter',346,v_payment_amount,v_max_payment_date);
raise notice 'The total payment amount is % and the latest payment date is %',v_payment_amount,v_max_payment_date;

end $$;

Monday, 22 May 2023

How To Create And Call A Stored Procedure With OUT Parameters In Postgre...


In this detailed tutorial, we delve into the process of creating and calling stored procedures with OUT parameters using the PL/pgSQL language in PostgreSQL. OUT parameters allow you to return multiple results from a stored procedure, making your database operations more efficient and versatile.

We start by guiding you through the syntax and structure needed to define a stored procedure with OUT parameters. You'll learn how to write a procedure that returns multiple values, which can be used to handle complex database tasks such as calculations, data transformations, or conditional operations.

Next, we demonstrate how to call the stored procedure and retrieve the OUT parameters' values. Through clear, step-by-step examples, you'll see how these procedures can be applied in real-world scenarios, helping you to streamline your database processes and reduce the complexity of your SQL queries.

We also cover best practices for managing and optimizing stored procedures in PostgreSQL, ensuring that your database operations are both effective and efficient. Whether you're a database administrator, developer, or just someone looking to enhance their PostgreSQL skills, this video provides valuable insights into advanced database management techniques.

PostgreSQL stored procedure, OUT parameters in PostgreSQL, PL/pgSQL stored procedure, create stored procedure PostgreSQL, call stored procedure PostgreSQL, PostgreSQL PL/pgSQL tutorial, SQL stored procedures, PostgreSQL OUT parameters, database management, PostgreSQL programming

create or replace procedure one_out_param_proc
(in_customer_name IN character varying,
 in_address_id IN numeric,
 out_payment_amount OUT numeric)
 Language 'plpgsql'
 AS $BODY$
 
 Declare
 Begin
  Select sum(amount) into out_payment_amount
From payment
where customer_id = (select customer_id from customer
where first_name = in_customer_name
and address_id = in_address_id);
exception
when others then
raise notice 'Something went wrong';
end;
$BODY$

select sum(amount) from payment where customer_id = 341;

select * from customer where customer_id = 341;

do $$
declare
v_payment_amount numeric(10,2);
begin
call one_out_param_proc ('Peter', 346, v_payment_amount);
raise notice 'Total Payment Amount is %',v_payment_amount;
end $$;

Friday, 19 May 2023

How To Create Audit Triggers In PostgreSQL || Trigger Functions In Postg...


In this continuation of our PostgreSQL trigger series, we focus on creating audit triggers using trigger functions. Audit triggers are an essential tool for tracking and logging changes in your database, ensuring that you maintain a robust record of all operations that modify your data.

This tutorial begins with a brief recap of trigger functions in PostgreSQL, highlighting how they can be used to automatically execute specific actions when certain events occur in your database. We then dive into the process of setting up audit triggers that log every INSERT, UPDATE, and DELETE operation performed on a table.

You'll learn how to define a trigger function that captures changes and writes them to an audit table, providing a detailed record of all modifications made to your data. The video includes step-by-step instructions, making it easy to follow along and implement these techniques in your own PostgreSQL environment.

Additionally, we discuss best practices for managing and optimizing your audit triggers, ensuring they run efficiently without negatively impacting your database's performance. By the end of this video, you'll have a thorough understanding of how to use PostgreSQL triggers for effective auditing and monitoring of your database activities.


PostgreSQL audit triggers, create audit triggers PostgreSQL, PostgreSQL trigger functions, audit logs PostgreSQL, database auditing PostgreSQL, PostgreSQL triggers tutorial, trigger functions SQL, database security PostgreSQL, PostgreSQL audit table, SQL trigger examples


-- SEQUENCE: public.students_logs_seq -- DROP SEQUENCE IF EXISTS public.students_logs_seq; CREATE SEQUENCE IF NOT EXISTS public.students_logs_seq INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 999999999 CACHE 1; ALTER SEQUENCE public.students_logs_seq OWNER TO postgres;

-- Table: public.students -- DROP TABLE IF EXISTS public.students; CREATE TABLE IF NOT EXISTS public.students ( roll numeric(10,0), name character varying(30) COLLATE pg_catalog."default", course character varying(30) COLLATE pg_catalog."default" ) TABLESPACE pg_default; ALTER TABLE IF EXISTS public.students OWNER to postgres; -- Trigger: student_trg -- DROP TRIGGER IF EXISTS student_trg ON public.students; CREATE TRIGGER student_trg AFTER INSERT OR DELETE OR UPDATE ON public.students FOR EACH ROW EXECUTE FUNCTION public.student_logs_trg_func();


-- Table: public.students_logs -- DROP TABLE IF EXISTS public.students_logs; CREATE TABLE IF NOT EXISTS public.students_logs ( logs_id numeric(10,0) NOT NULL DEFAULT nextval('students_logs_seq'::regclass), roll_old numeric(10,0), name_old character varying(30) COLLATE pg_catalog."default", course_old character varying(30) COLLATE pg_catalog."default", roll_new numeric(10,0), name_new character varying(30) COLLATE pg_catalog."default", course_new character varying(30) COLLATE pg_catalog."default", actions character varying(50) COLLATE pg_catalog."default", log_date timestamp without time zone DEFAULT CURRENT_TIMESTAMP, CONSTRAINT students_logs_pkey PRIMARY KEY (logs_id) ) TABLESPACE pg_default; ALTER TABLE IF EXISTS public.students_logs OWNER to postgres;

-- FUNCTION: public.student_logs_trg_func() -- DROP FUNCTION IF EXISTS public.student_logs_trg_func(); CREATE OR REPLACE FUNCTION public.student_logs_trg_func() RETURNS trigger LANGUAGE 'plpgsql' COST 100 VOLATILE NOT LEAKPROOF AS $BODY$ declare begin if old.roll <> new.roll then insert into students_logs (roll_old,name_old,course_old, roll_new,name_new,course_new,actions) values(old.roll,old.name,old.course,new.roll,new.name,new.course, 'Roll Value Updated'); end if; if old.name <> new.name then insert into students_logs (roll_old,name_old,course_old, roll_new,name_new,course_new,actions) values(old.roll,old.name,old.course,new.roll,new.name,new.course,'Name Value Updated'); end if; if old.course <> new.course then insert into students_logs (roll_old,name_old,course_old, roll_new,name_new,course_new,actions) values(old.roll,old.name,old.course,new.roll,new.name,new.course, 'Course Value Updated'); end if; -- For Insert if old.roll is null then insert into students_logs (roll_old,name_old,course_old, roll_new,name_new,course_new,actions) values(old.roll,old.name,old.course,new.roll,new.name,new.course, 'New Record Inserted'); end if; -- For Delete if new.roll is null then insert into students_logs (roll_old,name_old,course_old, roll_new,name_new,course_new,actions) values(old.roll,old.name,old.course,new.roll,new.name,new.course, 'Existing Record Deleted'); end if; return new; end; $BODY$; ALTER FUNCTION public.student_logs_trg_func() OWNER TO postgres;


How To Create Audit Triggers In PostgreSQL || Trigger Functions In PostgreSQL || Part 2 Video
In this video, we will try to create an audit trigger function for PostgreSQL. This is also an extended video called Part 2 of the audit triggers series. Please watch the video completely to understand the concept of trigger functions in PostgreSQL.

In PostgreSQL, an audit trigger is a mechanism that allows you to monitor and record changes to database tables. It helps in maintaining data integrity, tracking modifications, and ensuring compliance with regulatory requirements. When certain events or actions occur, such as INSERT, UPDATE, or DELETE operations on specific tables, the audit trigger is triggered, and it performs predefined actions to capture relevant information. Here's how audit triggers work in PostgreSQL: Defining Audit Triggers: To implement audit triggers, you need to define them on the tables you want to monitor. An audit trigger is a database object associated with a specific table and set of events. It consists of trigger functions and rules that define the desired behavior when the associated events occur. Trigger Functions: A trigger function is a user-defined function that gets executed when the associated event is triggered. In the context of audit triggers, the trigger function typically captures the necessary information about the event and inserts it into an audit table or log. Audit Tables or Logs: An audit table or log is a separate table or set of tables where the audit trail is stored. This is where the trigger function inserts the relevant information about the event, such as the user who performed the action, the timestamp, the old and new values (in case of UPDATE operations), and any other desired metadata. Event Types: You can configure audit triggers to fire on specific events, such as INSERT, UPDATE, or DELETE operations. This allows you to customize the level of detail captured in the audit trail based on your requirements. For example, you might choose to audit only certain tables or specific columns within those tables. Trigger Rules: Trigger rules define the conditions under which the audit trigger should be fired. For example, you can specify that the trigger should only be activated when a specific column is modified or when a certain condition is met. Enabling and Disabling Audit Triggers: Once you have defined the audit triggers, you can enable or disable them as needed. This gives you flexibility in controlling when the triggers are active, such as during specific maintenance or auditing periods. Analyzing Audit Data: The captured audit trail can be analyzed to gain insights into the database activity, identify potential issues or anomalies, and meet compliance requirements. By reviewing the audit logs, you can track changes, detect unauthorized actions, and investigate any suspicious activities. It's important to note that implementing audit triggers requires careful consideration of performance and storage implications. Storing detailed audit logs can generate a significant amount of data, so it's essential to strike a balance between capturing sufficient information and managing resource usage effectively.
In summary, audit triggers in PostgreSQL provide a powerful mechanism to monitor and record changes in database tables. By capturing relevant information about specific events, they enhance data integrity, assist in compliance efforts, and enable effective analysis of database activity.

How To Create Audit Triggers In PostgreSQL || Trigger Functions In Postg...


In this first part of our two-part series on audit triggers in PostgreSQL, we introduce you to the concept of audit triggers and how they can be used to monitor and log changes to your database automatically. Audit triggers are essential for maintaining a secure and accountable database environment, providing a record of every change that occurs within your tables.

We begin by explaining the fundamentals of triggers in PostgreSQL, including what they are and how they work. You'll learn how to create basic trigger functions that can capture changes in your data and log them for auditing purposes. The video guides you step-by-step through the process of defining these functions and attaching them to your tables using triggers.

This tutorial also covers the scenarios where audit triggers are particularly useful, such as tracking modifications to sensitive data or ensuring compliance with data governance policies. By the end of this video, you will have a solid understanding of how to implement audit triggers in PostgreSQL, setting the foundation for more advanced auditing techniques covered in Part 2.


PostgreSQL audit triggers, creating audit triggers PostgreSQL, PostgreSQL trigger functions, database auditing, PostgreSQL triggers tutorial, SQL audit triggers, database security PostgreSQL, trigger function examples, PostgreSQL auditing, SQL database triggers


insert into students values (1, 'Akram Sohail', 'MCA');

select * from students;

select * from students_logs;

update students set course = 'MCA 2018-2019';

update students set name = 'A. Sohail';

update students set roll = 2;

delete from students_logs;

delete from students;


-- Table: public.students


-- DROP TABLE IF EXISTS public.students;


CREATE TABLE IF NOT EXISTS public.students

(

    roll numeric(10,0),

    name character varying(30) COLLATE pg_catalog."default",

    course character varying(30) COLLATE pg_catalog."default"

)


TABLESPACE pg_default;


ALTER TABLE IF EXISTS public.students

    OWNER to postgres;


-- Trigger: student_trg


-- DROP TRIGGER IF EXISTS student_trg ON public.students;


CREATE TRIGGER student_trg

    AFTER INSERT OR DELETE OR UPDATE 

    ON public.students

    FOR EACH ROW

    EXECUTE FUNCTION public.student_logs_trg_func();


-- Table: public.students_logs


-- DROP TABLE IF EXISTS public.students_logs;


CREATE TABLE IF NOT EXISTS public.students_logs

(

    roll_old numeric(10,0),

    name_old character varying(30) COLLATE pg_catalog."default",

    course_old character varying(30) COLLATE pg_catalog."default",

    actions character varying(50) COLLATE pg_catalog."default"

)


TABLESPACE pg_default;


ALTER TABLE IF EXISTS public.students_logs

    OWNER to postgres;


-- FUNCTION: public.student_logs_trg_func()

 -- DROP FUNCTION IF EXISTS public.student_logs_trg_func();


CREATE OR REPLACE FUNCTION PUBLIC.STUDENT_LOGS_TRG_FUNC() RETURNS TRIGGER LANGUAGE 'plpgsql' COST 100 VOLATILE NOT LEAKPROOF AS $BODY$

declare

begin


if old.roll <> new.roll then


insert into students_logs

(roll_old,name_old,course_old, actions)

values(old.roll,old.name,old.course, 'Roll Value Updated');


end if;


if old.name <> new.name then


insert into students_logs

(roll_old,name_old,course_old, actions)

values(old.roll,old.name,old.course, 'Name Value Updated');


end if;


if old.course <> new.course then


insert into students_logs

(roll_old,name_old,course_old, actions)

values(old.roll,old.name,old.course, 'Course Value Updated');


end if;


return new;

end;

$BODY$;



ALTER FUNCTION PUBLIC.STUDENT_LOGS_TRG_FUNC() OWNER TO POSTGRES;

 

In PostgreSQL, an audit trigger is a mechanism that allows you to monitor and record changes to database tables. It helps in maintaining data integrity, tracking modifications, and ensuring compliance with regulatory requirements. When certain events or actions occur, such as INSERT, UPDATE, or DELETE operations on specific tables, the audit trigger is triggered, and it performs predefined actions to capture relevant information.

Here's how audit triggers work in PostgreSQL:

Defining Audit Triggers: To implement audit triggers, you need to define them on the tables you want to monitor. An audit trigger is a database object associated with a specific table and set of events. It consists of trigger functions and rules that define the desired behavior when the associated events occur.

Trigger Functions: A trigger function is a user-defined function that gets executed when the associated event is triggered. In the context of audit triggers, the trigger function typically captures the necessary information about the event and inserts it into an audit table or log.

Audit Tables or Logs: An audit table or log is a separate table or set of tables where the audit trail is stored. This is where the trigger function inserts the relevant information about the event, such as the user who performed the action, the timestamp, the old and new values (in case of UPDATE operations), and any other desired metadata.

Event Types: You can configure audit triggers to fire on specific events, such as INSERT, UPDATE, or DELETE operations. This allows you to customize the level of detail captured in the audit trail based on your requirements. For example, you might choose to audit only certain tables or specific columns within those tables.

Trigger Rules: Trigger rules define the conditions under which the audit trigger should be fired. For example, you can specify that the trigger should only be activated when a specific column is modified or when a certain condition is met.

Enabling and Disabling Audit Triggers: Once you have defined the audit triggers, you can enable or disable them as needed. This gives you flexibility in controlling when the triggers are active, such as during specific maintenance or auditing periods.

Analyzing Audit Data: The captured audit trail can be analyzed to gain insights into the database activity, identify potential issues or anomalies, and meet compliance requirements. By reviewing the audit logs, you can track changes, detect unauthorized actions, and investigate any suspicious activities.

It's important to note that implementing audit triggers requires careful consideration of performance and storage implications. Storing detailed audit logs can generate a significant amount of data, so it's essential to strike a balance between capturing sufficient information and managing resource usage effectively.

In summary, audit triggers in PostgreSQL provide a powerful mechanism to monitor and record changes in database tables. By capturing relevant information about specific events, they enhance data integrity, assist in compliance efforts, and enable effective analysis of database activity.

Sunday, 12 February 2023

How To Create Triggers In PostgreSQL || How To Create Trigger Function I...


In this comprehensive tutorial, we delve into the world of triggers in PostgreSQL, showing you how to create both triggers and trigger functions from scratch. Triggers are a powerful feature in PostgreSQL that allow you to automatically execute a function when certain events occur on a table, such as INSERT, UPDATE, or DELETE operations.

We start by explaining the concept of triggers and their importance in maintaining data integrity and automating routine tasks. You’ll learn how to define a trigger function, which contains the logic that will be executed when the trigger is fired. From there, we guide you through the process of creating a trigger that links this function to a specific table, ensuring that your database reacts automatically to changes.

The video includes detailed, step-by-step examples, making it easy for you to follow along and implement these techniques in your own PostgreSQL environment. We also cover best practices for managing and optimizing triggers, ensuring that they perform efficiently without negatively impacting your database.

Whether you're a database administrator, developer, or just starting with PostgreSQL, this tutorial will equip you with the knowledge needed to effectively use triggers to automate and secure your database operations.


PostgreSQL triggers, create triggers PostgreSQL, trigger functions PostgreSQL, SQL triggers, database automation, PostgreSQL tutorial, database management, trigger functions examples, PostgreSQL triggers step-by-step, SQL automation


-- Table: public.students

-- DROP TABLE IF EXISTS public.students;

CREATE TABLE IF NOT EXISTS public.students
(
    roll numeric(10,0),
    name character varying(30) COLLATE pg_catalog."default",
    course character varying(30) COLLATE pg_catalog."default"
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public.students
    OWNER to postgres;

-- Table: public.students_logs

-- DROP TABLE IF EXISTS public.students_logs;

CREATE TABLE IF NOT EXISTS public.students_logs
(
    roll_old numeric(10,0),
    name_old character varying(30) COLLATE pg_catalog."default",
    course_old character varying(30) COLLATE pg_catalog."default"
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public.students_logs
    OWNER to postgres;


-- FUNCTION: public.student_logs_trg_func()

-- DROP FUNCTION IF EXISTS public.student_logs_trg_func();

CREATE OR REPLACE FUNCTION public.student_logs_trg_func()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
declare
begin
insert into students_logs
(roll_old,name_old,course_old)
values(old.roll,old.name,old.course);
return new;
end;
$BODY$;

ALTER FUNCTION public.student_logs_trg_func()
    OWNER TO postgres;


-- Trigger: student_trg

-- DROP TRIGGER IF EXISTS student_trg ON public.students;

CREATE TRIGGER student_trg
    BEFORE DELETE OR UPDATE 
    ON public.students
    FOR EACH ROW
    EXECUTE FUNCTION public.student_logs_trg_func();

insert into students values (1,'Akram','MCA');

select * from students;
select * from students_logs;

update students set name = 'Akram Sohail' where roll = 1;

update students set name = 'Akram Sohail (Modified)' where roll = 1;

delete from students where roll = 1;


----------------------------------------------------------------------------------------------

Triggers are special types of functions that are called/invoked/executed/performed automatically as per the trigger event declaration. A trigger is usually set before or after updating, deleting, insert DML statements on a table. That means, whenever a record is to be inserted, updated, or deleted, based on the time of execution which can be before or after, the trigger executes. Generally, the execution of the Trigger is called “Trigger Fired”.

In PostgreSQL, to create a trigger and make it usable, the sequence of object creation will be:
•   Create a Table on which a trigger to be implemented
•   Create another table to keep logs, so we can see the Trigger work
•   Create a Trigger Function that holds the trigger
•   Create the Trigger Function and Define the Trigger Logic
•   Perform Insert/Update/Delete Operations on the Table

Friday, 13 January 2023

PostgreSQL Refcursor || Cursors In PostgreSQL || Part 4 Refcursor Cursor...


In the fourth installment of our PostgreSQL Cursors series, we dive into the world of Refcursors, a powerful and flexible feature in PostgreSQL that allows for dynamic and complex data retrieval. Unlike regular cursors, Refcursors provide the ability to open a cursor in one function and fetch data from it in another, making them incredibly useful for modular and reusable database operations.

This tutorial begins with an introduction to Refcursors, explaining what they are and how they differ from other types of cursors available in PostgreSQL. We then move on to demonstrate how to declare, open, and use Refcursors within your database procedures, providing step-by-step instructions and practical examples to ensure you understand the concept thoroughly.

We also cover scenarios where Refcursors shine, such as when you need to return a cursor from a function to be used later or in different parts of your application. Additionally, we discuss best practices for using Refcursors efficiently, ensuring that your database operations remain performant and reliable.

Whether you’re managing complex queries or looking to build more modular database functions, this video will equip you with the knowledge needed to effectively utilize Refcursors in PostgreSQL.


PostgreSQL Refcursors, Refcursors in PostgreSQL, PostgreSQL cursors, advanced SQL cursors, using Refcursors PostgreSQL, SQL Refcursor examples, PostgreSQL database management, dynamic data handling, database programming, PostgreSQL tutorial


select refcursor_cursor(1,'lv_refcursor');
fetch all in lv_refcursor;

create or replace function refcursor_cursor(in_actor_id in integer, lv_ref_cur refcursor)
returns refcursor
language plpgsql
as $$
begin
open lv_ref_cur
for select 'Title: '||f.title as Title
from film_actor fa, film f
where fa.film_id = f.film_id
and fa.actor_id = in_actor_id;
return lv_ref_cur;
exception when others then
raise notice 'Something Went Wrong';
end;
$$

Thursday, 12 January 2023

PostgreSQL Cursors || Cursors Available In PostgreSQL || Part 3 For Loop...


In the third part of our PostgreSQL Cursors series, we focus on For Loop Cursors, a powerful feature that allows you to iterate over the rows of a result set one by one. This technique is particularly useful when you need to perform operations on each row returned by a query, such as updating records, calculating values, or logging data.

We begin by explaining the concept of cursors in a For Loop and how they differ from other types of cursors. You’ll learn how to declare and use a For Loop Cursor in PostgreSQL, with step-by-step instructions and clear examples that demonstrate its practical applications. We also discuss common scenarios where For Loop Cursors are most effective, such as batch processing and automated data handling tasks.

The video also covers best practices for using For Loop Cursors efficiently, including tips on optimizing performance and managing resources within your PostgreSQL environment. By the end of this tutorial, you will have a thorough understanding of how to leverage For Loop Cursors to automate and enhance your database operations.

Whether you're new to PostgreSQL or looking to expand your expertise, this tutorial provides valuable insights into the effective use of cursors in a loop for database programming.

PostgreSQL For Loop Cursors, using For Loop Cursors PostgreSQL, cursor loops in PostgreSQL, SQL cursors tutorial, PostgreSQL database management, loop processing SQL, PostgreSQL cursor examples, data handling PostgreSQL, database automation, advanced SQL techniques


call for_loop_cursor(1);

create or replace procedure for_loop_cursor(in_actor_id in integer)
language plpgsql
as $$
declare
lv_string character varying(200);
loop_rec record;
begin
for loop_rec in 
select f.title from film_actor fa,film f 
where fa.film_id = f.film_id 
and actor_id = in_actor_id
LOOP
lv_string := 'Title: '||loop_rec.title;
raise notice '%',lv_string;
end loop;
exception when others then
raise notice 'Something Went Wrong';
end;
$$

Saturday, 7 January 2023

PostgreSQL Cursors || Cursors Available In PostgreSQL || Part 2 Paramete...



In Part 2 of our PostgreSQL Cursors series, we focus on Parameterized Cursors, an advanced type of cursor that allows for dynamic data retrieval based on parameters passed at runtime. Parameterized cursors are incredibly useful when you need to execute the same query with different values, making your database operations more flexible and efficient.

The tutorial begins with a brief overview of what parameterized cursors are and how they differ from simple cursors. You’ll learn how to define a parameterized cursor in PostgreSQL, set the necessary parameters, and use these cursors to fetch data dynamically. The video includes detailed, step-by-step examples that illustrate how to use parameterized cursors in various scenarios, such as filtering data or performing operations on subsets of data based on different criteria.

We also cover the best practices for managing parameterized cursors, ensuring that your queries run efficiently without putting undue strain on your database resources. By the end of this video, you will have a solid understanding of how to implement and optimize parameterized cursors in your PostgreSQL environment, helping you to build more dynamic and responsive database applications.

Whether you're a database administrator, developer, or just looking to deepen your PostgreSQL knowledge, this tutorial provides the insights and techniques you need to effectively use parameterized cursors.

PostgreSQL parameterized cursors, parameterized cursors PostgreSQL, dynamic SQL PostgreSQL, using cursors in PostgreSQL, SQL parameterized queries, PostgreSQL cursor examples, PostgreSQL tutorial, database management, advanced SQL, PostgreSQL tips


call parameterized_cursor(1);

create or replace procedure parameterized_cursor(in_actor_id in integer)
language plpgsql
as $$
declare
lv_string character varying(200);
loop_rec record;
rec1 record;
cur1 cursor(p_film_id integer) for 
select title from film where film_id = p_film_id order by film_id;
begin
for loop_rec in select film_id from film_actor where actor_id = in_actor_id
LOOP
open cur1(loop_rec.film_id);
loop 
fetch cur1 into rec1;
exit when not found;
lv_string := 'Title: '||rec1.title;
raise notice '%',lv_string;
end loop;
close cur1;
end loop;
exception when others then
raise notice 'Something Went Wrong';
end;
$$

Keywords

postgresql cursors parameterized cursor cursors available in postgresql,
parameterized cursor,
parameterised cursor,
cursors available in postgresql,
postgresql cursors,
postgresql,
cursors,
cursor,
postgres,
pg admin,
pg admin 4,
postgres pg admin,
how to create cursor in posgresql,
create cursor in posgresql,
create parameterized cursor,
create parameterised cursor,
fetch cursor,
loop cursor,
exit cursor,
declare cursor,
define cursor,
cursor in procedure,
cursor in function,
knowledge 360,
akram sohail

Wednesday, 4 January 2023

PostgreSQL Cursors || Cursors Available In PostgreSQL || Part 1 Simple C...


In this video, we introduce you to PostgreSQL Cursors, focusing on simple cursors as the first part of our series on cursors available in PostgreSQL. Cursors are an essential tool for managing large result sets, allowing you to retrieve and process data in smaller, more manageable chunks rather than all at once.

We start by explaining what a cursor is and how it works in PostgreSQL. You'll learn the scenarios where cursors are particularly useful, such as when working with large datasets or when you need to process query results row by row. The video then guides you through the steps to create and use a simple cursor, with clear and concise examples to help you understand how to implement this in your own database projects.

Additionally, we discuss best practices for using cursors effectively, ensuring that you can handle large amounts of data without overloading your system or causing performance issues. By the end of this tutorial, you'll have a solid understanding of how to leverage simple cursors in PostgreSQL, setting the foundation for more advanced cursor techniques in upcoming videos.

Whether you’re a beginner or looking to expand your PostgreSQL skills, this video is a great resource for understanding and utilizing cursors in your database operations.


PostgreSQL cursors, simple cursor PostgreSQL, using cursors in PostgreSQL, SQL cursors tutorial, PostgreSQL database management, fetch data with cursors, PostgreSQL cursor example, data handling PostgreSQL, database optimization, PostgreSQL tutorial


call simple_cursor();

create or replace procedure simple_cursor()
language plpgsql
as $$
declare
lv_string character varying(200);
rec1 record;
cur1 cursor for 
select actor_id, first_name, last_name as end_name from actor order by actor_id;
begin
open cur1;
loop 
fetch cur1 into rec1;
exit when not found;
lv_string := 'Actor ID: '||rec1.actor_id||', Actor First Name: '||rec1.first_name||', Actor Last Name: '||rec1.end_name;
raise notice '%',lv_string;
end loop;
close cur1;
exception when others then
raise notice 'Something Went Wrong';
end;
$$



Keywords:

postgresql cursors simple cursor cursors available in postgresql,simple cursor,cursors available in postgresql,postgresql cursors,postgresql,cursors,cursor,postgres,pg admin,pg admin 4,postgres pg admin,how to create cursor in posgresql,create cursor in posgresql,create simple cursor,fetch cursor,loop cursor,exit cursor,declare cursor,define cursor,cursor in procedure,cursor in function,knowledge 360,akram sohail,cursors in postgresql,postgresql cursor syntax