SlideShare a Scribd company logo
1 of 22
PL/PGSQL
AN INTRODUCTION ON HOW TO USE IMPERATIVE
PROGRAMMING IN POSTGRESQL
Robert Sosinski
Founder & Engineering Fellow
AGENDA
PL/pgSQL: what it is and why it matters
Volatility: living in an uncertain data world
Upserts: a little update with a little insert
Triggers: keeping data consistent
Code Blocks: control when you need it
Summary: bringing it all together
Questions: fire away
WHAT IS PL/PGSQL
Procedural
Language
postgres
Structured
Query
Language
HOW PL MEETS SQL
PL/pgSQL SQL
WHY SQL IS NOT ENOUGH
With SQL, every statement must be executed individually by
the database server
1. Complex actions can require multiple round-trips
2. Intermediate results have to be marshaled and
transferred
3. Multiple clients must implement redundant logic
4. Secure information might require exposure
5. Indexes and common filters might need complex logic
6. Consistency can require client-side interaction
TWO WAYS TO PL/PGSQL
Stored Procedure
• Stored directly on the database server
• Can be used in queries and indexes
• Able to be activated upon trigger conditions
• May take input parameters and return values
Anonymous Code Block
• Sent to and parsed by the database when needed
• Able to write to the database but unable to return a value
MORE PL THEN JUST PGSQL
PL/Perl
PL/TCL
PL/Python
PL/Ruby PL/PHPPL/V8PL/Java
DIVING HEAD FIRST
Secure access database
for a fictitious company
with high performance needs.
LETS WRITE SOME
FUNCTIONS
Open Postgres Terminal
DEALING WITH VOLATILITY
Volatility Categories
provide assumptions
the the query planner on
how to optimize a function call
IMMUTABLE
Characteristics
• Cannot modify the database
• Should not read from the database (side effect free)
• Similar inputs should always return the same output
• Can be used when creating indexes
• Database may replace a function call with a constant
Examples
• Our check_access_for_user function for user types
• The lower function for string types
STABLE
Characteristics
• Cannot modify the database
• Able to read from database
• Similar inputs should always return the same output on a
per statement basis
• Can be used in index conditions, but not creation
• Can give caching benefits when called multiple times
Examples
• The current_timestamp and now function
VOLATILE
Characteristics
• Default volatility classification if none is specified
• Can read from and write to the database
• Can return different data on each call
• Can be used as trigger functions
• Planner will not make any assumptions for optimization
Examples
• The random and timeofday functions
• Sequence functions such as nextval and currval
LETS TRY TO WRITE SOME
STABLE FUNCTIONS
Open Postgres Terminal
PULLING THE TRIGGER
Trigger Function
• The function to be run when a triggered event happens
• Written using PL/pgSQL or any other PL language
• Has special arguments available for control flow
• If returns NULL, the event is canceled, else it continues
Trigger Definition
• The event that causes the trigger to be run
• Always attached directly to the table or view
• Can be run BEFORE, AFTER or INSTEAD OF
• Can be run run for EACH ROW or EACH STATEMENT
LETS PULL SOME TRIGGERS
Open Postgres Terminal
ANONYMOUS CODE BLOCKS
The Good
• You do not have to store the function on the server
• Can run arbitrary PL/pgSQL when it is needed
• Good for admin functions stored in your application
The Bad
• Cannot take arguments, so must be injected by your app
• Unable to return a value, but you can get feedback
• Must be parsed each time they are used
LETS “DO” SOMETHING
Open Postgres Terminal
SUMMARY
Powerful: have direct imperative access to your data
Easy: syntax is familiar and simple to use
Fast: because you are never leaving the database
Secure: you do not need to send data back and forth
Flexible: store the logic on the database or in your app
CONDENSED SUMMARY
Direct access
to your data means
better control
of your business
THANKS
Open For Questions

More Related Content

What's hot

WEPA - Webdriver Enhanced Platform for Automation - WEPATest
WEPA - Webdriver Enhanced Platform for Automation - WEPATestWEPA - Webdriver Enhanced Platform for Automation - WEPATest
WEPA - Webdriver Enhanced Platform for Automation - WEPATestFreddy Vega
 
Cassandra: Not Just NoSQL, It's MoSQL
Cassandra: Not Just NoSQL, It's MoSQLCassandra: Not Just NoSQL, It's MoSQL
Cassandra: Not Just NoSQL, It's MoSQLEric Evans
 
PostgreSQL for Oracle Developers and DBA's
PostgreSQL for Oracle Developers and DBA'sPostgreSQL for Oracle Developers and DBA's
PostgreSQL for Oracle Developers and DBA'sGerger
 
Oracle Objects And Transactions
Oracle Objects And TransactionsOracle Objects And Transactions
Oracle Objects And Transactionstepsum
 
All of the thing about Postman
All of the thing about PostmanAll of the thing about Postman
All of the thing about PostmanAlihossein shahabi
 
Pl sql training in pune
Pl sql training in punePl sql training in pune
Pl sql training in punesambhajimeher
 
Load testing in Zonky with Gatling
Load testing in Zonky with GatlingLoad testing in Zonky with Gatling
Load testing in Zonky with GatlingPetr Vlček
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noiseNeeraj Bhusare
 
Rational Robot (http://www.geektester.blogspot.com)
Rational Robot (http://www.geektester.blogspot.com)Rational Robot (http://www.geektester.blogspot.com)
Rational Robot (http://www.geektester.blogspot.com)raj.kamal13
 
Scala adoption by enterprises
Scala adoption by enterprisesScala adoption by enterprises
Scala adoption by enterprisesMike Slinn
 
Sbt, idea and eclipse
Sbt, idea and eclipseSbt, idea and eclipse
Sbt, idea and eclipseMike Slinn
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with XtendSven Efftinge
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Mike Slinn
 
Web development basics (Part-4)
Web development basics (Part-4)Web development basics (Part-4)
Web development basics (Part-4)Rajat Pratap Singh
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel StreamTengwen Wang
 
Performance Test Automation With Gatling
Performance Test Automation  With GatlingPerformance Test Automation  With Gatling
Performance Test Automation With GatlingKnoldus Inc.
 
Reactive by example - at Reversim Summit 2015
Reactive by example - at Reversim Summit 2015Reactive by example - at Reversim Summit 2015
Reactive by example - at Reversim Summit 2015Eran Harel
 
EXPath Webapp - CXAN: a case-study for Servlex, an XML web framework
EXPath Webapp - CXAN: a case-study for Servlex, an XML web frameworkEXPath Webapp - CXAN: a case-study for Servlex, an XML web framework
EXPath Webapp - CXAN: a case-study for Servlex, an XML web frameworkFlorent Georges
 

What's hot (20)

WEPA - Webdriver Enhanced Platform for Automation - WEPATest
WEPA - Webdriver Enhanced Platform for Automation - WEPATestWEPA - Webdriver Enhanced Platform for Automation - WEPATest
WEPA - Webdriver Enhanced Platform for Automation - WEPATest
 
Cassandra: Not Just NoSQL, It's MoSQL
Cassandra: Not Just NoSQL, It's MoSQLCassandra: Not Just NoSQL, It's MoSQL
Cassandra: Not Just NoSQL, It's MoSQL
 
PostgreSQL for Oracle Developers and DBA's
PostgreSQL for Oracle Developers and DBA'sPostgreSQL for Oracle Developers and DBA's
PostgreSQL for Oracle Developers and DBA's
 
Oracle Objects And Transactions
Oracle Objects And TransactionsOracle Objects And Transactions
Oracle Objects And Transactions
 
All of the thing about Postman
All of the thing about PostmanAll of the thing about Postman
All of the thing about Postman
 
Pl sql training in pune
Pl sql training in punePl sql training in pune
Pl sql training in pune
 
Load testing in Zonky with Gatling
Load testing in Zonky with GatlingLoad testing in Zonky with Gatling
Load testing in Zonky with Gatling
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noise
 
Rational Robot (http://www.geektester.blogspot.com)
Rational Robot (http://www.geektester.blogspot.com)Rational Robot (http://www.geektester.blogspot.com)
Rational Robot (http://www.geektester.blogspot.com)
 
Scala adoption by enterprises
Scala adoption by enterprisesScala adoption by enterprises
Scala adoption by enterprises
 
Sbt, idea and eclipse
Sbt, idea and eclipseSbt, idea and eclipse
Sbt, idea and eclipse
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with Xtend
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0
 
Web development basics (Part-4)
Web development basics (Part-4)Web development basics (Part-4)
Web development basics (Part-4)
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel Stream
 
Java 8 parallel stream
Java 8 parallel streamJava 8 parallel stream
Java 8 parallel stream
 
Performance Test Automation With Gatling
Performance Test Automation  With GatlingPerformance Test Automation  With Gatling
Performance Test Automation With Gatling
 
Reactive by example - at Reversim Summit 2015
Reactive by example - at Reversim Summit 2015Reactive by example - at Reversim Summit 2015
Reactive by example - at Reversim Summit 2015
 
EXPath Webapp - CXAN: a case-study for Servlex, an XML web framework
EXPath Webapp - CXAN: a case-study for Servlex, an XML web frameworkEXPath Webapp - CXAN: a case-study for Servlex, an XML web framework
EXPath Webapp - CXAN: a case-study for Servlex, an XML web framework
 

Viewers also liked

Database , 5 Semantic
Database , 5 SemanticDatabase , 5 Semantic
Database , 5 SemanticAli Usman
 
MySQL InnoDB 源码实现分析(一)
MySQL InnoDB 源码实现分析(一)MySQL InnoDB 源码实现分析(一)
MySQL InnoDB 源码实现分析(一)frogd
 
Database ,16 P2P
Database ,16 P2P Database ,16 P2P
Database ,16 P2P Ali Usman
 
Database , 12 Reliability
Database , 12 ReliabilityDatabase , 12 Reliability
Database , 12 ReliabilityAli Usman
 
Database ,10 Transactions
Database ,10 TransactionsDatabase ,10 Transactions
Database ,10 TransactionsAli Usman
 
Postgres MVCC - A Developer Centric View of Multi Version Concurrency Control
Postgres MVCC - A Developer Centric View of Multi Version Concurrency ControlPostgres MVCC - A Developer Centric View of Multi Version Concurrency Control
Postgres MVCC - A Developer Centric View of Multi Version Concurrency ControlReactive.IO
 
Database ,14 Parallel DBMS
Database ,14 Parallel DBMSDatabase ,14 Parallel DBMS
Database ,14 Parallel DBMSAli Usman
 
InnoDB Internal
InnoDB InternalInnoDB Internal
InnoDB Internalmysqlops
 
Database , 13 Replication
Database , 13 ReplicationDatabase , 13 Replication
Database , 13 ReplicationAli Usman
 
Database ,7 query localization
Database ,7 query localizationDatabase ,7 query localization
Database ,7 query localizationAli Usman
 
Database, 3 Distribution Design
Database, 3 Distribution DesignDatabase, 3 Distribution Design
Database, 3 Distribution DesignAli Usman
 
Database ,11 Concurrency Control
Database ,11 Concurrency ControlDatabase ,11 Concurrency Control
Database ,11 Concurrency ControlAli Usman
 
Discrete Structures lecture 2
 Discrete Structures lecture 2 Discrete Structures lecture 2
Discrete Structures lecture 2Ali Usman
 
Oracle rac资源管理算法与cache fusion实现浅析
Oracle rac资源管理算法与cache fusion实现浅析Oracle rac资源管理算法与cache fusion实现浅析
Oracle rac资源管理算法与cache fusion实现浅析frogd
 
Database , 15 Object DBMS
Database , 15 Object DBMSDatabase , 15 Object DBMS
Database , 15 Object DBMSAli Usman
 
Database , 1 Introduction
 Database , 1 Introduction Database , 1 Introduction
Database , 1 IntroductionAli Usman
 
SQL: Query optimization in practice
SQL: Query optimization in practiceSQL: Query optimization in practice
SQL: Query optimization in practiceJano Suchal
 
Database ,2 Background
 Database ,2 Background Database ,2 Background
Database ,2 BackgroundAli Usman
 
Database , 6 Query Introduction
Database , 6 Query Introduction Database , 6 Query Introduction
Database , 6 Query Introduction Ali Usman
 

Viewers also liked (20)

Profiling PL/pgSQL
Profiling PL/pgSQLProfiling PL/pgSQL
Profiling PL/pgSQL
 
Database , 5 Semantic
Database , 5 SemanticDatabase , 5 Semantic
Database , 5 Semantic
 
MySQL InnoDB 源码实现分析(一)
MySQL InnoDB 源码实现分析(一)MySQL InnoDB 源码实现分析(一)
MySQL InnoDB 源码实现分析(一)
 
Database ,16 P2P
Database ,16 P2P Database ,16 P2P
Database ,16 P2P
 
Database , 12 Reliability
Database , 12 ReliabilityDatabase , 12 Reliability
Database , 12 Reliability
 
Database ,10 Transactions
Database ,10 TransactionsDatabase ,10 Transactions
Database ,10 Transactions
 
Postgres MVCC - A Developer Centric View of Multi Version Concurrency Control
Postgres MVCC - A Developer Centric View of Multi Version Concurrency ControlPostgres MVCC - A Developer Centric View of Multi Version Concurrency Control
Postgres MVCC - A Developer Centric View of Multi Version Concurrency Control
 
Database ,14 Parallel DBMS
Database ,14 Parallel DBMSDatabase ,14 Parallel DBMS
Database ,14 Parallel DBMS
 
InnoDB Internal
InnoDB InternalInnoDB Internal
InnoDB Internal
 
Database , 13 Replication
Database , 13 ReplicationDatabase , 13 Replication
Database , 13 Replication
 
Database ,7 query localization
Database ,7 query localizationDatabase ,7 query localization
Database ,7 query localization
 
Database, 3 Distribution Design
Database, 3 Distribution DesignDatabase, 3 Distribution Design
Database, 3 Distribution Design
 
Database ,11 Concurrency Control
Database ,11 Concurrency ControlDatabase ,11 Concurrency Control
Database ,11 Concurrency Control
 
Discrete Structures lecture 2
 Discrete Structures lecture 2 Discrete Structures lecture 2
Discrete Structures lecture 2
 
Oracle rac资源管理算法与cache fusion实现浅析
Oracle rac资源管理算法与cache fusion实现浅析Oracle rac资源管理算法与cache fusion实现浅析
Oracle rac资源管理算法与cache fusion实现浅析
 
Database , 15 Object DBMS
Database , 15 Object DBMSDatabase , 15 Object DBMS
Database , 15 Object DBMS
 
Database , 1 Introduction
 Database , 1 Introduction Database , 1 Introduction
Database , 1 Introduction
 
SQL: Query optimization in practice
SQL: Query optimization in practiceSQL: Query optimization in practice
SQL: Query optimization in practice
 
Database ,2 Background
 Database ,2 Background Database ,2 Background
Database ,2 Background
 
Database , 6 Query Introduction
Database , 6 Query Introduction Database , 6 Query Introduction
Database , 6 Query Introduction
 

Similar to PL/pgSQL - An Introduction on Using Imperative Programming in PostgreSQL

Migrating Oracle database to PostgreSQL
Migrating Oracle database to PostgreSQLMigrating Oracle database to PostgreSQL
Migrating Oracle database to PostgreSQLUmair Mansoob
 
The Amazing and Elegant PL/SQL Function Result Cache
The Amazing and Elegant PL/SQL Function Result CacheThe Amazing and Elegant PL/SQL Function Result Cache
The Amazing and Elegant PL/SQL Function Result CacheSteven Feuerstein
 
Stumbling stones when migrating from Oracle
 Stumbling stones when migrating from Oracle Stumbling stones when migrating from Oracle
Stumbling stones when migrating from OracleEDB
 
Implementing GraphQL API in Elixir – Victor Deryagin
Implementing GraphQL API in Elixir – Victor DeryaginImplementing GraphQL API in Elixir – Victor Deryagin
Implementing GraphQL API in Elixir – Victor DeryaginElixir Club
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Steve Pember
 
Cassandra Lunch #88: Cadence
Cassandra Lunch #88: CadenceCassandra Lunch #88: Cadence
Cassandra Lunch #88: CadenceAnant Corporation
 
Agile Oracle to PostgreSQL migrations (PGConf.EU 2013)
Agile Oracle to PostgreSQL migrations (PGConf.EU 2013)Agile Oracle to PostgreSQL migrations (PGConf.EU 2013)
Agile Oracle to PostgreSQL migrations (PGConf.EU 2013)Gabriele Bartolini
 
A Marriage of Lambda and Kappa: Supporting Iterative Development of an Event ...
A Marriage of Lambda and Kappa: Supporting Iterative Development of an Event ...A Marriage of Lambda and Kappa: Supporting Iterative Development of an Event ...
A Marriage of Lambda and Kappa: Supporting Iterative Development of an Event ...confluent
 
Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)Brooklyn Zelenka
 
Building a document e-signing workflow with Azure Durable Functions
Building a document e-signing workflow with Azure Durable FunctionsBuilding a document e-signing workflow with Azure Durable Functions
Building a document e-signing workflow with Azure Durable FunctionsJoonas Westlin
 
Performance tuning Grails applications
Performance tuning Grails applicationsPerformance tuning Grails applications
Performance tuning Grails applicationsLari Hotari
 
Чурюканов Вячеслав, “Code simple, but not simpler”
Чурюканов Вячеслав, “Code simple, but not simpler”Чурюканов Вячеслав, “Code simple, but not simpler”
Чурюканов Вячеслав, “Code simple, but not simpler”EPAM Systems
 
Programming language paradigms
Programming language paradigmsProgramming language paradigms
Programming language paradigmsAshok Raj
 
Advantages of Rails Framework
Advantages of Rails FrameworkAdvantages of Rails Framework
Advantages of Rails FrameworkSathish Mariappan
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowTen query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowKevin Kline
 

Similar to PL/pgSQL - An Introduction on Using Imperative Programming in PostgreSQL (20)

Migrating Oracle database to PostgreSQL
Migrating Oracle database to PostgreSQLMigrating Oracle database to PostgreSQL
Migrating Oracle database to PostgreSQL
 
Rails DB migrate SAFE.pdf
Rails DB migrate SAFE.pdfRails DB migrate SAFE.pdf
Rails DB migrate SAFE.pdf
 
The Amazing and Elegant PL/SQL Function Result Cache
The Amazing and Elegant PL/SQL Function Result CacheThe Amazing and Elegant PL/SQL Function Result Cache
The Amazing and Elegant PL/SQL Function Result Cache
 
Stumbling stones when migrating from Oracle
 Stumbling stones when migrating from Oracle Stumbling stones when migrating from Oracle
Stumbling stones when migrating from Oracle
 
Implementing GraphQL API in Elixir – Victor Deryagin
Implementing GraphQL API in Elixir – Victor DeryaginImplementing GraphQL API in Elixir – Victor Deryagin
Implementing GraphQL API in Elixir – Victor Deryagin
 
Dal deck
Dal deckDal deck
Dal deck
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
 
Cassandra Lunch #88: Cadence
Cassandra Lunch #88: CadenceCassandra Lunch #88: Cadence
Cassandra Lunch #88: Cadence
 
Store programs
Store programsStore programs
Store programs
 
introduction v4
introduction v4introduction v4
introduction v4
 
Agile Oracle to PostgreSQL migrations (PGConf.EU 2013)
Agile Oracle to PostgreSQL migrations (PGConf.EU 2013)Agile Oracle to PostgreSQL migrations (PGConf.EU 2013)
Agile Oracle to PostgreSQL migrations (PGConf.EU 2013)
 
A Marriage of Lambda and Kappa: Supporting Iterative Development of an Event ...
A Marriage of Lambda and Kappa: Supporting Iterative Development of an Event ...A Marriage of Lambda and Kappa: Supporting Iterative Development of an Event ...
A Marriage of Lambda and Kappa: Supporting Iterative Development of an Event ...
 
Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)
 
Building a document e-signing workflow with Azure Durable Functions
Building a document e-signing workflow with Azure Durable FunctionsBuilding a document e-signing workflow with Azure Durable Functions
Building a document e-signing workflow with Azure Durable Functions
 
Performance tuning Grails applications
Performance tuning Grails applicationsPerformance tuning Grails applications
Performance tuning Grails applications
 
Чурюканов Вячеслав, “Code simple, but not simpler”
Чурюканов Вячеслав, “Code simple, but not simpler”Чурюканов Вячеслав, “Code simple, but not simpler”
Чурюканов Вячеслав, “Code simple, but not simpler”
 
Programming language paradigms
Programming language paradigmsProgramming language paradigms
Programming language paradigms
 
Breaking data
Breaking dataBreaking data
Breaking data
 
Advantages of Rails Framework
Advantages of Rails FrameworkAdvantages of Rails Framework
Advantages of Rails Framework
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowTen query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should know
 

Recently uploaded

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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 WorkerThousandEyes
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
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 FMESafe Software
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
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.pdfOrbitshub
 
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 ...apidays
 
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 FMESafe Software
 
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...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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.pdfsudhanshuwaghmare1
 

Recently uploaded (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
+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...
 
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
 
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 ...
 
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
 
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...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 

PL/pgSQL - An Introduction on Using Imperative Programming in PostgreSQL

  • 1. PL/PGSQL AN INTRODUCTION ON HOW TO USE IMPERATIVE PROGRAMMING IN POSTGRESQL
  • 2. Robert Sosinski Founder & Engineering Fellow
  • 3. AGENDA PL/pgSQL: what it is and why it matters Volatility: living in an uncertain data world Upserts: a little update with a little insert Triggers: keeping data consistent Code Blocks: control when you need it Summary: bringing it all together Questions: fire away
  • 5. HOW PL MEETS SQL PL/pgSQL SQL
  • 6. WHY SQL IS NOT ENOUGH With SQL, every statement must be executed individually by the database server 1. Complex actions can require multiple round-trips 2. Intermediate results have to be marshaled and transferred 3. Multiple clients must implement redundant logic 4. Secure information might require exposure 5. Indexes and common filters might need complex logic 6. Consistency can require client-side interaction
  • 7. TWO WAYS TO PL/PGSQL Stored Procedure • Stored directly on the database server • Can be used in queries and indexes • Able to be activated upon trigger conditions • May take input parameters and return values Anonymous Code Block • Sent to and parsed by the database when needed • Able to write to the database but unable to return a value
  • 8. MORE PL THEN JUST PGSQL PL/Perl PL/TCL PL/Python PL/Ruby PL/PHPPL/V8PL/Java
  • 9. DIVING HEAD FIRST Secure access database for a fictitious company with high performance needs.
  • 10. LETS WRITE SOME FUNCTIONS Open Postgres Terminal
  • 11. DEALING WITH VOLATILITY Volatility Categories provide assumptions the the query planner on how to optimize a function call
  • 12. IMMUTABLE Characteristics • Cannot modify the database • Should not read from the database (side effect free) • Similar inputs should always return the same output • Can be used when creating indexes • Database may replace a function call with a constant Examples • Our check_access_for_user function for user types • The lower function for string types
  • 13. STABLE Characteristics • Cannot modify the database • Able to read from database • Similar inputs should always return the same output on a per statement basis • Can be used in index conditions, but not creation • Can give caching benefits when called multiple times Examples • The current_timestamp and now function
  • 14. VOLATILE Characteristics • Default volatility classification if none is specified • Can read from and write to the database • Can return different data on each call • Can be used as trigger functions • Planner will not make any assumptions for optimization Examples • The random and timeofday functions • Sequence functions such as nextval and currval
  • 15. LETS TRY TO WRITE SOME STABLE FUNCTIONS Open Postgres Terminal
  • 16. PULLING THE TRIGGER Trigger Function • The function to be run when a triggered event happens • Written using PL/pgSQL or any other PL language • Has special arguments available for control flow • If returns NULL, the event is canceled, else it continues Trigger Definition • The event that causes the trigger to be run • Always attached directly to the table or view • Can be run BEFORE, AFTER or INSTEAD OF • Can be run run for EACH ROW or EACH STATEMENT
  • 17. LETS PULL SOME TRIGGERS Open Postgres Terminal
  • 18. ANONYMOUS CODE BLOCKS The Good • You do not have to store the function on the server • Can run arbitrary PL/pgSQL when it is needed • Good for admin functions stored in your application The Bad • Cannot take arguments, so must be injected by your app • Unable to return a value, but you can get feedback • Must be parsed each time they are used
  • 19. LETS “DO” SOMETHING Open Postgres Terminal
  • 20. SUMMARY Powerful: have direct imperative access to your data Easy: syntax is familiar and simple to use Fast: because you are never leaving the database Secure: you do not need to send data back and forth Flexible: store the logic on the database or in your app
  • 21. CONDENSED SUMMARY Direct access to your data means better control of your business