SlideShare uma empresa Scribd logo
1 de 12
Introduction to Triggers Robert Haas PostgreSQL East 2010
What Is a Trigger? ,[object Object]
Can fire on INSERT or UPDATE or DELETE or any combination.
Can fire once per statement or for every row.
Can fire BEFORE or AFTER the main operation.
Example #1: Compute full name CREATE TABLE person ( id serial PRIMARY KEY, first_name varchar not null, middle_name varchar not null, last_name varchar not null, full_name varchar not null ); CREATE OR REPLACE FUNCTION compute_person_full_name() RETURNS trigger AS $$ BEGIN NEW.full_name := NEW.first_name || CASE WHEN NEW.middle_name = '' THEN '' ELSE ' ' || NEW.middle_name END || ' ' || NEW.last_name; RETURN NEW; END $$ LANGUAGE plpgsql;
Example #1: Compute full name CREATE TRIGGER compute_person_full_name BEFORE INSERT OR UPDATE ON person FOR EACH ROW EXECUTE PROCEDURE compute_person_full_name(); INSERT INTO person (first_name, middle_name, last_name) VALUES ('Robert', 'M.', 'Haas'), ('Tom', '', 'Lane'); rhaas=# select full_name from person; full_name  ---------------- Robert M. Haas Tom Lane (2 rows)
Example #2: Counts and sums CREATE TABLE orders ( id serial primary key, customer_name varchar not null, number_of_items integer not null default 0, total_price numeric(12,2) not null default 0 ); CREATE TABLE order_items ( order_id integer not null references orders (id), item_name varchar not null, price numeric(12,2) not null default 0 );
Example #2: Counts and sums CREATE OR REPLACE FUNCTION update_order_stats() RETURNS trigger AS $$ BEGIN IF (TG_OP != 'DELETE') THEN UPDATE orders SET number_of_items = number_of_items + 1,  total_price = total_price + NEW.price WHERE id = NEW.order_id; END IF; IF (TG_OP != 'INSERT') THEN UPDATE orders SET number_of_items = number_of_items - 1,  total_price = total_price - OLD.price WHERE id = OLD.order_id; END IF; RETURN NULL; END $$ LANGUAGE plpgsql;
Example #2: Counts and sums CREATE TRIGGER update_order_stats AFTER INSERT OR UPDATE OR DELETE ON order_items FOR EACH ROW EXECUTE PROCEDURE update_order_stats();
Example #3: Denormalization CREATE TABLE person ( id serial primary key, full_name varchar not null, is_project_manager boolean not null ); CREATE TABLE project ( id serial primary key, name varchar not null, project_manager_id integer not null references person (id) );
Example #3: Denormalization CREATE TABLE person ( id serial primary key, full_name varchar not null, is_project_manager boolean not null ); CREATE TABLE project ( id serial primary key, name varchar not null, project_manager_id integer not null references person (id), is_project_manager boolean not null, CONSTRAINT pm_is_legal CHECK (is_project_manager) );

Mais conteúdo relacionado

Mais procurados

Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
Anurag
 

Mais procurados (20)

Sql commands
Sql commandsSql commands
Sql commands
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
Mysql joins
Mysql joinsMysql joins
Mysql joins
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
DML Commands
DML CommandsDML Commands
DML Commands
 
Triggers in SQL | Edureka
Triggers in SQL | EdurekaTriggers in SQL | Edureka
Triggers in SQL | Edureka
 
Oracle Database Trigger
Oracle Database TriggerOracle Database Trigger
Oracle Database Trigger
 
sql function(ppt)
sql function(ppt)sql function(ppt)
sql function(ppt)
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
MySQL and its basic commands
MySQL and its basic commandsMySQL and its basic commands
MySQL and its basic commands
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
 
Triggers and Stored Procedures
Triggers and Stored ProceduresTriggers and Stored Procedures
Triggers and Stored Procedures
 
Mysql
MysqlMysql
Mysql
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 

Destaque

Trigger and cursor program using sql
Trigger and cursor program using sqlTrigger and cursor program using sql
Trigger and cursor program using sql
Sushil Mishra
 
Introduction to databases
Introduction to databasesIntroduction to databases
Introduction to databases
akanksha007
 

Destaque (20)

Trigger
TriggerTrigger
Trigger
 
TRIGGERS
TRIGGERSTRIGGERS
TRIGGERS
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
 
Triggers ppt
Triggers pptTriggers ppt
Triggers ppt
 
Presentatie Marshall Goldsmith
Presentatie Marshall GoldsmithPresentatie Marshall Goldsmith
Presentatie Marshall Goldsmith
 
Using triggers in my sql database
Using triggers in my sql databaseUsing triggers in my sql database
Using triggers in my sql database
 
Trigger and cursor program using sql
Trigger and cursor program using sqlTrigger and cursor program using sql
Trigger and cursor program using sql
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
 
Trigger Data Base
Trigger Data BaseTrigger Data Base
Trigger Data Base
 
View of data DBMS
View of data DBMSView of data DBMS
View of data DBMS
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
Database backup and recovery
Database backup and recoveryDatabase backup and recovery
Database backup and recovery
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Backup And Recovery
Backup And RecoveryBackup And Recovery
Backup And Recovery
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Introduction to databases
Introduction to databasesIntroduction to databases
Introduction to databases
 
Introduction to triggers
Introduction to triggersIntroduction to triggers
Introduction to triggers
 
Database Security
Database SecurityDatabase Security
Database Security
 

Semelhante a Introduction to triggers

perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
Joe Jiang
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
Reka
 
My sql presentation
My sql presentationMy sql presentation
My sql presentation
Nikhil Jain
 
I am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdfI am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdf
petercoiffeur18
 
Oracle trigger
Oracle triggerOracle trigger
Oracle trigger
nasrul28
 
MYSQL
MYSQLMYSQL
MYSQL
ARJUN
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricks
Yanli Liu
 

Semelhante a Introduction to triggers (20)

Function Procedure Trigger Partition.pdf
Function Procedure Trigger Partition.pdfFunction Procedure Trigger Partition.pdf
Function Procedure Trigger Partition.pdf
 
SQL -PHP Tutorial
SQL -PHP TutorialSQL -PHP Tutorial
SQL -PHP Tutorial
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
 
Oracle - Program with PL/SQL - Lession 05
Oracle - Program with PL/SQL - Lession 05Oracle - Program with PL/SQL - Lession 05
Oracle - Program with PL/SQL - Lession 05
 
My sql presentation
My sql presentationMy sql presentation
My sql presentation
 
Getting Started with PL/Proxy
Getting Started with PL/ProxyGetting Started with PL/Proxy
Getting Started with PL/Proxy
 
Mca ii-dbms-u-v-transaction management
Mca ii-dbms-u-v-transaction managementMca ii-dbms-u-v-transaction management
Mca ii-dbms-u-v-transaction management
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16
 
I am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdfI am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdf
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
 
Oracle trigger
Oracle triggerOracle trigger
Oracle trigger
 
MYSQL
MYSQLMYSQL
MYSQL
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented Perl
 
Valeriy Prokopchuk: Validators in Migrations.
Valeriy Prokopchuk: Validators in Migrations.Valeriy Prokopchuk: Validators in Migrations.
Valeriy Prokopchuk: Validators in Migrations.
 
Sql Objects And PL/SQL
Sql Objects And PL/SQLSql Objects And PL/SQL
Sql Objects And PL/SQL
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricks
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 

Mais de Command Prompt., Inc

Mastering PostgreSQL Administration
Mastering PostgreSQL AdministrationMastering PostgreSQL Administration
Mastering PostgreSQL Administration
Command Prompt., Inc
 
Replication using PostgreSQL Replicator
Replication using PostgreSQL ReplicatorReplication using PostgreSQL Replicator
Replication using PostgreSQL Replicator
Command Prompt., Inc
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
Command Prompt., Inc
 

Mais de Command Prompt., Inc (20)

Howdah - An Application using Pylons, PostgreSQL, Simpycity and Exceptable
Howdah - An Application using Pylons, PostgreSQL, Simpycity and ExceptableHowdah - An Application using Pylons, PostgreSQL, Simpycity and Exceptable
Howdah - An Application using Pylons, PostgreSQL, Simpycity and Exceptable
 
Backup and-recovery2
Backup and-recovery2Backup and-recovery2
Backup and-recovery2
 
Mastering PostgreSQL Administration
Mastering PostgreSQL AdministrationMastering PostgreSQL Administration
Mastering PostgreSQL Administration
 
Temporal Data
Temporal DataTemporal Data
Temporal Data
 
Replication using PostgreSQL Replicator
Replication using PostgreSQL ReplicatorReplication using PostgreSQL Replicator
Replication using PostgreSQL Replicator
 
Go replicator
Go replicatorGo replicator
Go replicator
 
Pg migrator
Pg migratorPg migrator
Pg migrator
 
Python utilities for data presentation
Python utilities for data presentationPython utilities for data presentation
Python utilities for data presentation
 
PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...
PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...
PostgreSQL, Extensible to the Nth Degree: Functions, Languages, Types, Rules,...
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
Not Just UNIQUE: Generalized Index Constraints
Not Just UNIQUE: Generalized Index ConstraintsNot Just UNIQUE: Generalized Index Constraints
Not Just UNIQUE: Generalized Index Constraints
 
Implementing the Future of PostgreSQL Clustering with Tungsten
Implementing the Future of PostgreSQL Clustering with TungstenImplementing the Future of PostgreSQL Clustering with Tungsten
Implementing the Future of PostgreSQL Clustering with Tungsten
 
Elephant Roads: a tour of Postgres forks
Elephant Roads: a tour of Postgres forksElephant Roads: a tour of Postgres forks
Elephant Roads: a tour of Postgres forks
 
configuring a warm standby, the easy way
configuring a warm standby, the easy wayconfiguring a warm standby, the easy way
configuring a warm standby, the easy way
 
Bucardo
BucardoBucardo
Bucardo
 
Basic Query Tuning Primer
Basic Query Tuning PrimerBasic Query Tuning Primer
Basic Query Tuning Primer
 
A Practical Multi-Tenant Cluster
A Practical Multi-Tenant ClusterA Practical Multi-Tenant Cluster
A Practical Multi-Tenant Cluster
 
5 Steps to PostgreSQL Performance
5 Steps to PostgreSQL Performance5 Steps to PostgreSQL Performance
5 Steps to PostgreSQL Performance
 
Normalization: A Workshop for Everybody Pt. 2
Normalization: A Workshop for Everybody Pt. 2Normalization: A Workshop for Everybody Pt. 2
Normalization: A Workshop for Everybody Pt. 2
 
Normalization: A Workshop for Everybody Pt. 1
Normalization: A Workshop for Everybody Pt. 1Normalization: A Workshop for Everybody Pt. 1
Normalization: A Workshop for Everybody Pt. 1
 

Introduction to triggers

  • 1. Introduction to Triggers Robert Haas PostgreSQL East 2010
  • 2.
  • 3. Can fire on INSERT or UPDATE or DELETE or any combination.
  • 4. Can fire once per statement or for every row.
  • 5. Can fire BEFORE or AFTER the main operation.
  • 6. Example #1: Compute full name CREATE TABLE person ( id serial PRIMARY KEY, first_name varchar not null, middle_name varchar not null, last_name varchar not null, full_name varchar not null ); CREATE OR REPLACE FUNCTION compute_person_full_name() RETURNS trigger AS $$ BEGIN NEW.full_name := NEW.first_name || CASE WHEN NEW.middle_name = '' THEN '' ELSE ' ' || NEW.middle_name END || ' ' || NEW.last_name; RETURN NEW; END $$ LANGUAGE plpgsql;
  • 7. Example #1: Compute full name CREATE TRIGGER compute_person_full_name BEFORE INSERT OR UPDATE ON person FOR EACH ROW EXECUTE PROCEDURE compute_person_full_name(); INSERT INTO person (first_name, middle_name, last_name) VALUES ('Robert', 'M.', 'Haas'), ('Tom', '', 'Lane'); rhaas=# select full_name from person; full_name ---------------- Robert M. Haas Tom Lane (2 rows)
  • 8. Example #2: Counts and sums CREATE TABLE orders ( id serial primary key, customer_name varchar not null, number_of_items integer not null default 0, total_price numeric(12,2) not null default 0 ); CREATE TABLE order_items ( order_id integer not null references orders (id), item_name varchar not null, price numeric(12,2) not null default 0 );
  • 9. Example #2: Counts and sums CREATE OR REPLACE FUNCTION update_order_stats() RETURNS trigger AS $$ BEGIN IF (TG_OP != 'DELETE') THEN UPDATE orders SET number_of_items = number_of_items + 1, total_price = total_price + NEW.price WHERE id = NEW.order_id; END IF; IF (TG_OP != 'INSERT') THEN UPDATE orders SET number_of_items = number_of_items - 1, total_price = total_price - OLD.price WHERE id = OLD.order_id; END IF; RETURN NULL; END $$ LANGUAGE plpgsql;
  • 10. Example #2: Counts and sums CREATE TRIGGER update_order_stats AFTER INSERT OR UPDATE OR DELETE ON order_items FOR EACH ROW EXECUTE PROCEDURE update_order_stats();
  • 11. Example #3: Denormalization CREATE TABLE person ( id serial primary key, full_name varchar not null, is_project_manager boolean not null ); CREATE TABLE project ( id serial primary key, name varchar not null, project_manager_id integer not null references person (id) );
  • 12. Example #3: Denormalization CREATE TABLE person ( id serial primary key, full_name varchar not null, is_project_manager boolean not null ); CREATE TABLE project ( id serial primary key, name varchar not null, project_manager_id integer not null references person (id), is_project_manager boolean not null, CONSTRAINT pm_is_legal CHECK (is_project_manager) );
  • 13. Example #3: Denormalization CREATE OR REPLACE FUNCTION project_insert_or_update() RETURNS trigger AS $$ BEGIN SELECT pp.is_project_manager FROM person pp WHERE pp.id = NEW.project_manager_id FOR UPDATE INTO NEW.is_project_manager; RETURN NEW; END $$ LANGUAGE plpgsql; CREATE TRIGGER project_insert_or_update BEFORE INSERT OR UPDATE ON project FOR EACH ROW EXECUTE PROCEDURE project_insert_or_update();
  • 14. Example #3: Denormalization CREATE OR REPLACE FUNCTION person_update() RETURNS trigger AS $$ BEGIN IF (OLD.is_project_manager IS DISTINCT FROM NEW.is_project_manager) THEN UPDATE project SET is_project_manager = NEW.is_project_manager WHERE project_manager_id = NEW.id; END IF; RETURN NULL; END $$ LANGUAGE plpgsql; CREATE TRIGGER person_update AFTER UPDATE ON person FOR EACH ROW EXECUTE PROCEDURE person_update();
  • 15.