SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Intro to Stored Procedures in PostgreSQL
개발팀
Why use Stored Procedures?
• Reusability
– Avoid rewriting subqueries and improve readability.
– If you can't store a query in a library that all the applications can access,
you can put that query in a stored procedure.
• Separation of duties
– You don't trust non-DBA's to write queries.
• Data integrity
– Use triggers or constraints to prevent bad data from entering.
– Run several interdependent queries in a transaction in a single stored procedure.
• Event handling
– Log changes.
– Notify other systems of new data.
Why NOT use Stored Procedures?
• Views may be all you need.
• An object-relational mapper (ORM) can help write queries safely.
• Difficult to version control stored procedures.
• Software rollouts may require more DB changes.
• Could slow software development process.
Writing a Stored Procedure in SQL
Writing Stored Procedure in PL/pgSQL
Executing get_last_name()
Triggers
• Triggers can be used to call a stored procedure before or after an INSERT, UPDATE, or DELETE
statement on a table.
• Triggers can be called once per each row affected or once per each INSERT, UPDATE, or DELETE
statement.
• Triggers on many different tables can share the same stored procedure.
Automatic Variables in Triggers
• NEW: The new row for INSERT/UPDATE statements. It is NULL in statement-level triggers.
• OLD: The old row for UPDATE/DELETE statements. It is NULL in statement-level triggers.
• TG_NAME: Name of the trigger.
• TG_WHEN: 'BEFORE' or 'AFTER'.
• TG_LEVEL: 'ROW' or 'STATEMENT'.
• TG_OP: 'INSERT', 'UPDATE', or 'DELETE'
• TG_TABLE_NAME: Name of the table that invoked the trigger.
• TG_TABLE_SCHEMA: Schema for the table in TG_TABLE_NAME.
Writing a Trigger in PL/pgSQL
Watching Triggers in Action
Views are Actually Rules
Example Rule for Updates
Granting Access through Views
Views and Rules Summary
• Relations (tables/views) that are used due to rules get checked against the privileges of the rule
owner, not the user invoking the rule.
• One of the things that cannot be implemented by rules are some kinds of constraints,
especially foreign keys.
• A trigger that is fired on INSERT on a view can do the same as a rule: put the data somewhere
else and suppress the insert in the view. But it cannot do the same thing on UPDATE or DELETE,
because there is no real data in the view relation that could be scanned, and thus the trigger
would never get called.
• A rule may be more efficient than row-level triggers for bulk updates or deletes.
• A rule may be easier to write than a statement-level triggers, since the rule will rewrite complex
queries for you.
http://www.day32.com/MySQL/Meetup/Presentations/postgresql_stored_procedures.pdf
References
http://www.postgresql.org/docs/9.1/static/plpgsql-overview.html#PLPGSQL-ADVANTAGES
http://coffeenix.net/doc/db/pgsql_sql_091a/pgsql_sql_091a.html#toc5
Postgresql stored procedure

Weitere ähnliche Inhalte

Was ist angesagt?

3 Tier Architecture
3  Tier Architecture3  Tier Architecture
3 Tier Architecture
Webx
 

Was ist angesagt? (20)

SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Index in sql server
Index in sql serverIndex in sql server
Index in sql server
 
Partitioning
PartitioningPartitioning
Partitioning
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An Introduction
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
 
Database
DatabaseDatabase
Database
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbms
 
Normalization
NormalizationNormalization
Normalization
 
introduction to NOSQL Database
introduction to NOSQL Databaseintroduction to NOSQL Database
introduction to NOSQL Database
 
Advanced sql
Advanced sqlAdvanced sql
Advanced sql
 
User, roles and privileges
User, roles and privilegesUser, roles and privileges
User, roles and privileges
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
 
3 Tier Architecture
3  Tier Architecture3  Tier Architecture
3 Tier Architecture
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
 
Bash Programming
Bash ProgrammingBash Programming
Bash Programming
 
SQL Joins.pptx
SQL Joins.pptxSQL Joins.pptx
SQL Joins.pptx
 

Ähnlich wie Postgresql stored procedure

ORACLE 12C-New-Features
ORACLE 12C-New-FeaturesORACLE 12C-New-Features
ORACLE 12C-New-Features
Navneet Upneja
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
Abdul Rahman Sherzad
 
Oracle 12 c new-features
Oracle 12 c new-featuresOracle 12 c new-features
Oracle 12 c new-features
Navneet Upneja
 
View, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptView, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - Thaipt
Framgia Vietnam
 
Merging Multiple Drug Safety and Pharmacovigilance Databases
Merging Multiple Drug Safety and Pharmacovigilance DatabasesMerging Multiple Drug Safety and Pharmacovigilance Databases
Merging Multiple Drug Safety and Pharmacovigilance Databases
Perficient
 

Ähnlich wie Postgresql stored procedure (20)

MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
 
Sql server 2016 new features
Sql server 2016 new featuresSql server 2016 new features
Sql server 2016 new features
 
Sql server 2016 new features
Sql server 2016 new featuresSql server 2016 new features
Sql server 2016 new features
 
Triggers.PPTX
Triggers.PPTXTriggers.PPTX
Triggers.PPTX
 
ORACLE 12C-New-Features
ORACLE 12C-New-FeaturesORACLE 12C-New-Features
ORACLE 12C-New-Features
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
 
Oracle 12 c new-features
Oracle 12 c new-featuresOracle 12 c new-features
Oracle 12 c new-features
 
PL/pgSQL - An Introduction on Using Imperative Programming in PostgreSQL
PL/pgSQL - An Introduction on Using Imperative Programming in PostgreSQLPL/pgSQL - An Introduction on Using Imperative Programming in PostgreSQL
PL/pgSQL - An Introduction on Using Imperative Programming in PostgreSQL
 
Database testing
Database testingDatabase testing
Database testing
 
View, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptView, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - Thaipt
 
Store programs
Store programsStore programs
Store programs
 
triggers.pptx
triggers.pptxtriggers.pptx
triggers.pptx
 
GLOC 2014 NEOOUG - Oracle Database 12c New Features
GLOC 2014 NEOOUG - Oracle Database 12c New FeaturesGLOC 2014 NEOOUG - Oracle Database 12c New Features
GLOC 2014 NEOOUG - Oracle Database 12c New Features
 
Sql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices ISql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices I
 
IR SQLite Session #1
IR SQLite Session #1IR SQLite Session #1
IR SQLite Session #1
 
Backup And Recovery
Backup And RecoveryBackup And Recovery
Backup And Recovery
 
[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
Merging Multiple Drug Safety and Pharmacovigilance Databases
Merging Multiple Drug Safety and Pharmacovigilance DatabasesMerging Multiple Drug Safety and Pharmacovigilance Databases
Merging Multiple Drug Safety and Pharmacovigilance Databases
 

Mehr von Jong Woo Rhee (10)

Jpa 필드 와 컬럼 매핑 레퍼런스
Jpa 필드 와 컬럼 매핑 레퍼런스Jpa 필드 와 컬럼 매핑 레퍼런스
Jpa 필드 와 컬럼 매핑 레퍼런스
 
Git hub repository 관리 방안
Git hub repository 관리 방안Git hub repository 관리 방안
Git hub repository 관리 방안
 
Connection pool
Connection poolConnection pool
Connection pool
 
RabbitMQ
RabbitMQRabbitMQ
RabbitMQ
 
Ionic project guide
Ionic project guideIonic project guide
Ionic project guide
 
Ionics구조
Ionics구조Ionics구조
Ionics구조
 
Java8 람다
Java8 람다Java8 람다
Java8 람다
 
Hibernate 기초
Hibernate 기초Hibernate 기초
Hibernate 기초
 
Glances
GlancesGlances
Glances
 
Jmeter
JmeterJmeter
Jmeter
 

Kürzlich hochgeladen

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

Postgresql stored procedure

  • 1. Intro to Stored Procedures in PostgreSQL 개발팀
  • 2. Why use Stored Procedures? • Reusability – Avoid rewriting subqueries and improve readability. – If you can't store a query in a library that all the applications can access, you can put that query in a stored procedure. • Separation of duties – You don't trust non-DBA's to write queries. • Data integrity – Use triggers or constraints to prevent bad data from entering. – Run several interdependent queries in a transaction in a single stored procedure. • Event handling – Log changes. – Notify other systems of new data.
  • 3. Why NOT use Stored Procedures? • Views may be all you need. • An object-relational mapper (ORM) can help write queries safely. • Difficult to version control stored procedures. • Software rollouts may require more DB changes. • Could slow software development process.
  • 4. Writing a Stored Procedure in SQL
  • 7. Triggers • Triggers can be used to call a stored procedure before or after an INSERT, UPDATE, or DELETE statement on a table. • Triggers can be called once per each row affected or once per each INSERT, UPDATE, or DELETE statement. • Triggers on many different tables can share the same stored procedure.
  • 8. Automatic Variables in Triggers • NEW: The new row for INSERT/UPDATE statements. It is NULL in statement-level triggers. • OLD: The old row for UPDATE/DELETE statements. It is NULL in statement-level triggers. • TG_NAME: Name of the trigger. • TG_WHEN: 'BEFORE' or 'AFTER'. • TG_LEVEL: 'ROW' or 'STATEMENT'. • TG_OP: 'INSERT', 'UPDATE', or 'DELETE' • TG_TABLE_NAME: Name of the table that invoked the trigger. • TG_TABLE_SCHEMA: Schema for the table in TG_TABLE_NAME.
  • 9. Writing a Trigger in PL/pgSQL
  • 12. Example Rule for Updates
  • 14. Views and Rules Summary • Relations (tables/views) that are used due to rules get checked against the privileges of the rule owner, not the user invoking the rule. • One of the things that cannot be implemented by rules are some kinds of constraints, especially foreign keys. • A trigger that is fired on INSERT on a view can do the same as a rule: put the data somewhere else and suppress the insert in the view. But it cannot do the same thing on UPDATE or DELETE, because there is no real data in the view relation that could be scanned, and thus the trigger would never get called. • A rule may be more efficient than row-level triggers for bulk updates or deletes. • A rule may be easier to write than a statement-level triggers, since the rule will rewrite complex queries for you.