]> begriffs open source - ai-pg/blob - full-docs/src/sgml/html/tutorial-transactions.html
PG 18 docs from https://ftp.postgresql.org/pub/source/v18.0/postgresql-18.0-docs...
[ai-pg] / full-docs / src / sgml / html / tutorial-transactions.html
1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>3.4. Transactions</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="tutorial-fk.html" title="3.3. Foreign Keys" /><link rel="next" href="tutorial-window.html" title="3.5. Window Functions" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">3.4. Transactions</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="tutorial-fk.html" title="3.3. Foreign Keys">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="tutorial-advanced.html" title="Chapter 3. Advanced Features">Up</a></td><th width="60%" align="center">Chapter 3. Advanced Features</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="tutorial-window.html" title="3.5. Window Functions">Next</a></td></tr></table><hr /></div><div class="sect1" id="TUTORIAL-TRANSACTIONS"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.4. Transactions <a href="#TUTORIAL-TRANSACTIONS" class="id_link">#</a></h2></div></div></div><a id="id-1.4.5.5.2" class="indexterm"></a><p>
3     <em class="firstterm">Transactions</em> are a fundamental concept of all database
4     systems.  The essential point of a transaction is that it bundles
5     multiple steps into a single, all-or-nothing operation.  The intermediate
6     states between the steps are not visible to other concurrent transactions,
7     and if some failure occurs that prevents the transaction from completing,
8     then none of the steps affect the database at all.
9    </p><p>
10     For example, consider a bank database that contains balances for various
11     customer accounts, as well as total deposit balances for branches.
12     Suppose that we want to record a payment of $100.00 from Alice's account
13     to Bob's account.  Simplifying outrageously, the SQL commands for this
14     might look like:
15
16 </p><pre class="programlisting">
17 UPDATE accounts SET balance = balance - 100.00
18     WHERE name = 'Alice';
19 UPDATE branches SET balance = balance - 100.00
20     WHERE name = (SELECT branch_name FROM accounts WHERE name = 'Alice');
21 UPDATE accounts SET balance = balance + 100.00
22     WHERE name = 'Bob';
23 UPDATE branches SET balance = balance + 100.00
24     WHERE name = (SELECT branch_name FROM accounts WHERE name = 'Bob');
25 </pre><p>
26    </p><p>
27     The details of these commands are not important here; the important
28     point is that there are several separate updates involved to accomplish
29     this rather simple operation.  Our bank's officers will want to be
30     assured that either all these updates happen, or none of them happen.
31     It would certainly not do for a system failure to result in Bob
32     receiving $100.00 that was not debited from Alice.  Nor would Alice long
33     remain a happy customer if she was debited without Bob being credited.
34     We need a guarantee that if something goes wrong partway through the
35     operation, none of the steps executed so far will take effect.  Grouping
36     the updates into a <em class="firstterm">transaction</em> gives us this guarantee.
37     A transaction is said to be <em class="firstterm">atomic</em>: from the point of
38     view of other transactions, it either happens completely or not at all.
39    </p><p>
40     We also want a
41     guarantee that once a transaction is completed and acknowledged by
42     the database system, it has indeed been permanently recorded
43     and won't be lost even if a crash ensues shortly thereafter.
44     For example, if we are recording a cash withdrawal by Bob,
45     we do not want any chance that the debit to his account will
46     disappear in a crash just after he walks out the bank door.
47     A transactional database guarantees that all the updates made by
48     a transaction are logged in permanent storage (i.e., on disk) before
49     the transaction is reported complete.
50    </p><p>
51     Another important property of transactional databases is closely
52     related to the notion of atomic updates: when multiple transactions
53     are running concurrently, each one should not be able to see the
54     incomplete changes made by others.  For example, if one transaction
55     is busy totalling all the branch balances, it would not do for it
56     to include the debit from Alice's branch but not the credit to
57     Bob's branch, nor vice versa.  So transactions must be all-or-nothing
58     not only in terms of their permanent effect on the database, but
59     also in terms of their visibility as they happen.  The updates made
60     so far by an open transaction are invisible to other transactions
61     until the transaction completes, whereupon all the updates become
62     visible simultaneously.
63    </p><p>
64     In <span class="productname">PostgreSQL</span>, a transaction is set up by surrounding
65     the SQL commands of the transaction with
66     <code class="command">BEGIN</code> and <code class="command">COMMIT</code> commands.  So our banking
67     transaction would actually look like:
68
69 </p><pre class="programlisting">
70 BEGIN;
71 UPDATE accounts SET balance = balance - 100.00
72     WHERE name = 'Alice';
73 -- etc etc
74 COMMIT;
75 </pre><p>
76    </p><p>
77     If, partway through the transaction, we decide we do not want to
78     commit (perhaps we just noticed that Alice's balance went negative),
79     we can issue the command <code class="command">ROLLBACK</code> instead of
80     <code class="command">COMMIT</code>, and all our updates so far will be canceled.
81    </p><p>
82     <span class="productname">PostgreSQL</span> actually treats every SQL statement as being
83     executed within a transaction.  If you do not issue a <code class="command">BEGIN</code>
84     command,
85     then each individual statement has an implicit <code class="command">BEGIN</code> and
86     (if successful) <code class="command">COMMIT</code> wrapped around it.  A group of
87     statements surrounded by <code class="command">BEGIN</code> and <code class="command">COMMIT</code>
88     is sometimes called a <em class="firstterm">transaction block</em>.
89    </p><div class="note"><h3 class="title">Note</h3><p>
90      Some client libraries issue <code class="command">BEGIN</code> and <code class="command">COMMIT</code>
91      commands automatically, so that you might get the effect of transaction
92      blocks without asking.  Check the documentation for the interface
93      you are using.
94     </p></div><p>
95     It's possible to control the statements in a transaction in a more
96     granular fashion through the use of <em class="firstterm">savepoints</em>.  Savepoints
97     allow you to selectively discard parts of the transaction, while
98     committing the rest.  After defining a savepoint with
99     <code class="command">SAVEPOINT</code>, you can if needed roll back to the savepoint
100     with <code class="command">ROLLBACK TO</code>.  All the transaction's database changes
101     between defining the savepoint and rolling back to it are discarded, but
102     changes earlier than the savepoint are kept.
103    </p><p>
104     After rolling back to a savepoint, it continues to be defined, so you can
105     roll back to it several times.  Conversely, if you are sure you won't need
106     to roll back to a particular savepoint again, it can be released, so the
107     system can free some resources.  Keep in mind that either releasing or
108     rolling back to a savepoint
109     will automatically release all savepoints that were defined after it.
110    </p><p>
111     All this is happening within the transaction block, so none of it
112     is visible to other database sessions.  When and if you commit the
113     transaction block, the committed actions become visible as a unit
114     to other sessions, while the rolled-back actions never become visible
115     at all.
116    </p><p>
117     Remembering the bank database, suppose we debit $100.00 from Alice's
118     account, and credit Bob's account, only to find later that we should
119     have credited Wally's account.  We could do it using savepoints like
120     this:
121
122 </p><pre class="programlisting">
123 BEGIN;
124 UPDATE accounts SET balance = balance - 100.00
125     WHERE name = 'Alice';
126 SAVEPOINT my_savepoint;
127 UPDATE accounts SET balance = balance + 100.00
128     WHERE name = 'Bob';
129 -- oops ... forget that and use Wally's account
130 ROLLBACK TO my_savepoint;
131 UPDATE accounts SET balance = balance + 100.00
132     WHERE name = 'Wally';
133 COMMIT;
134 </pre><p>
135    </p><p>
136     This example is, of course, oversimplified, but there's a lot of control
137     possible in a transaction block through the use of savepoints.
138     Moreover, <code class="command">ROLLBACK TO</code> is the only way to regain control of a
139     transaction block that was put in aborted state by the
140     system due to an error, short of rolling it back completely and starting
141     again.
142    </p></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="tutorial-fk.html" title="3.3. Foreign Keys">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="tutorial-advanced.html" title="Chapter 3. Advanced Features">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="tutorial-window.html" title="3.5. Window Functions">Next</a></td></tr><tr><td width="40%" align="left" valign="top">3.3. Foreign Keys </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="40%" align="right" valign="top"> 3.5. Window Functions</td></tr></table></div></body></html>