Introduction to Triggers using SQL

Similar documents
SQL NULL s, Constraints, Triggers

Introduction to the Oracle DBMS

Normal Form vs. Non-First Normal Form

SQL Databases Course. by Applied Technology Research Center. This course provides training for MySQL, Oracle, SQL Server and PostgreSQL databases.

Oracle Database: SQL and PL/SQL Fundamentals

14 Triggers / Embedded SQL

Introduction This document s purpose is to define Microsoft SQL server database design standards.

Oracle Database: SQL and PL/SQL Fundamentals NEW

Programming Database lectures for mathema

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Oracle Database: SQL and PL/SQL Fundamentals

Database Programming with PL/SQL: Learning Objectives

Instant SQL Programming

5. CHANGING STRUCTURE AND DATA

Databases What the Specification Says

Fine Grained Auditing In Oracle 10G

Oracle Database: SQL and PL/SQL Fundamentals NEW

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

Oracle SQL. Course Summary. Duration. Objectives

Oracle 10g PL/SQL Training

How To Create A Table In Sql (Ahem)

A basic create statement for a simple student table would look like the following.

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

ETL Process in Data Warehouse. G.Lakshmi Priya & Razia Sultana.A Assistant Professor/IT

ATTACHMENT 6 SQL Server 2012 Programming Standards

Demystified CONTENTS Acknowledgments xvii Introduction xix CHAPTER 1 Database Fundamentals CHAPTER 2 Exploring Relational Database Components

php tek 2006 in Orlando Florida Lukas Kahwe Smith

The Relational Model. Why Study the Relational Model? Relational Database: Definitions. Chapter 3

SQL. by Steven Holzner, Ph.D. ALPHA. A member of Penguin Group (USA) Inc.

CS2Bh: Current Technologies. Introduction to XML and Relational Databases. The Relational Model. The relational model

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

CSC 443 Data Base Management Systems. Basic SQL

CS143 Notes: Views & Authorization

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Structure101g SQL Flavor

ETL Overview. Extract, Transform, Load (ETL) Refreshment Workflow. The ETL Process. General ETL issues. MS Integration Services

Commercial Database Software Development- A review.

Maintaining Stored Procedures in Database Application

Procedural Extension to SQL using Triggers. SS Chung

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Conventional Files versus the Database. Files versus Database. Pros and Cons of Conventional Files. Pros and Cons of Databases. Fields (continued)

DBMS / Business Intelligence, SQL Server

ICAB4136B Use structured query language to create database structures and manipulate data

Oracle Database 10g: Program with PL/SQL

CHAPTER 2 DATABASE MANAGEMENT SYSTEM AND SECURITY

1 File Processing Systems

T-SQL STANDARD ELEMENTS

SQL Data Definition. Database Systems Lecture 5 Natasha Alechina

Duration Vendor Audience 5 Days Oracle Developers, Technical Consultants, Database Administrators and System Analysts

IENG2004 Industrial Database and Systems Design. Microsoft Access I. What is Microsoft Access? Architecture of Microsoft Access

Introduction to Databases

3. Relational Model and Relational Algebra

Database Schema Deployment. Lukas Smith - lukas@liip.ch CodeWorks PHP on the ROAD

MySQL for Beginners Ed 3

Virtual Private Database Features in Oracle 10g.

Geodatabase Programming with SQL

3.GETTING STARTED WITH ORACLE8i

Basic Concepts of Database Systems

Database Systems. Lecture 1: Introduction

news from Tom Bacon about Monday's lecture

Driver for JDBC Implementation Guide

SQL Server An Overview

Managing Objects with Data Dictionary Views. Copyright 2006, Oracle. All rights reserved.

5.1 Database Schema Schema Generation in SQL

SQL Tables, Keys, Views, Indexes

Partitioning under the hood in MySQL 5.5

Oracle Database 12c: Introduction to SQL Ed 1.1

The Entity-Relationship Model

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems

Databasesystemer, forår 2005 IT Universitetet i København. Forelæsning 3: Business rules, constraints & triggers. 3. marts 2005

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

Microsoft SQL Server Security & Auditing. March 23, 2011 ISACA Chapter Meeting

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

New SQL Features in Firebird 3

Oracle Database 10g Express

CSE 530A Database Management Systems. Introduction. Washington University Fall 2013

CSI 2132 Lab 3. Outline 09/02/2012. More on SQL. Destroying and Altering Relations. Exercise: DROP TABLE ALTER TABLE SELECT

Netezza SQL Class Outline

Linas Virbalas Continuent, Inc.

HP Quality Center. Upgrade Preparation Guide

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Zero Downtime Deployments with Database Migrations. Bob Feldbauer

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1

Software Engineering Techniques

Database 10g Edition: All possible 10g features, either bundled or available at additional cost.

Database Query 1: SQL Basics

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1

Programming in postgresql with PL/pgSQL. Procedural Language extension to postgresql

The first time through running an Ad Hoc query or Stored Procedure, SQL Server will go through each of the following steps.

The Relational Model. Why Study the Relational Model?

Using SAS as a Relational Database

Oracle to MySQL Migration

Intermediate SQL C H A P T E R4. Practice Exercises. 4.1 Write the following queries in SQL:

IT2305 Database Systems I (Compulsory)

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Oracle Database: Develop PL/SQL Program Units

Logi Ad Hoc Reporting System Administration Guide

SQL Server Database Coding Standards and Guidelines

Transcription:

Introduction to Triggers using SQL Kristian Torp Department of Computer Science Aalborg University www.cs.aau.dk/ torp torp@cs.aau.dk November 24, 2011 daisy.aau.dk Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 1 / 63

Outline 1 A Case Study: General Concepts 2 A Case Study: With Code 3 Overview and Motivation Usage 4 Trigger Types 5 Case Study: Instead of Triggers 6 Managing Triggers 7 Summary Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 2 / 63

Learning Outcomes Goals Why? Note Understand basic trigger mechanism Understand pros and cons of triggers See procedural code in a DBMS Widely used in database applications Widely supported in most DBMSs Concepts presented are general Code presented is PostgreSQL specific One is Oracle specific because not supported on PostgreSQL Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 3 / 63

Two Minute Discussion Usage of Triggers Have you use triggers before? Have you used triggers for deriving temporal information? Does your organization have any policies wrt. triggers? Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 4 / 63

Outline 1 A Case Study: General Concepts 2 A Case Study: With Code 3 Overview and Motivation Usage 4 Trigger Types 5 Case Study: Instead of Triggers 6 Managing Triggers 7 Summary Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 5 / 63

Case Study: Handling Football Players Note Keep track of the players in all football clubs Keep a history of where each player has been playing Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 6 / 63

Case Study: Handling Football Players Note Keep track of the players in all football clubs Keep a history of where each player has been playing At Time 10 AaB buys the p l a y e r Wurtz i n s e r t i n t o p l a y e r values Wurtz, AaB ) ; Player Table Log Table Name Wurtz Club AaB Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 6 / 63

Case Study: Handling Football Players Note Keep track of the players in all football clubs Keep a history of where each player has been playing At Time 10 AaB buys the p l a y e r Wurtz i n s e r t i n t o p l a y e r values Wurtz, AaB ) ; Player Table Log Table Name Wurtz Club AaB Name Club start date stop date Wurtz AaB 10 null Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 6 / 63

Case Study: Handling Football Players Note Keep track of the players in all football clubs Keep a history of where each player has been playing At Time 10 AaB buys the p l a y e r Wurtz i n s e r t i n t o p l a y e r values Wurtz, AaB ) ; Player Table Log Table Note Name Wurtz Club AaB Name Club start date stop date Wurtz AaB 10 null All values are copied from the table player to the table log A value is automatically provided for the column start date A value cannot be provided for the column stop date Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 6 / 63

Case Study: Handling Football Players, cont. At Time 12 AaB buys the p l a y e r Caca i n s e r t i n t o p l a y e r values Caca, AaB ) ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 7 / 63

Case Study: Handling Football Players, cont. At Time 12 AaB buys the p l a y e r Caca i n s e r t i n t o p l a y e r values Caca, AaB ) ; Player Table Log Table Name Wurtz Caca Club AaB AaB Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 7 / 63

Case Study: Handling Football Players, cont. At Time 12 AaB buys the p l a y e r Caca i n s e r t i n t o p l a y e r values Caca, AaB ) ; Player Table Log Table Name Wurtz Caca Club AaB AaB Name Club start date stop date Wurtz AaB 10 null Caca AaB 12 null Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 7 / 63

Case Study: Handling Football Players, cont. At Time 12 AaB buys the p l a y e r Caca i n s e r t i n t o p l a y e r values Caca, AaB ) ; Player Table Log Table Name Wurtz Caca Club AaB AaB Name Club start date stop date Wurtz AaB 10 null Caca AaB 12 null Note Similar to the first insert Start date is the current-time, stop date is unknown/not specified/tbd Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 7 / 63

Case Study: Handling Football Players, cont. At Time 15 AaB s e l l s Wurtz to FCK update player set club = FCK where name = Wurtz ; Player Table Log Table Name Wurtz Caca Club FCK AaB Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 8 / 63

Case Study: Handling Football Players, cont. At Time 15 AaB s e l l s Wurtz to FCK update player set club = FCK where name = Wurtz ; Player Table Log Table Name Wurtz Caca Club FCK AaB Name Club start date stop date Wurtz AaB 10 15 Caca AaB 12 null Wurtz FCK 15 null Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 8 / 63

Case Study: Handling Football Players, cont. At Time 15 AaB s e l l s Wurtz to FCK update player set club = FCK where name = Wurtz ; Player Table Log Table Name Wurtz Caca Club FCK AaB Name Club start date stop date Wurtz AaB 10 15 Caca AaB 12 null Wurtz FCK 15 null Note The table player is naturally updated The column stop date for the first Wurtz row is updated in the log table A new row is entered into the log table Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 8 / 63

Case Study: Handling Football Players, cont. At Time 25 AaB s e l l s Caca to OB update player set club = OB where name = Caca ; Player Table Log Table Name Wurtz Caca Club FCK OB Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 9 / 63

Case Study: Handling Football Players, cont. At Time 25 AaB s e l l s Caca to OB update player set club = OB where name = Caca ; Player Table Log Table Name Wurtz Caca Club FCK OB Name Club start date stop date Wurtz AaB 10 15 Caca AaB 12 25 Wurtz FCK 15 null Caca OB 25 null Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 9 / 63

Case Study: Handling Football Players, cont. At Time 25 AaB s e l l s Caca to OB update player set club = OB where name = Caca ; Player Table Log Table Note Name Wurtz Caca Club FCK OB Similar to the first update Name Club start date stop date Wurtz AaB 10 15 Caca AaB 12 25 Wurtz FCK 15 null Caca OB 25 null Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 9 / 63

Case Study: Handling Football Players, cont. At Time 27 AaB buys Wurtz back from FCK update player set club = AaB where name = Wurtz ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 10 / 63

Case Study: Handling Football Players, cont. At Time 27 AaB buys Wurtz back from FCK update player set club = AaB where name = Wurtz ; Player Table Log Table Name Wurtz Caca Club AaB OB Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 10 / 63

Case Study: Handling Football Players, cont. At Time 27 AaB buys Wurtz back from FCK update player set club = AaB where name = Wurtz ; Player Table Log Table Name Wurtz Caca Club AaB OB Name Club start date stop date Wurtz AaB 10 15 Caca AaB 12 25 Wurtz FCK 15 27 Caca OB 25 null Wurtz AaB 27 null Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 10 / 63

Case Study: Handling Football Players, cont. At Time 27 AaB buys Wurtz back from FCK update player set club = AaB where name = Wurtz ; Player Table Log Table Name Wurtz Caca Club AaB OB Name Club start date stop date Wurtz AaB 10 15 Caca AaB 12 25 Wurtz FCK 15 27 Caca OB 25 null Wurtz AaB 27 null Note A new Wurtz row is started in the log table Still, similar to the previous updates Basically a delete followed by an insert Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 10 / 63

Case Study: Handling Football Players, cont. At Time 62 Wurtz r e t i r e s as an a c t i v e f o o t b a l l p l a y e r d e l e te from p l a y e r name = Wurtz ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 11 / 63

Case Study: Handling Football Players, cont. At Time 62 Wurtz r e t i r e s as an a c t i v e f o o t b a l l p l a y e r d e l e te from p l a y e r name = Wurtz ; Player Table Log Table Name Caca Club OB Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 11 / 63

Case Study: Handling Football Players, cont. At Time 62 Wurtz r e t i r e s as an a c t i v e f o o t b a l l p l a y e r d e l e te from p l a y e r name = Wurtz ; Player Table Log Table Name Caca Club OB Name Club start date stop date Wurtz AaB 10 15 Caca AaB 12 25 Wurtz FCK 15 27 Caca OB 25 null Wurtz AaB 27 62 Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 11 / 63

Case Study: Handling Football Players, cont. At Time 62 Wurtz r e t i r e s as an a c t i v e f o o t b a l l p l a y e r d e l e te from p l a y e r name = Wurtz ; Player Table Log Table Name Caca Club OB Name Club start date stop date Wurtz AaB 10 15 Caca AaB 12 25 Wurtz FCK 15 27 Caca OB 25 null Wurtz AaB 27 62 Note The Wurtz row is deleted from the player table The value column stop date is update for the last Wurtz row Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 11 / 63

Quiz: Handling Football Players Final Tables Player Table Name Club Caca OB Log Table Name Club start date stop date Wurtz AaB 10 15 Caca AaB 12 25 Wurtz FCK 15 27 Caca OB 25 null Wurtz AaB 27 62 Questions How to you identify the active players in the log table? What is the interpretation of the null values in the log table? What is the primary key of the log table? In how many clubs can a single player be active at once? When are rows deleted from the log table? Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 12 / 63

Outline 1 A Case Study: General Concepts 2 A Case Study: With Code 3 Overview and Motivation Usage 4 Trigger Types 5 Case Study: Instead of Triggers 6 Managing Triggers 7 Summary Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 13 / 63

Audit Trail Example create t a b l e p l a y e r ( p l a y e r i d i n t primary key, player name varchar ( 50) not n u l l, d a t e o f b i r t h date, club varchar ( 50) not n u l l ) ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 14 / 63

Audit Trail Example create t a b l e p l a y e r ( p l a y e r i d i n t primary key, player name varchar ( 50) not n u l l, d a t e o f b i r t h date, club varchar ( 50) not n u l l ) ; create t a b l e p l a y e r l o g ( p l a y e r i d i n t not n u l l, player name varchar ( 50) not n u l l, d a t e o f b i r t h date, club varchar ( 50) not n u l l, s t a r t d a t e date not n u l l, stop date date ) ; Note The primary keys are not the same in the two tables The stop date column is nullable Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 14 / 63

Insert Trigger create or replace f u n c t i o n f p l a y e r i n s ( ) r e t u r n s t r i g g e r as $$ begin i n s e r t i n t o p l a y e r l o g values ( new. p l a y e r i d, new. player name, new. d a t e o f b i r t h, new. club, c u r r e n t d a t e, n u l l ) ; r e t u r n new ; end ; $$ language p l p g s q l ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 15 / 63

Insert Trigger create or replace f u n c t i o n f p l a y e r i n s ( ) r e t u r n s t r i g g e r as $$ begin i n s e r t i n t o p l a y e r l o g values ( new. p l a y e r i d, new. player name, new. d a t e o f b i r t h, new. club, c u r r e n t d a t e, n u l l ) ; r e t u r n new ; end ; $$ language p l p g s q l ; create t r i g g e r p l a y e r i n s a f t e r i n s e r t on p l a y e r f o r each row execute procedure f p l a y e r i n s ( ) ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 15 / 63

Insert Trigger create or replace f u n c t i o n f p l a y e r i n s ( ) r e t u r n s t r i g g e r as $$ begin i n s e r t i n t o p l a y e r l o g values ( new. p l a y e r i d, new. player name, new. d a t e o f b i r t h, new. club, c u r r e n t d a t e, n u l l ) ; r e t u r n new ; end ; $$ language p l p g s q l ; create t r i g g e r p l a y e r i n s a f t e r i n s e r t on p l a y e r f o r each row execute procedure f p l a y e r i n s ( ) ; Note The new syntax The null is inserted into the stop date column The current date is give me the current date Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 15 / 63

Let Dreams Come Trough i n s e r t i n t o p l a y e r values (101, Wurtz, 1987 03 03, AaB ) ; i n s e r t i n t o p l a y e r values (102, Messi, 1988 02 13, AaB ) ; update player set club = Barcelona where player name = Messi ; d e l e te from p l a y e r where p l a y e r i d = 101; Note The clients cannot see the derived information Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 16 / 63

Delete Trigger create or replace f u n c t i o n f p l a y e r d e l ( ) r e t u r n s t r i g g e r as $$ begin update p l a y e r l o g set stop date = c u r r e n t d a t e where p l a y e r i d = old. p l a y e r i d and stop date i s n u l l ; r e t u r n old ; end ; $$ language p l p g s q l ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 17 / 63

Delete Trigger create or replace f u n c t i o n f p l a y e r d e l ( ) r e t u r n s t r i g g e r as $$ begin update p l a y e r l o g set stop date = c u r r e n t d a t e where p l a y e r i d = old. p l a y e r i d and stop date i s n u l l ; r e t u r n old ; end ; $$ language p l p g s q l ; create t r i g g e r p l a y e r d e l a f t e r d e l e t e on p l a y e r f o r each row execute procedure f p l a y e r d e l ( ) ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 17 / 63

Delete Trigger create or replace f u n c t i o n f p l a y e r d e l ( ) r e t u r n s t r i g g e r as $$ begin update p l a y e r l o g set stop date = c u r r e n t d a t e where p l a y e r i d = old. p l a y e r i d and stop date i s n u l l ; r e t u r n old ; end ; $$ language p l p g s q l ; create t r i g g e r p l a y e r d e l a f t e r d e l e t e on p l a y e r f o r each row execute procedure f p l a y e r d e l ( ) ; Note This trigger is only fired for delete statements Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 17 / 63

Update Trigger create or replace f u n c t i o n f p l a y e r u p d ( ) r e t u r n s t r i g g e r as $$ begin stop old update p l a y e r l o g set stop date = c u r r e n t d a t e where p l a y e r i d = old. p l a y e r i d and stop date i s n u l l ; s t a r t new i n s e r t i n t o p l a y e r l o g values ( new. p l a y e r i d, new. player name, new. d a t e o f b i r t h, new. club, c u r r e n t d a t e, n u l l ) ; r e t u r n new ; end ; $$ language p l p g s q l ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 18 / 63

Update Trigger create or replace f u n c t i o n f p l a y e r u p d ( ) r e t u r n s t r i g g e r as $$ begin stop old update p l a y e r l o g set stop date = c u r r e n t d a t e where p l a y e r i d = old. p l a y e r i d and stop date i s n u l l ; s t a r t new i n s e r t i n t o p l a y e r l o g values ( new. p l a y e r i d, new. player name, new. d a t e o f b i r t h, new. club, c u r r e n t d a t e, n u l l ) ; r e t u r n new ; end ; $$ language p l p g s q l ; create t r i g g e r player upd a f t e r update on p l a y e r f o r each row execute procedure f p l a y e r u p d ( ) ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 18 / 63

Outline 1 A Case Study: General Concepts 2 A Case Study: With Code 3 Overview and Motivation Usage 4 Trigger Types 5 Case Study: Instead of Triggers 6 Managing Triggers 7 Summary Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 19 / 63

Overview Triggers are executed implicitly When insert, update, or delete statements are executed Similar to a stored procedure, i.e., code Can make call-outs to procedural code Connected to a table In some DBMSs also on a view Triggers are side effects Normally considered very bad in software engineering Triggers not part of SQL-92 first introduced in SQL-1999. Many DBMS have supported triggers for much longer therefore limited standard compliance Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 20 / 63

Transition Tables A set of internal tables that the DBMS uses to keep track of modifications made by a transaction Four transition tables for each real table R during the execution of a transaction T i R inserted R deleted R updatedold R updatednew Contains the rows inserted into R during T i Contains the rows deleted from R during T i Contains the values of updated rows before T i Contains the values of updated rows after T i R new = R old \ R deleted \ R updatedold R inserted R updatednew Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 21 / 63

Outline 1 A Case Study: General Concepts 2 A Case Study: With Code 3 Overview and Motivation Usage 4 Trigger Types 5 Case Study: Instead of Triggers 6 Managing Triggers 7 Summary Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 22 / 63

Usage To generate derived values Sum of amount of order lines To create an audit trail Think STASI To enforce complex business rules When a customer buys goods for more than 300$ then give a 10% discount To generate statistics How often is a table modified To provide event logging Each time a new house is inserted in the for sale table notify potential customers Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 23 / 63

Another Example: Compute Derived Values I User Requirements Wants to store order and order lines The total amount of an order is derived from order lines The total amount is often queried Solution Store the derived information total amount with the order Makes it fast to look-up orders based on total amount Use triggers to automatically derived the total amount Convenient for the customers Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 24 / 63

Another Example: Compute Derived Values II create t a b l e oorder ( o o r d e r i d i n t primary key, customer name varchar2 (50) not n u l l, amount number (10,2) d e f a u l t 0 not n u l l, c o n s t r a i n t amount gt zero check ( amount > 0) d e f e r r a b l e i n i t i a l l y immediate ) ; create t a b l e o o r d e r l i n e ( o o r d e r i d i n t not n u l l, l i n e n o i n t not n u l l check ( l i n e n o > 0 ), dsc varchar2 (50) not n u l l, q u a n t i t y i n t not n u l l check ( q u a n t i t y > 0 ), price each number ( 6, 2 ) not n u l l check ( price each > 0. 0 ), c o n s t r a i n t o l p k primary key ( oorder i d, l i n e n o ), c o n s t r a i n t o l o f k f o r e i g n key ( o o r d e r i d ) references oorder ( o o r d e r i d ) ) ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 25 / 63

Another Example: Compute Derived Values III create or replace t r i g g e r set amount a f t e r i n s e r t or update or d e l e t e on o o r d e r l i n e f o r each row declare v a l number (10,2) := 0; oid i n t ; begin i f i n s e r t i n g then v a l := : new. q u a n t i t y : new. price each ; oid := : new. o o r d e r i d ; e l s i f updating then v a l := : new. q u a n t i t y : new. price each : old. q u a n t i t y : old. price each ; oid := : new. o o r d e r i d ; e l s i f d e l e t i n g then v a l := 0 : old. q u a n t i t y : old. price each ; oid := : old. o o r d e r i d ; end i f ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 26 / 63

Another Example: Compute Derived Values IV update oorder set amount = amount + v a l where o o r d e r i d = oid ; end ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 27 / 63

A Bad Example create or replace t r i g g e r set amount2 a f t e r i n s e r t on oorder f o r each row declare tmp amount number ( 1 0, 2 ) ; begin s e l e c t sum( q u a n t i t y price each ) i n t o tmp amount from o o r d e r l i n e where o o r d e r i d = : new. o o r d e r i d ; update oorder set amount = tmp amount where o o r d e r i d = : new. o o r d e r i d ; end ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 28 / 63

Mutating Triggers Insert trigger trigger Note A trigger can make an insert, this new insert may fire a trigger, etc Cannot have cycles will cause a mutating trigger Causes a runtime error

Mutating Triggers Insert trigger trigger trigger Note A trigger can make an insert, this new insert may fire a trigger, etc Cannot have cycles will cause a mutating trigger Causes a runtime error Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 29 / 63

Correct Usage Can have multiple triggers on a table Order of execution cannot be specified Can be hard to understand a database schema with many triggers A trigger cannot modify the table that it is associated with May cause an infinite loop of trigger executions Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 30 / 63

Correct Usage Can have multiple triggers on a table Order of execution cannot be specified Can be hard to understand a database schema with many triggers A trigger cannot modify the table that it is associated with May cause an infinite loop of trigger executions Not for Integrity Constraints Do not use triggers for enforcing referential integrity! Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 30 / 63

Trigger Parts Event on update of <table name>... Condition Must evaluate to true Action Code that is executed Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 31 / 63

Two Minute Discussion Triggers vs. Application Code Why not move trigger logic to applications? Discuss the pros and cons of this Would you like to have a trigger on select statements When and where could it be useful? Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 32 / 63

Outline 1 A Case Study: General Concepts 2 A Case Study: With Code 3 Overview and Motivation Usage 4 Trigger Types 5 Case Study: Instead of Triggers 6 Managing Triggers 7 Summary Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 33 / 63

Trigger Types I { row statement } { before after } A total of four trigger types Some DBMSs support INSTEAD OF triggers Very powerful, e.g., to make view updateable or hide legacy code Before triggers can be used for preconditions After triggers can be used for postconditions Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 34 / 63

Trigger Types II Statement level triggers always fires Row trigger fires only if rows are modified Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 35 / 63

Row Triggers: Setup Table Row Triggers Executed once for each row modified by triggering statement If no rows modified trigger is not executed Example (Create Table) create t a b l e x ( i i n t primary key, j i n t not n u l l ) ; Example (Populate Table) i n s e r t i n t o x values ( 1, 1 ) ; i n s e r t i n t o x values ( 2, 2 ) ; i n s e r t i n t o x values ( 3, 3 ) ; commit ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 36 / 63

Before Row Trigger Example (Stored Procedure) update row before t r i g g e r create or replace f u n c t i o n f x u p d b e f o r e r o w ( ) r e t u r n s t r i g g e r as $$ begin r a i s e n o t i c e before row ; r e t u r n new ; end ; $$ language p l p g s q l ; Example (Before Row Trigger) create t r i g g e r x upd before row before update on x f o r each row execute procedure f x u p d b e f o r e r o w ( ) ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 37 / 63

After Row Trigger Example (Stored Procedure) update row a f t e r t r i g g e r create or replace f u n c t i o n f x u p d a f t e r r o w ( ) r e t u r n s t r i g g e r as $$ begin r a i s e n o t i c e a f t e r row ; r e t u r n new ; end ; $$ language p l p g s q l ; Example (After Row Trigger) create t r i g g e r x u p d a f t e r r o w a f t e r update on x f o r each row execute procedure f x u p d a f t e r r o w ( ) ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 38 / 63

Statement Triggers Statement-Level Triggers Executed once for each triggering statement Executed even if no rows are modified Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 39 / 63

Statement Triggers Statement-Level Triggers Executed once for each triggering statement Executed even if no rows are modified Example (Stored Procedure) create or replace f u n c t i o n f x u p d b e f o r e s t m t ( ) r e t u r n s t r i g g e r as $$ begin r a i s e n o t i c e before stmt ; r e t u r n new ; end ; $$ language p l p g s q l ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 39 / 63

Statement Triggers Statement-Level Triggers Executed once for each triggering statement Executed even if no rows are modified Example (Stored Procedure) create or replace f u n c t i o n f x u p d b e f o r e s t m t ( ) r e t u r n s t r i g g e r as $$ begin r a i s e n o t i c e before stmt ; r e t u r n new ; end ; $$ language p l p g s q l ; Example (Before Statement Trigger) create t r i g g e r x upd before stmt before update on x f o r each statement execute procedure f x u p d b e f o r e s t m t ( ) ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 39 / 63

After Statement Trigger Example (Stored Procedure) create or replace f u n c t i o n f x u p d a f t e r s t m t ( ) r e t u r n s t r i g g e r as $$ begin r a i s e n o t i c e a f t e r stmt ; r e t u r n new ; end ; $$ language p l p g s q l ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 40 / 63

After Statement Trigger Example (Stored Procedure) create or replace f u n c t i o n f x u p d a f t e r s t m t ( ) r e t u r n s t r i g g e r as $$ begin r a i s e n o t i c e a f t e r stmt ; r e t u r n new ; end ; $$ language p l p g s q l ; Example (After Statement Trigger) create t r i g g e r x u p d a f t e r s t m t a f t e r update on x f o r each statement execute procedure f x u p d a f t e r s t m t ( ) ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 40 / 63

Other Types of Triggers System Event Triggers At database start up or shut down When a DBMS fails User-Event Ttriggers On logon and logoff When DML statement executed When DDL statement executed Note These types of triggers are not part of the SQL standard! Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 41 / 63

Outline 1 A Case Study: General Concepts 2 A Case Study: With Code 3 Overview and Motivation Usage 4 Trigger Types 5 Case Study: Instead of Triggers 6 Managing Triggers 7 Summary Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 42 / 63

Introduction Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 43 / 63

Very Strong Concept Can make all views updateable Can make modifications easier to understand Can wrap ugly database design, by nice design Can make the changes work for multiple programming languages Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 44 / 63

Mini University Schema Customer Requirements Wants to have a readable access to students status without joins A student name must have the column name name A student status must the column name status Wants to be able to modify a students status using strings Challenges name is a reserved word status is also a name of an exiting table Currently needs to join to get readable status of students Currently needs to memorize the int values used for status Solutions Create a view Use instead-of-triggers on view Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 45 / 63

Create the View Example (The View) create or replace view s t u d e n t s t a t u s as s e l e c t stu. s name as name, sta. dsc as s t a t u s from student stu, s t a t u s sta where stu. s t a t i d = sta. s t a t i d Note The name and status columns are in quotes A simple view statement Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 46 / 63

Insert Function I create or replace f u n c t i o n f i n s s t u d e n t s t a t u s ( ) r e t u r n s t r i g g e r as $$ declare v s t a t i d s t a t u s. s t a t i d%type ; v s i d student. s i d%type ; v no numeric ; begin check t h a t the s t a t u s column e x i s t s i n the s t a t u s t a b l e begin s e l e c t sta. s t a t i d i n t o v s t a t i d from s t a t u s sta where sta. dsc = lower ( new. s t a t u s ) ; exception when no data found then n u l l ; Need to r a i s e an e r r o r!!!! end ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 47 / 63

Insert Function II f i n d i f there are any students with the same name s e l e c t count ( stu. s i d ) i n t o v no from student stu where stu. s name = new. name ; i f v no > 0 then n u l l ; r a i s e an e r r o r end i f ; f i n d a new student i d s e l e c t coalesce (max( stu. s i d ), 0 ) i n t o v s i d from student stu ; v s i d := v s i d + 1; i n s e r t i n t o student values ( v sid, new. name, v s t a t i d ) ; r e t u r n new ; end ; $$ language p l p g s q l ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 48 / 63

Insert Instead-Of-Trigger Example (Create Trigger) create t r i g g e r i n s s t u d e n t s t a t u s instead of i n s e r t on s t u d e n t s t a t u s f o r each row execute procedure f i n s s t u d e n t s t a t u s ( ) ; Note All inserts on student status will call stored procedure View is now updateable Only insert supported Very few limit on what can be done in stored procedure Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 49 / 63

Delete Function create or replace f u n c t i o n f d e l s t u d e n t s t a t u s ( ) r e t u r n s t r i g g e r as $$ declare v s t a t i d s t a t u s. s t a t i d%type ; begin begin s e l e c t sta. s t a t i d i n t o v s t a t i d from s t a t u s sta where sta. dsc = lower ( old. s t a t u s ) ; exception when no data found then n u l l ; Need to r a i s e an e r r o r!!!! end ; delete from student where s name = old. name and s t a t i d = v s t a t i d ; r e t u r n new ; end ; $$ language p l p g s q l ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 50 / 63

Delete Instead-Of-Trigger Example (Create Trigger) create t r i g g e r d e l s t u d e n t s t a t u s instead of d e l e t e on s t u d e n t s t a t u s f o r each row execute procedure f d e l s t u d e n t s t a t u s ( ) ; Note All delete on student status will call stored procedure Similar idea as for the insert instead-of trigger Trigger for update can be defined in a similar way Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 51 / 63

Use the Updateable View Example (Update Through View) i n s e r t through the view i n s e r t i n t o s t u d e n t s t a t u s values ( Curt, a c t i v e ) ; delete through the view d e l e te from s t u d e n t s t a t u s where name = Ann ; Note View now behave (almost) like a table Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 52 / 63

Summary: Instead-Of Triggers Summary Note A very powerful concept Generally well-supported most DBMSs Old or ugly design can removed and old application logic retained Insert, update, and delete can be combined in a single stored procedure Should make sense! Too many triggers makes the database very hard to maintain! Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 53 / 63

Outline 1 A Case Study: General Concepts 2 A Case Study: With Code 3 Overview and Motivation Usage 4 Trigger Types 5 Case Study: Instead of Triggers 6 Managing Triggers 7 Summary Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 54 / 63

Enabling and Disabling Triggers Example (Disable Triggers) d i s a b l e s i n g l e t r i g g e r a l t e r t a b l e x d i s a b l e t r i g g e r x u p d a f t e r r o w ; d i s a b l e a l l t r i g g e r s on a s i n g l e t a b l e a l t e r t a b l e x d i s a b l e t r i g g e r a l l ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 55 / 63

Enabling and Disabling Triggers Example (Disable Triggers) d i s a b l e s i n g l e t r i g g e r a l t e r t a b l e x d i s a b l e t r i g g e r x u p d a f t e r r o w ; d i s a b l e a l l t r i g g e r s on a s i n g l e t a b l e a l t e r t a b l e x d i s a b l e t r i g g e r a l l ; Example (Enable Triggers) enable s i n g l e t r i g g e r a l t e r t a b l e x enable t r i g g e r x u p d a f t e r r o w ; enable a l l t r i g g e r s on a s i n g l e t a b l e a l t e r t a b l e x enable t r i g g e r a l l ; Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 55 / 63

Enabling and Disabling Triggers Example (Disable Triggers) d i s a b l e s i n g l e t r i g g e r a l t e r t a b l e x d i s a b l e t r i g g e r x u p d a f t e r r o w ; d i s a b l e a l l t r i g g e r s on a s i n g l e t a b l e a l t e r t a b l e x d i s a b l e t r i g g e r a l l ; Example (Enable Triggers) enable s i n g l e t r i g g e r a l t e r t a b l e x enable t r i g g e r x u p d a f t e r r o w ; enable a l l t r i g g e r s on a s i n g l e t a b l e a l t e r t a b l e x enable t r i g g e r a l l ; Note Be careful, know why a trigger is disabled! Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 55 / 63

Trigger Metadata Example (Find Information on All Triggers) s e l e c t from information schema. t r i g g e r s ; Note Cannot see if trigger is enabled/disabled Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 56 / 63

Trigger Metadata Example (Find Information on All Triggers) s e l e c t from information schema. t r i g g e r s ; Note Cannot see if trigger is enabled/disabled Example (Find All Disabled Triggers) s e l e c t p. from p g t r i g g e r as p where p. tgenabled = D Note This is PostgreSQL specific Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 56 / 63

Dropping Triggers Example (Find Information on All Triggers) Drop row t r i g g e r on t a b l e drop t r i g g e r x u p d a f t e r r o w on x ; Drop instead of t r i g g e r on view drop t r i g g e r i n s s t u d e n t s t a t u s on s t u d e n t s t a t u s ; Note The triggers are now removed from the database schema! There is no syntax for dropping all triggers on a table! Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 57 / 63

Summary: Trigger Management Summary Note Triggers can be enabled/disabled When table/view dropped all triggers automatically dropped A view cannot always altered therefore triggers on views cannot be altered Disabling triggers can lead to hard to find bugs Many DBMSs have vendor specific extension for triggers Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 58 / 63

Outline 1 A Case Study: General Concepts 2 A Case Study: With Code 3 Overview and Motivation Usage 4 Trigger Types 5 Case Study: Instead of Triggers 6 Managing Triggers 7 Summary Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 59 / 63

Use or Avoid Triggers? Use Triggers For any type of logging Also called auditing For deriving information For advanced checking that cannot be implemented using integrity constraints For automating tasks associated with modification statements For simple data replication To wrap bad database design Avoid Triggers That must be retained of backwards compatibility reasons When a declarative statement can be used Triggers are procedural When foreign key or check statement can be used Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 60 / 63

Summary E-C-A rules (event-condition-action) Triggers are called implicitly Side-effects {before, after} {row, statement} Instead-of triggers interesting for hiding legacy design Very powerful concept Avoid transaction handling in triggers (commit or rollback) Do not overuse the number of triggers Can make it very hard to find out what a system does Many vendor specific extensions for trigger functionality Because very late before added to the standard Core idea large overlap between DBMSs Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 61 / 63

Additional Information Note PL/pgSQL www.postgres.cz/index.php/pl/pgsql_(en) How to write the trigger stored procedures Triggers in MySQL http://forge.mysql.com/wiki/triggers Good overview, well explained, linear readable document Exploring SQL Server Triggers msdn.microsoft.com/en-us/magazine/cc164047.aspx Good introduction, quite readable Triggers in Oracle www.java2s.com/tutorial/oracle/0560 Trigger/Catalog0560 Trigger.htm Only code, many details, Oracle specific Cannot find a good general introduction to triggers Send me an email if you are aware of such an introduction Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 62 / 63

Two-Minute Digesting Questions Why can you not specify the order in which triggers execute? Why can triggers not be stand-alone database objects? Why are triggers part of the transaction? You have the same logic that must be executed by a trigger and sometimes explicitly what do you do? Kristian Torp (Aalborg University) Introduction to Triggers using SQL November 24, 2011 63 / 63