PostgreSQL functions and rollback behavior with primary key conflicts
Clyde Jin
04-30
DBA
32

Here’s the explanation about PostgreSQL functions and rollback behavior with primary key conflicts:

Default Behavior Demonstration

-- Create test table
CREATE TABLE test_table (
    id INT PRIMARY KEY,
    name VARCHAR(50)
);

-- Create function: intentionally cause a primary key conflict on the second insert
CREATE OR REPLACE FUNCTION test_insert_with_conflict()
RETURNS VOID AS $$
BEGIN
    -- First insert (should succeed)
    INSERT INTO test_table (id, name) VALUES (1, 'First');

    -- Second insert (attempts to insert existing id=1, will cause conflict)
    INSERT INTO test_table (id, name) VALUES (1, 'Second');

    -- Third insert (will not be reached)
    INSERT INTO test_table (id, name) VALUES (2, 'Third');
END;
$$ LANGUAGE plpgsql;

-- Execute function (will error)
SELECT test_insert_with_conflict();

-- Query result: no data was inserted
SELECT * FROM test_table;
-- Result is empty, all inserts were rolled back

Using Subtransactions (SAVEPOINT) for Partial Rollback

If you want to catch the conflict and allow other inserts to succeed, you can use subtransactions:

-- Create function: isolate conflicting insert using subtransaction
CREATE OR REPLACE FUNCTION test_insert_with_savepoint()
RETURNS VOID AS $$
BEGIN
    -- First insert
    INSERT INTO test_table (id, name) VALUES (1, 'First');

    -- Use subtransaction to handle potential conflict
    BEGIN
        INSERT INTO test_table (id, name) VALUES (1, 'Second');
    EXCEPTION 
        WHEN unique_violation THEN
            -- Only roll back the subtransaction on conflict, main transaction unaffected
            RAISE NOTICE 'Primary key conflict, skipping duplicate insert';
    END;

    -- Third insert (will succeed)
    INSERT INTO test_table (id, name) VALUES (2, 'Third');
END;
$$ LANGUAGE plpgsql;

-- Truncate table and re-execute
TRUNCATE test_table;
SELECT test_insert_with_savepoint();

-- Query result
SELECT * FROM test_table;

Result:

id | name
---|------
1  | First
2  | Third

Using ON CONFLICT for Graceful Handling

The recommended approach is to use ON CONFLICT:

CREATE OR REPLACE FUNCTION test_insert_on_conflict()
RETURNS VOID AS $$
BEGIN
    INSERT INTO test_table (id, name) VALUES (1, 'First')
        ON CONFLICT (id) DO NOTHING;

    INSERT INTO test_table (id, name) VALUES (1, 'Second')
        ON CONFLICT (id) DO NOTHING;

    INSERT INTO test_table (id, name) VALUES (2, 'Third')
        ON CONFLICT (id) DO NOTHING;
END;
$$ LANGUAGE plpgsql;

TRUNCATE test_table;
SELECT test_insert_on_conflict();
SELECT * FROM test_table;  -- Result: one row each for id=1 and id=2

Summary

  • Default behavior: Any error (including primary key conflicts) will roll back all operations in the entire function
  • Using subtransactions (BEGIN…EXCEPTION): Only the conflicting statement is rolled back, other statements commit normally
  • Using ON CONFLICT: The most elegant approach, avoids throwing exceptions
  • PostgreSQL functions execute within a single transaction by default, unless you explicitly use an EXCEPTION block to create savepoints

Star
Donate
HiddenMerit Daily · Issue 4
Previous
HiddenMerit Daily · Issue 5
Next

Leave a comment

Registration is not required

Clyde Jin
303 Articles
0 Comments
0 Like
Recent Posts

HiddenMerit Daily · Issue 60

📊 HiddenMerit Daily · Issue 60 Focus on Database Frontiers, Practical Insights for DBAs July 22, 2026 | 5 Selected Global Breaking News 01|Oracle Releases Largest Quarterly Patch in History: 1,449 Patches Fix 1,235 CVEs, 261 Critical On July 21, Oracle released its July 2026 Critical Patch Update (CPU), setting a record for the largest single patch release in the company’s history. This CPU contains 1,449 security patches fixing 1,235 independent CVEs across 32 Oracle product families, of which 261 patches are rated Critical. Patch Distribution by Product Family: Product Family Patches Remotely Exploitable Without Authentication Oracle E‑Business Suite 410 45 Oracle Fusion Middleware 355 219 Oracle Communications 168 122 Oracle MySQL 54 9 Oracle Database Server 15 6 Context for This Patch: Oracle had already issued an urgent “Prepare Now” warning a week earlier, emphasising that AI is fundamentally lowering the barrier to discovering and exploiting vulnerabilities – frontier AI models can analyse software changes, reverse‑engineer security patches, and develop attack paths at unprecedented speed. Oracle has collaborated with state‑of‑the‑art models from Anthropic and OpenAI to proactively identify and fix potential security vulnerabilities. Oracle strongly recommends that customers immediately test and deploy this update in their monthly patch cycles. […]

HiddenMerit Daily · Issue 59

📊 HiddenMerit Daily · Issue 59 Focus on Database Frontiers, Practical Insights for DBAs July 21, 2026 | 5 Selected Global Breaking News 01|Oracle Issues Urgent Warning: July 21 Release Update to Fix Large Number of High‑Risk Vulnerabilities, Immediate Deployment Recommended On July 13, Oracle issued an urgent security warning, strongly recommending that all customers running supported Oracle Database versions (including Oracle Database 19c and Oracle AI Database 26ai) immediately test and deploy the Release Update (RU) after its release on July 21. Background: New frontier AI models are significantly lowering the barrier to discovering and exploiting software vulnerabilities – these models can identify weaknesses, analyse software changes, reverse‑engineer security patches, and develop potential attack paths at unprecedented speed and scale. AI models are also becoming increasingly adept at combining multiple weaknesses across the application and data stack into complex attacks, even when individual weaknesses do not themselves pose a serious risk. As a result, protecting systems solely at the network or application layer is no longer sufficient; enterprises must protect the entire technology stack. Fixes Included in This RU: Oracle has collaborated with state‑of‑the‑art models from Anthropic and OpenAI to proactively identify and fix potential security vulnerabilities. The upcoming […]

HiddenMerit Daily · Issue 58

📊 HiddenMerit Daily · Issue 58 Focus on Database Frontiers, Practical Insights for DBAs July 20, 2026 | 5 Selected Global Breaking News 01|CAICT: Domestic Databases Enter Core System “Deep Water,” AI‑Native Leads New Industry Landscape On July 9, at the 2026 Trustworthy Database Development Conference, CAICT released the “Database Development Research Report (2026).” The report notes that domestic databases have basically completed peripheral system replacement and have officially entered the critical business system breakthrough phase. Key Data: The global database market reached $131.6 billion in 2025 (approximately RMB 894.09 billion). The Chinese database market reached $9.49 billion in 2025 (approximately RMB 64.48 billion), and is expected to reach RMB 97.974 billion by 2028, with a CAGR of 13.06%. The number of domestic database vendors has shrunk from a peak of 167 to 94, with a clear head‑concentration effect and an intensifying “Matthew effect.” AI‑Native Becomes the Main Theme: The report points out that database technology is accelerating its evolution toward the AI‑native direction, and the global database industry is entering a new phase of landscape restructuring. The role of databases is upgrading from “underlying support systems” to “core engines enabling intelligent decision‑making and business innovation.” AI agents are becoming […]

HiddenMerit Daily · Issue 56

📊 HiddenMerit Daily · Issue 56 Focus on Database Frontiers, Practical Insights for DBAs July 6, 2026 | 5 Selected Global Breaking News 01|Kingware Releases Manufacturing Scenario Database Evolution White Paper: SQL Server Replacement Enters “Deep Water” On July 5, CETC Kingware published a technical article titled “Database Evolution in Manufacturing Scenarios: How Kingware Replaces SQL Server,” pointing out that the data surge on industrial shop floors has exceeded the processing capacity of single‑node systems. Traditional database architectures that rely on vertical scaling are facing unprecedented performance challenges. Over the next 1‑3 years, manufacturing enterprises will no longer face only the “choice of replacement,” but must answer the strategic question: “How do we build an autonomous data foundation in the context of de‑IOE?” Three Paradigm Shifts: Hybrid Workloads Become the Norm: The IT architecture of modern factories is shifting from separated OLTP and OLAP to HTAP mode. The same data system must simultaneously handle tens of thousands of device instruction writes per second and minute‑level production report analysis. Distributed Architecture Becomes a Hard Requirement: When a single table exceeds 100 million rows with daily increments exceeding 1 million rows, the index maintenance cost of traditional single‑node databases rises exponentially. Autonomous […]
生成中...
扫描二维码
扫描二维码