SlideShare a Scribd company logo
6
Most read
7
Most read
22
Most read
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

PPTX
PostgreSQL Database Slides
PDF
An Introduction To PostgreSQL Triggers
KEY
PostgreSQL
PDF
[Pgday.Seoul 2017] 7. PostgreSQL DB Tuning 기업사례 - 송춘자
PPTX
PDF
Project Reactor Now and Tomorrow
PDF
PostgreSQL High_Performance_Cheatsheet
PDF
PostgreSQL WAL for DBAs
PostgreSQL Database Slides
An Introduction To PostgreSQL Triggers
PostgreSQL
[Pgday.Seoul 2017] 7. PostgreSQL DB Tuning 기업사례 - 송춘자
Project Reactor Now and Tomorrow
PostgreSQL High_Performance_Cheatsheet
PostgreSQL WAL for DBAs

What's hot (20)

PDF
Deep dive into PostgreSQL statistics.
PDF
High Availability PostgreSQL with Zalando Patroni
PDF
Solving PostgreSQL wicked problems
PDF
MySQL Index Cookbook
PDF
TypeScript Introduction
PDF
Advanced Postgres Monitoring
PPT
JavaScript Tutorial
PPTX
Standard Template Library
PDF
MySQL partitions tutorial
PDF
Percona XtraDB Cluster ( Ensure high Availability )
PPTX
PostgreSQL.pptx
PPTX
Java 8 - Features Overview
PPTX
Introduction to PostgreSQL
PDF
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
PDF
PostgreSQL Performance Tuning
PDF
Django Templates
PDF
Python Class | Python Programming | Python Tutorial | Edureka
PDF
Sql query patterns, optimized
PDF
Clean coding-practices
PDF
[Pgday.Seoul 2020] SQL Tuning
Deep dive into PostgreSQL statistics.
High Availability PostgreSQL with Zalando Patroni
Solving PostgreSQL wicked problems
MySQL Index Cookbook
TypeScript Introduction
Advanced Postgres Monitoring
JavaScript Tutorial
Standard Template Library
MySQL partitions tutorial
Percona XtraDB Cluster ( Ensure high Availability )
PostgreSQL.pptx
Java 8 - Features Overview
Introduction to PostgreSQL
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
PostgreSQL Performance Tuning
Django Templates
Python Class | Python Programming | Python Tutorial | Edureka
Sql query patterns, optimized
Clean coding-practices
[Pgday.Seoul 2020] SQL Tuning
Ad

Viewers also liked (20)

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

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

PDF
Migrating Oracle database to PostgreSQL
PDF
Rails DB migrate SAFE.pdf
PPTX
The Amazing and Elegant PL/SQL Function Result Cache
PDF
Stumbling stones when migrating from Oracle
 
PDF
Implementing GraphQL API in Elixir – Victor Deryagin
PPT
Dal deck
PDF
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
PDF
MariaDB/MySQL_: Developing Scalable Applications
PDF
Data Integration Basics: Merging & Joining Data
PPTX
Cassandra Lunch #88: Cadence
PPT
Store programs
PPT
introduction v4
PDF
Agile Oracle to PostgreSQL migrations (PGConf.EU 2013)
PDF
A Marriage of Lambda and Kappa: Supporting Iterative Development of an Event ...
PPTX
Relay: Seamless Syncing for React (VanJS)
PPTX
Building a document e-signing workflow with Azure Durable Functions
PDF
Performance tuning Grails applications
PPTX
Stored procedures
PPTX
Чурюканов Вячеслав, “Code simple, but not simpler”
PPTX
Programming language paradigms
Migrating Oracle database to PostgreSQL
Rails DB migrate SAFE.pdf
The Amazing and Elegant PL/SQL Function Result Cache
Stumbling stones when migrating from Oracle
 
Implementing GraphQL API in Elixir – Victor Deryagin
Dal deck
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
MariaDB/MySQL_: Developing Scalable Applications
Data Integration Basics: Merging & Joining Data
Cassandra Lunch #88: Cadence
Store programs
introduction v4
Agile Oracle to PostgreSQL migrations (PGConf.EU 2013)
A Marriage of Lambda and Kappa: Supporting Iterative Development of an Event ...
Relay: Seamless Syncing for React (VanJS)
Building a document e-signing workflow with Azure Durable Functions
Performance tuning Grails applications
Stored procedures
Чурюканов Вячеслав, “Code simple, but not simpler”
Programming language paradigms

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
KodekX | Application Modernization Development
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Machine learning based COVID-19 study performance prediction
PPTX
A Presentation on Artificial Intelligence
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Empathic Computing: Creating Shared Understanding
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
KodekX | Application Modernization Development
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
NewMind AI Monthly Chronicles - July 2025
Machine learning based COVID-19 study performance prediction
A Presentation on Artificial Intelligence
Diabetes mellitus diagnosis method based random forest with bat algorithm
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Encapsulation theory and applications.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
NewMind AI Weekly Chronicles - August'25 Week I
The AUB Centre for AI in Media Proposal.docx
Big Data Technologies - Introduction.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
20250228 LYD VKU AI Blended-Learning.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Empathic Computing: Creating Shared Understanding

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