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 Triggers
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 Triggers

By Priya PedamkarPriya Pedamkar

PostgreSQL Triggers

Introduction to PostgreSQL Triggers

PostgreSQL trigger will be associated with a specific view or table; it will execute with a specified function when a certain event occurs. PostgreSQL trigger is used to execute the specified events at a specific time using events.   PostgreSQL trigger will invoke automatically when any event (Insert, Update or delete) occurs on a table or views. To create a new trigger in PostgreSQL, we need to define the trigger function first, and then we have binding this trigger function to the specified table.

The main difference between PostgreSQL trigger and user-defined function is trigger was automatically invoked when a specified event occurs.

Syntax and Parameters of PostgreSQL trigger

Create a trigger statement is used to create a new trigger in PostgreSQL. The trigger will occur when any particular or specific event occurs on a table or view.

Syntax

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

CREATE [ CONSTRAINT ] TRIGGER name(must be distinct of any other trigger in same table) { BEFORE | AFTER | INSTEAD OF } { event (Event Name)[ OR ... ] }
ON table (Table_name)
[FROM referenced_table_name] [NOT DEFERRABLE | [DEFERRABLE] {INITIALLY IMMEDIATE | INITIALLY DEFERRED} ] [FOR [EACH] {ROW | STATEMENT} ] [WHEN (condition) ] EXECUTE PROCEDURE function name (arguments)

Where event can be one of the following:

INSERT
UPDATE [OF Column_name [, ... ] ] DELETE
TRUNCATE

Parameter

  • Name – The name of the trigger. This name will be distinct from any other trigger from the same table.
  • Before – Determines that we are calling the function before the event.
  • After – Determines that we are calling the function after the event.
  • Instead Of – Determines that we are calling the function instead of the event.
  • Event – Any of the event like Insert, Update, delete or truncate will fire the trigger.
  • Table name – Name of the table or view
  • Referenced table name – This is the name of other tables which is referenced by constraints. This option only specified with constraints triggers.
  • DEFERRABLE, NOT DEFERRABLE, INITIALLY IMMEDIATE and INITIALLY DEFERRED – This is the PostgreSQL trigger’s default time.
  • For each row, this will specify that the trigger will be fired once for every row affected by trigger events.
  • For each statement – If we have not specified any row or statement, this will default. This will specify that it will be fired once for every statement affected by a trigger event.
  • Condition – Condition will be the Boolean expression that determines that trigger function will be executed.
  • Function name – User-supplied function that is not arguments, and it will return trigger.
  • Arguments – This is an optional comma-separated argument provided to the function, then the trigger was executing.

PostgreSQL Triggers Working

Below is the working of PostgreSQL Triggers.

  • It is a set of actions that run automatically when specific database event like (Insert, Update, Delete and Truncate) will perform on a table.
  • It will provide two important types of triggers.
  • Row-level triggers
  • Statement level triggers
  • If the trigger is marked as FOR EACH ROW, then it will be called once for every row that the operation was modified.
  • If the trigger is marked as FOR EACH STATEMENT, then it will be called once for every statement that the operation was modified.
  • The main difference between the row-level trigger and statement-level triggers is that if we are updating 20 rows in a single table, row-level triggers will be invoked 20 times. Instead of that, statement-level triggers are executed only one time.
  • By default, statement-level triggers were invoked if we don’t define the level of triggers.
  • We can also specify whether the trigger is invoked before or after an event occurs. If the trigger was invoked after the event, all changes are available to the trigger. In case it was invoked before, it will skip operation from the current row.
  • It is essential and useful when a single database accessed by much application.
  • It is also useful when we are maintaining complex data integrity rules that rule we cannot implement elsewhere except database level.
  • Creating a new trigger in PostgreSQL first, we need to create a trigger function. It does not take any argument; it will return value with the type of trigger.
  • Following is the syntax of creating a trigger function are as follows.

Creat Trigger Function

Below is the syntax for creating Trigger Function:

Syntax:

CREATE FUNCTION trigger_function_name ()
RETURNS trigger AS

  • We can create a trigger function in any language that PostgreSQL supported. It will receive data from its calling environment through a special structure called trigger data.
  • Trigger data contains a set of local variables in the PostgreSQL trigger function.
  • After creating a trigger function, we can bind it into one or more trigger events such as Update, Truncate, Delete and Insert.

The function is defined in the following compatible languages:

  • PL/pgsql
  • PL/Python
  • Pl/ Java

Examples of PostgreSQL Triggers

Please find below the steps to create the trigger in PostgreSQL.

Example #1 – Create a table and insert a record for testing

Code:

testing=# CREATE TABLE employee ( emp_name character(100) NOT NULL, emp_email character(20) NOT NULL, emp_phone character(14));
testing=# CREATE TABLE employee_history ( log_id character(100) NOT NULL);
testing=# INSERT INTO EMPLOYEE (emp_name, emp_email, emp_phone) VALUES ('ABC', 'abc@gmail.com', '1234567890');
testing=# INSERT INTO EMPLOYEE (emp_name, emp_email, emp_phone) VALUES ('PQR', 'pqr@gmail.com', '1234567890');
testing=# INSERT INTO EMPLOYEE (emp_name, emp_email, emp_phone) VALUES ('XYZ', 'xyz@gmail.com', '1234567890');

Output:

PostgreSQL Triggers output 1

Example #2 – Create a trigger function

We have created a trigger function name as trigger_testing.

Code:

CREATE OR REPLACE FUNCTION trigger_testing()
RETURNS trigger
AS $test_trigger$
BEGIN
INSERT INTO employee_history (log_id) VALUES (new.id);
RETURN NEW;
END;
$test_trigger$
LANGUAGE plpgsql;

Output:

PostgreSQL Triggers output 2

Example #3 – Create a trigger

We have to create a trigger name as a trigger_test.

Code:

CREATE TRIGGER trigger_test
AFTER INSERT ON employee
FOR EACH ROW
EXECUTE PROCEDURE trigger_testing();

Output:

output 3

Example #4 – Drop trigger in PostgreSQL

To drop trigger in PostgreSQL drop trigger statement is used.

Syntax 

DROP TRIGGER trigger_name on table_name;

Example

testing=#  drop trigger trigger_test on the employee;

Output:

output 4

Conclusion

For creating a new trigger in PostgreSQL CREATE TRIGGER statement is used. Row-level and statement-level triggers are two main important types of PostgreSQL triggers.

It always refers to a function that was triggered automatically when the event occurs on database tables or views.

Recommended Articles

This is a guide to PostgreSQL Triggers. Here we discuss the basic concept, examples of PostgreSQL Triggers, along with the steps and syntax. You may also have a look at the following articles to learn more –

  1. What is PostgreSQL?
  2. PostgreSQL String Functions
  3. PostgreSQL Views
  4. PostgreSQL FETCH
Popular Course in this category
SQL Training Program (7 Courses, 8+ Projects)
  7 Online Courses |  8 Hands-on Projects |  73+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
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

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

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

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

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

EDUCBA Login

Forgot Password?

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

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

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

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

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

Let’s Get Started

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