PL/pgSQL (PostgreSQL 18)
This assessment applies the coupling account — coupling as access to a shared resource, and the coupling floor [1], [2] — and the knowledge-embodiment theorem [3]; the language is assessed against its official reference [4].
Snapshot PL/pgSQL (PostgreSQL 18) — released 25 September 2025 · lifecycle current (PostgreSQL 18; PL/pgSQL ships with the engine, so the language release is the database release.)
Family PL/pgSQL — shelf: Data and Science
The language’s primary object is a dataset or a numeric array, not a program loop. A shelf groups; it does not classify — the tags below carry every use, paradigm, and platform of this snapshot.
Trajectory PostgreSQL 6.x (1998 — PL/pgSQL first ships in the PostgreSQL line, modelled on PL/SQL) · PostgreSQL 18 (25 September 2025 — assessed release; the current major release)
Tags
Use — Query
Paradigm — Imperative, Procedural, Declarative
Lifecycle — Current
Memory — Runtime-managed
Typing — Static, strong
Resources
The language’s official entry points, and the documents that name the release this page assesses. A link marked this release pins the document to PL/pgSQL (PostgreSQL 18); an unmarked link is the current reference for the language.
Landing page
Specification and reference
1 Assessment
This page assesses PL/pgSQL in five parts: core coupling — what the language’s own constructs force; ecosystem coupling — what the surrounding platform, tooling, and community cost; engineering readiness — whether the artifact can be reproduced, verified, observed, worked in quickly, connected to other languages, and governed openly; the profile — the unscored facts a score cannot express; and the scoring detail — the mechanism marks and the arithmetic behind every score. A ✅ bullet marks a construct that helps. A ⚠️ or ❌ bullet marks a cost; the scoring model does not price every cost named here.
Core coupling 82.0/100 · Ecosystem coupling 83.2/100 · Engineering readiness 63.2/100
1.1 Core coupling
1.1.1 Type
- ✅ Static typing over SQL data types: Every variable, parameter, and return value declares a type, and a body that violates its declarations fails when the function is compiled
- ✅
%TYPEand%ROWTYPEanchor a declaration to the schema:emp%ROWTYPEfollows the table’s column list, so a column change does not require editing the declaration - ✅ Polymorphic parameters keep one algorithm generic:
anyelementandanyarraylet a single function run over many types, with the type fixed per call - ⚠️ Operators resolve by operand type (T8):
+,||, and&&name different operations for different types, andCREATE OPERATORlets an extension add meanings, so an expression’s sense follows from the operand types - ⚠️ A
recordvariable defers its row type to run time: The row shape is known only when a value is assigned, so a mistyped field surfaces on the path that reaches it - ❌ NULL is the default value and it propagates (T10): A declared variable starts as NULL, three-valued logic applies, so
IF x = 5is not true whenxis NULL - ❌ A signature says what a function returns, not what it does (T12): A function that mutates tables, reads a foreign table, or sends notifications looks like any other function
1.1.2 Construction
- ✅ A function is a closed unit: Local variables are private to the call, and the signature is the whole interface, so a caller cannot reach inside
- ✅
CREATE FUNCTIONandCREATE PROCEDUREcompile at creation: The body is checked once when it is deployed, and a caller binds to the name and the signature - ✅ Anonymous
DOblocks run ad-hoc logic without a deployment step: A one-off migration or maintenance script is a block, not a schema object - ⚠️ Triggers fire implicitly: A trigger function runs in response to a data change, so the writer of a statement cannot see from the statement which code will run
- ⚠️
SECURITY DEFINERis decided in the definition, not at the call: A caller sees only a function name; whether it runs with the owner’s rights follows from the definition
1.1.3 Memory
- ✅ No manual memory management: The PostgreSQL server owns process memory, and a block never names an address or frees a byte
- ✅ The server sizes the work areas: A sort or a hash inside a function’s statements gets its memory from
work_mem, which is a setting, not a statement property - ⚠️
RETURN QUERYmaterialises its result before returning: A set-returning function builds its whole output in a tuplestore, so the call’s memory follows the result size - ⚠️ A
CREATE TEMP TABLEinside a function outlives the call: The table persists for the session, so a local act leaves a session-scoped resource behind
1.1.4 Error
- ✅ The block separates the normal path from the recovery path:
BEGIN ... EXCEPTION WHEN unique_violation THEN ...gives a named handler section, and conditions match by code or by name - ✅
RAISE EXCEPTIONcarries a code and a detail:RAISE EXCEPTION 'msg' USING ERRCODE = '23505'raises a failure a caller’s handler can match on - ✅
GET STACKED DIAGNOSTICSreports the caught error: A handler can read the error’s code, message, constraint, context, and line - ⚠️ A handler can swallow (Er3): An
EXCEPTIONblock that catches and returns normally lets the caller see success, andWHEN OTHERSis the widest net - ❌ A failure cannot travel as a value (Er4): The failure path is the exception path, so a fallible operation cannot be folded into an expression or returned as a result the caller inspects
1.1.5 Concurrency
- ✅ A procedure can manage its own transaction: A
CALLed procedure mayCOMMITandROLLBACK(since PostgreSQL 11), while a function always runs inside its caller’s transaction - ✅
SELECT ... FOR UPDATEnames the rows to lock in the query text: The lock is declared by the statement rather than by a separate call - ✅ Advisory locks give an explicit lock service:
pg_advisory_lockserialises an application-level critical section across sessions under a declared key - ❌ Session state is shared by default (K2): Custom session parameters set with
set_config, session temp tables, andcurrent_settingare visible to every function that runs in the session - ⚠️ Transaction isolation and declared locks do not order independent work: Two sessions’ multi-step work is ordered only by the locks its statements name, so any ordering the source relies on is an agreement no declaration carries
1.1.6 Platform
- ❌ Cannot function outside one engine (P1): A PL/pgSQL program needs PostgreSQL or a compatible fork, so the unit of deployment is a database schema
- ❌ Portability is the engine’s, not the artifact’s (Y10): The program runs wherever its PostgreSQL release runs, and the language has no build target of its own
- ⚠️ Managed services track the engine’s calendar: A managed PostgreSQL carries the PL/pgSQL of its engine version, so the available surface follows the provider’s upgrade
- ⚠️ Foreign languages load in-process (T14):
LANGUAGE Cand the untrusted PLs such asplpython3urun outside PL/pgSQL’s checks, so a boundary no signature can see separates the two sides - ✅ Client interfaces are standard: libpq, ODBC, and JDBC reach the engine, so a client is not bound to one binary protocol
1.1.7 Trade-offs (not coupling)
- Logic beside the data is deliberate: A rule that runs beside its tables is enforced for every writer; the cost is that the rule sits outside the application’s test suite and profilers
- A session cache in custom parameters is deliberate:
set_configkeeps a value for the session without a table; the cost is staleness, since nothing invalidates the value when the underlying data changes - Dynamic SQL is deliberate for DDL and for a flexible filter:
EXECUTEwithformat()reaches names a static statement cannot; the cost is the plan, since a built string is parsed and planned on every execution SECURITY DEFINERis deliberate for gated access: It exposes one narrow operation instead of table grants; the cost is an audit duty, since the function runs with its owner’s rights
1.2 Ecosystem coupling
1.2.1 Performance
- ✅ Statements inside a function use cached plans: A function’s static SQL is planned once per session and reused, so a call does not re-parse
- ✅ Set-based statements in the body do the heavy lifting: One
INSERT ... SELECTinside the function carries the optimiser’s plan, so the procedural wrapper is not the hot path - ⚠️ Row-by-row loops pay per-row context switches: A loop that fetches one row at a time runs far slower than its set-based equivalent
- ⚠️ A plan regression arrives hidden inside the call: A caller cannot see the queries inside a function, so a changed plan surfaces as the function being slow
1.2.2 Ecosystem
- ✅ The extension ecosystem supplies the libraries:
CREATE EXTENSIONloads packaged capabilities such as PostGIS, pg_trgm, and pgcrypto into the database - ✅ PGXN catalogs shareable extensions: A public registry indexes community extensions with releases and metadata
- ✅ PostgreSQL’s popularity carries the market: Documentation, books, courses, and hiring are abundant
- ✅ The stack is open and permissively licensed: The engine, the client tools, and the documentation carry no per-seat licence
- ⚠️ Tooling centres on the engine’s own tools: psql, pg_dump, and pgAdmin cover administration and query work, and the procedural language has no dedicated environment of its own
1.2.3 Evolution
- ✅ Major releases keep the language: A PL/pgSQL function written years ago compiles in the current release
- ✅ Deprecation is announced before removal: The release notes and the documentation mark obsolescent features, so an upgrade is planned rather than discovered
- ⚠️ A feature arrives with the engine’s major release: Adoption follows the server a deployment can upgrade to, not a separate language release
- ⚠️ The community’s own decisions govern the change: No independent standard bounds the syntax, so the release notes are the definition’s change log
1.2.4 Domain
- ✅ Excellent fit for data-centric logic: A function runs beside its tables with SQL directly in the body, so a rule executes where the data is
- ✅ A full procedural language inside SQL: Loops, records, cursors, and subprograms live in the same unit as the queries
- ✅ The engine reaches beyond its own schema: Foreign data wrappers and
dblinkread remote sources, and other PLs run beside PL/pgSQL in the same database - ❌ Domain lock-in (D1): The language exists to run inside PostgreSQL, so the PostgreSQL data tier is the only domain
- ⚠️ It is not a runtime for arbitrary programs: A user interface, a heavy text workload, or a long-running service belongs in another language beside PL/pgSQL
1.2.5 Learning
- ✅ Gentle for a SQL developer: A block with
DECLARE,BEGIN, andENDreads like SQL with control flow added - ✅ The documentation is complete and canonical: The PL/pgSQL chapter of the PostgreSQL manual documents every construct with runnable examples
- ⚠️
SELECT INTOis silent on an empty result: A plainSELECT INTOassigns NULL when the query returns no rows, andSTRICTis the opt-in that makes it error - ⚠️ Engine behaviour is a separate body of knowledge: Locks, MVCC, and transaction semantics matter more than syntax for correct code
1.2.6 Syntax
- ❌ Verbose (S1): Every unit needs
CREATE FUNCTION, a dollar-quoted body, andDECLARE,BEGIN, andENDsections before it does anything - ✅ Keyword-led and readable: Statements read as verbs, and the block boundaries are visible in the source
- ⚠️ The body is one dollar-quoted string:
$$ ... $$hides the body from the outer statement’s parser, so a function deploys as a single statement - ⚠️ Function overloading hides the signature: Two functions may share a name and differ by argument types, so a call’s target follows from the argument list
1.2.7 Testing
- ⚠️ No test framework ships with the engine (G1): psql and the server tools provide no assertion or runner, so a suite depends on pgTAP or a hand-rolled harness
- ✅ pgTAP is the established framework: An open-source test framework runs database tests with xUnit-style assertion functions
- ✅ Transaction control isolates a test: A test can run inside a transaction that rolls back, leaving the database unchanged
- ✅ The engine traces execution:
RAISEwrites to the server log with line numbers, andauto_explainlogs the plans of statements inside functions - ⚠️ A suite needs a server: Tests run inside the database they exercise, so the harness depends on a PostgreSQL instance and on deployment rights
- ❌ No monotonic reading published: now() and CURRENT_TIMESTAMP anchor the transaction’s wall time (G4)
1.2.8 Security
- ✅ Static SQL in the body is parameterised automatically: The function’s variables become
$nparameters of the planned statement, so values cannot change the parse - ✅
GRANTand roles express least privilege:EXECUTEon a function is granted per role, and the function signature is the grantable interface - ✅
SECURITY DEFINERstates the effective identity in the definition:ALTER FUNCTION ... SECURITY DEFINERplus a pinnedSET search_pathmakes the rights and the environment explicit - ❌ Known vulnerability/injection (Q3):
EXECUTEwith a built string turns concatenated input into code, andformat()with%Iand%Lis the mitigation, not a guarantee - ⚠️ Definer’s-rights functions can escalate: A
SECURITY DEFINERfunction runs with its owner’s rights, so it needs a pinned search path and an audit
1.2.9 Delivery targets
What ships from a producer to a consumer, and whether the interface across a release boundary is promised. Ec8 is present when one compiled target crosses with no promise.
| Target | Ships as | Crosses a producer boundary | Cross-release promise |
|---|---|---|---|
| stored program | script | no | The database stores the source text and parses it; no compiled unit crosses a boundary |
1.3 Engineering readiness
1.3.1 Reproducibility
- ❌ The distribution records no toolchain version per project; the server and extension versions are facts of the installation. (Y14)
1.3.2 Supply chain
- ❌ PGXN and community extensions carry no signed provenance. (Y3)
- ❌ The extension registry is a flat name space. (Y4)
- ❌ No advisory feed joins CVEs to extensions. (Y16)
1.3.3 Observability
- ❌ No tracing standard exists in the language; the server’s log stats are the instruments. (Y5)
- ❌ RAISE is the whole logging surface. (Y6)
1.3.4 Feedback
- ❌ No analyzer ships with the server; editor analysis rides third-party tools. (Y8)
- ❌ No PL/pgSQL debugger ships with the server; pgAdmin’s is separate. (Y13)
1.3.5 Interop
- ❌ The routine runs only in PostgreSQL-family servers. (Y10)
1.3.6 Governance
- ✅ The PostgreSQL community governs in the open; no vendor owns the language. (Y11)
- ✅ The documentation set is complete and public. (Y12)
- ✅ The server and the procedural handler are public source. (Y19)
1.4 Profile
Unscored, and kept separate from every score on purpose. The profile records what a mechanism price cannot express: what a running program costs, how well a coding model and an agent work in the language, and whether a safety-critical path exists.
1.4.1 Energy and cost
What this axis asks: what does a running program cost in energy and time?
- ⚠️ Runs inside a database engine: energy and time are the engine’s, not the program’s.
1.4.2 AI and agent readiness
What this axis asks: how well does a coding model and an agent work in this language?
- ❌ Procedural SQL is thin in model training data relative to mainstream languages, so generated PL/pgSQL mixes in other dialects’ syntax [5].
1.4.3 Safety certification
What this axis asks: is there a certified or standards-qualified path to a safety-critical system?
- ❌ No certified or standards-qualified path for safety-critical systems.
1.5 Scoring detail
1.5.1 Core coupling Dimensions
| Dimension | Mechanism | Description | Imposed by | Present | Weight |
|---|---|---|---|---|---|
| Type | T1 |
dynamic no static check | language | — | 0 |
T2 |
weak static | language | — | 0 | |
T3 |
dynamic/duck dispatch | language | — | 0 | |
T4 |
no sum types | language | — | 0 | |
T5 |
no generics | language | — | 0 | |
T6 |
no namespaces | language | — | 0 | |
T7 |
type erasure/reflection | language | — | 0 | |
T8 |
operator overloading | language | ✅ | −4 | |
T9 |
inheritance required for polymorphism | language | — | 0 | |
T10 |
no null-safety | language | ✅ | −8 | |
T11 |
no module boundary | language | — | 0 | |
T12 |
no effect tracking | language | ✅ | −8 | |
T13 |
async/sync colouring | language | — | 0 | |
T14 |
unchecked foreign boundary | language | ✅ | −4 | |
T15 |
chars are encoding units | language | — | 0 | |
| Type cost | −6.9 (−24) | ||||
| Construction | C1 |
global mutable state by default | language | — | 0 |
C2 |
no immutability by default | language | — | 0 | |
C3 |
constructors coupled to allocation | language | — | 0 | |
C4 |
no constructor/validation | language | — | 0 | |
C5 |
unpinned collection order | language | — | 0 | |
C6 |
aliasing by default | language | — | 0 | |
C7 |
undeclared control transfer | language | — | 0 | |
C8 |
no source-visible init order | language | — | 0 | |
| Construction cost | 0 | ||||
| Memory | M1 |
manual deallocation | runtime | — | 0 |
M2 |
GC non-deterministic pauses | runtime | — | 0 | |
M3 |
no RAII | language | — | 0 | |
M4 |
no ownership model | language | — | 0 | |
M5 |
uninitialized reads | language | — | 0 | |
M6 |
unchecked reinterpretation | language | — | 0 | |
Er6 |
uncatchable runtime fault | language | — | 0 | |
M7 |
reference cycles leak | runtime | — | 0 | |
| Memory cost | 0 | ||||
| Error | Er1 |
no structured path | language | — | 0 |
Er2 |
unchecked exceptions only | language | — | 0 | |
Er3 |
errors ignored/non-exhaustive | language | ✅ | −4 | |
Er4 |
no composable result type | language | ✅ | −4 | |
Er5 |
no isolation unit for a fault | runtime | — | 0 | |
| Error cost | −2.3 (−8) | ||||
| Concurrency | K1 |
GIL/no parallel | runtime | — | 0 |
K2 |
shared mutable state default | language | ✅ | −8 | |
K3 |
manual sync no race detection | runtime | — | 0 | |
K4 |
no structured concurrency | language | — | 0 | |
K5 |
no primitives | language | — | 0 | |
K6 |
thread-per-task cost | runtime | — | 0 | |
| Concurrency cost | −2.3 (−8) | ||||
| Platform | P1 |
cannot function outside one vendor/domain | context | ✅ | −15 |
P2 |
single-vendor but other uses | context | — | 0 | |
P3 |
legacy/discontinued platform | context | — | 0 | |
P4 |
poor domain fit | context | ✅ | −8 | |
| Platform cost | −6.6 (−23) |
Core coupling score: 82.0/100 — 63 of the 350 inventory points are present, so the axis cost is 100 × 63 ÷ 350 = 18.0 and the score is 100 − 18.0. Each dimension’s cost above is its share of the same denominator, and the raw weight sum follows in parentheses.
1.5.2 Ecosystem coupling Dimensions
| Dimension | Mechanism | Description | Imposed by | Present | Weight |
|---|---|---|---|---|---|
| Performance | R1 |
interpreted no AOT/JIT | runtime | — | 0 |
R2 |
GC pauses | runtime | — | 0 | |
R3 |
JIT warmup | runtime | — | 0 | |
| Performance cost | 0 | ||||
| Ecosystem | Ec1 |
no package manager | context | — | 0 |
Ec2 |
fragmented tooling | context | — | 0 | |
Ec3 |
small/niche/discontinued | context | — | 0 | |
Ec4 |
proprietary | context | — | 0 | |
Ec5 |
platform-locked tooling | context | — | 0 | |
Ec6 |
monoculture | context | — | 0 | |
Ec7 |
legacy burden | context | — | 0 | |
Ec8 |
unpromised binary boundary | context | — | 0 | |
Ec9 |
unpromised data boundary | context | — | 0 | |
| Ecosystem cost | 0 | ||||
| Evolution | V1 |
breaking changes | language | — | 0 |
V2 |
frozen | context | — | 0 | |
V3 |
discontinued | context | — | 0 | |
V4 |
glacial standards | context | — | 0 | |
V5 |
silent default drift | runtime | — | 0 | |
V7 |
build-variant state space | context | — | 0 | |
| Evolution cost | 0 | ||||
| Domain | D1 |
domain/vendor lock-in | context | ✅ | −15 |
D3 |
framework forces architecture | context | — | 0 | |
| Domain cost | −5.9 (−15) | ||||
| Learning | L1 |
steep | context | — | 0 |
L2 |
large surface/multi-paradigm | context | — | 0 | |
L3 |
sparse docs | context | — | 0 | |
| Learning cost | 0 | ||||
| Syntax | S1 |
verbose | language | ✅ | −8 |
S2 |
inconsistent | language | — | 0 | |
S3 |
punctuation-heavy | language | — | 0 | |
| Syntax cost | −3.1 (−8) | ||||
| Testing | G1 |
weak tooling | context | ✅ | −8 |
G2 |
poor debugging | context | — | 0 | |
G3 |
runtime-only errors | context | — | 0 | |
G4 |
no published monotonic clock | runtime | ✅ | −4 | |
| Testing cost | −4.7 (−12) | ||||
| Security | Q1 |
memory-unsafe | language | — | 0 |
Q2 |
dynamic/weak typing risk | language | — | 0 | |
Q3 |
known vulnerability/injection | context | ✅ | −8 | |
Q4 |
silent integer overflow | language | — | 0 | |
| Security cost | −3.1 (−8) |
Ecosystem coupling score: 83.2/100 — 43 of the 256 inventory points are present, so the axis cost is 100 × 43 ÷ 256 = 16.8 and the score is 100 − 16.8. Each dimension’s cost above is its share of the same denominator, and the raw weight sum follows in parentheses.
1.5.3 Engineering readiness Dimensions
| Dimension | Mechanism | Description | Imposed by | Present | Weight |
|---|---|---|---|---|---|
| Reproducibility | Y1 |
build not reproducible | context | — | 0 |
Y2 |
dependencies not pinned | context | — | 0 | |
Y14 |
no toolchain version pin | context | ✅ | −8 | |
Y18 |
no machine-read project contract | context | — | 0 | |
| Reproducibility cost | −4.7 (−8) | ||||
| Supply chain | Y3 |
no signed provenance | context | ✅ | −15 |
Y4 |
registry without namespacing | context | ✅ | −4 | |
Y16 |
no advisory feed | context | ✅ | −8 | |
| Supply chain cost | −15.8 (−27) | ||||
| Observability | Y5 |
no stable tracing standard | context | ✅ | −8 |
Y6 |
no structured logging | context | ✅ | −4 | |
Y15 |
no post-mortem diagnostics | runtime | — | 0 | |
| Observability cost | −7.0 (−12) | ||||
| Feedback | Y7 |
slow build | context | — | 0 |
Y8 |
no fast in-editor analysis | context | ✅ | −4 | |
Y13 |
no bundled debugger | context | ✅ | −8 | |
| Feedback cost | −7.0 (−12) | ||||
| Interop | Y9 |
no foreign-function interface | language | — | 0 |
Y10 |
no portable target | context | ✅ | −4 | |
| Interop cost | −2.3 (−4) | ||||
| Governance | Y11 |
single-vendor governance | context | — | 0 |
Y12 |
closed specification | context | — | 0 | |
Y17 |
no conformance mechanism | context | — | 0 | |
Y19 |
no published parser | context | — | 0 | |
| Governance cost | 0 |
Engineering readiness score: 63.2/100 — 63 of the 171 inventory points are present, so the axis cost is 100 × 63 ÷ 171 = 36.8 and the score is 100 − 36.8. Each dimension’s cost above is its share of the same denominator, and the raw weight sum follows in parentheses.
Verdict: PL/pgSQL’s coupling is set by its host engine and governed by its community. Functions are closed units with typed declarations, the EXCEPTION ... WHEN section gives a structured failure path, static SQL in the body is parameterised automatically, and the extension registry, the open licence, and community governance give this shelf’s most open ecosystem. Main strengths: open source end to end, an independent steward, complete documentation, automatic parameterisation, and real modularity at function granularity. Main weaknesses: everything runs inside PostgreSQL, NULL starts in every declared variable and propagates, signatures carry no effects, dynamic SQL turns built strings into code, a handler can swallow a failure and return success, RETURN QUERY materialises its result, and the block structure adds boilerplate to every unit.
The formal development. The definitions, theorems, and proofs behind this page are published in:
- On the Nature of Coupling: All Coupling as Shared Resource Access — Zenodo, 2026 — doi:10.5281/zenodo.21925122
- Coupling as a Consequence of Cohesion: Decomposition, the Coupling Floor, and Domain-Imposed Coupling — Zenodo, 2026 — doi:10.5281/zenodo.21925201
- On the Nature of Cohesion: Cohesion as Correctness Relative to a Partitioning Rule — Zenodo, 2026 — doi:10.5281/zenodo.21703193