]> granicus.if.org Git - postgresql/blob - doc/src/sgml/ref/update.sgml
Allow WITH clauses to be attached to INSERT, UPDATE, DELETE statements.
[postgresql] / doc / src / sgml / ref / update.sgml
1 <!--
2 doc/src/sgml/ref/update.sgml
3 PostgreSQL documentation
4 -->
5
6 <refentry id="SQL-UPDATE">
7  <refmeta>
8   <refentrytitle>UPDATE</refentrytitle>
9   <manvolnum>7</manvolnum>
10   <refmiscinfo>SQL - Language Statements</refmiscinfo>
11  </refmeta>
12
13  <refnamediv>
14   <refname>UPDATE</refname>
15   <refpurpose>update rows of a table</refpurpose>
16  </refnamediv>
17
18  <indexterm zone="sql-update">
19   <primary>UPDATE</primary>
20  </indexterm>
21
22  <refsynopsisdiv>
23 <synopsis>
24 [ WITH [ RECURSIVE ] <replaceable class="parameter">with_query</replaceable> [, ...] ]
25 UPDATE [ ONLY ] <replaceable class="PARAMETER">table</replaceable> [ [ AS ] <replaceable class="parameter">alias</replaceable> ]
26     SET { <replaceable class="PARAMETER">column</replaceable> = { <replaceable class="PARAMETER">expression</replaceable> | DEFAULT } |
27           ( <replaceable class="PARAMETER">column</replaceable> [, ...] ) = ( { <replaceable class="PARAMETER">expression</replaceable> | DEFAULT } [, ...] ) } [, ...]
28     [ FROM <replaceable class="PARAMETER">from_list</replaceable> ]
29     [ WHERE <replaceable class="PARAMETER">condition</replaceable> | WHERE CURRENT OF <replaceable class="PARAMETER">cursor_name</replaceable> ]
30     [ RETURNING * | <replaceable class="parameter">output_expression</replaceable> [ [ AS ] <replaceable class="parameter">output_name</replaceable> ] [, ...] ]
31 </synopsis>
32  </refsynopsisdiv>
33
34  <refsect1>
35   <title>Description</title>
36
37   <para>
38    <command>UPDATE</command> changes the values of the specified
39    columns in all rows that satisfy the condition. Only the columns to
40    be modified need be mentioned in the <literal>SET</literal> clause;
41    columns not explicitly modified retain their previous values.
42   </para>
43
44   <para>
45    By default, <command>UPDATE</command> will update rows in the
46    specified table and all its subtables. If you wish to only update
47    the specific table mentioned, you must use the <literal>ONLY</>
48    clause.
49   </para>
50
51   <para>
52    There are two ways to modify a table using information contained in
53    other tables in the database: using sub-selects, or specifying
54    additional tables in the <literal>FROM</literal> clause. Which
55    technique is more appropriate depends on the specific
56    circumstances.
57   </para>
58
59   <para>
60    The optional <literal>RETURNING</> clause causes <command>UPDATE</>
61    to compute and return value(s) based on each row actually updated.
62    Any expression using the table's columns, and/or columns of other
63    tables mentioned in <literal>FROM</literal>, can be computed.
64    The new (post-update) values of the table's columns are used.
65    The syntax of the <literal>RETURNING</> list is identical to that of the
66    output list of <command>SELECT</>.
67   </para>
68
69   <para>
70    You must have the <literal>UPDATE</literal> privilege on the table,
71    or at least on the column(s) that are listed to be updated.
72    You must also have the <literal>SELECT</literal>
73    privilege on any column whose values are read in the
74    <replaceable class="parameter">expressions</replaceable> or
75    <replaceable class="parameter">condition</replaceable>.
76   </para>
77  </refsect1>
78
79  <refsect1>
80   <title>Parameters</title>
81
82   <variablelist>
83    <varlistentry>
84     <term><replaceable class="parameter">with_query</replaceable></term>
85     <listitem>
86      <para>
87       The <literal>WITH</literal> clause allows you to specify one or more
88       subqueries that can be referenced by name in the <command>UPDATE</>
89       query. See <xref linkend="queries-with"> and <xref linkend="sql-select">
90       for details.
91      </para>
92     </listitem>
93    </varlistentry>
94
95    <varlistentry>
96     <term><replaceable class="PARAMETER">table</replaceable></term>
97     <listitem>
98      <para>
99       The name (optionally schema-qualified) of the table to update.
100      </para>
101     </listitem>
102    </varlistentry>
103
104    <varlistentry>
105     <term><replaceable class="parameter">alias</replaceable></term>
106     <listitem>
107      <para>
108       A substitute name for the target table. When an alias is
109       provided, it completely hides the actual name of the table.  For
110       example, given <literal>UPDATE foo AS f</>, the remainder of the
111       <command>UPDATE</command> statement must refer to this table as
112       <literal>f</> not <literal>foo</>.
113      </para>
114     </listitem>
115    </varlistentry>
116
117    <varlistentry>
118     <term><replaceable class="PARAMETER">column</replaceable></term>
119     <listitem>
120      <para>
121       The name of a column in <replaceable
122       class="PARAMETER">table</replaceable>.
123       The column name can be qualified with a subfield name or array
124       subscript, if needed.  Do not include the table's name in the
125       specification of a target column &mdash; for example,
126       <literal>UPDATE tab SET tab.col = 1</> is invalid.
127      </para>
128     </listitem>
129    </varlistentry>
130
131    <varlistentry>
132     <term><replaceable class="PARAMETER">expression</replaceable></term>
133     <listitem>
134      <para>
135       An expression to assign to the column.  The expression can use the
136       old values of this and other columns in the table.
137      </para>
138     </listitem>
139    </varlistentry>
140
141    <varlistentry>
142     <term><literal>DEFAULT</literal></term>
143     <listitem>
144      <para>
145       Set the column to its default value (which will be NULL if no
146       specific default expression has been assigned to it).
147      </para>
148     </listitem>
149    </varlistentry>
150
151    <varlistentry>
152     <term><replaceable class="PARAMETER">from_list</replaceable></term>
153     <listitem>
154      <para>
155       A list of table expressions, allowing columns from other tables
156       to appear in the <literal>WHERE</> condition and the update
157       expressions. This is similar to the list of tables that can be
158       specified in the <xref linkend="sql-from"
159       endterm="sql-from-title"> of a <command>SELECT</command>
160       statement.  Note that the target table must not appear in the
161       <replaceable>from_list</>, unless you intend a self-join (in which
162       case it must appear with an alias in the <replaceable>from_list</>).
163      </para>
164     </listitem>
165    </varlistentry>
166
167    <varlistentry>
168     <term><replaceable class="PARAMETER">condition</replaceable></term>
169     <listitem>
170      <para>
171       An expression that returns a value of type <type>boolean</type>.
172       Only rows for which this expression returns <literal>true</>
173       will be updated.
174      </para>
175     </listitem>
176    </varlistentry>
177
178    <varlistentry>
179     <term><replaceable class="PARAMETER">cursor_name</replaceable></term>
180     <listitem>
181      <para>
182       The name of the cursor to use in a <literal>WHERE CURRENT OF</>
183       condition.  The row to be updated is the one most recently fetched
184       from this cursor.  The cursor must be a non-grouping
185       query on the <command>UPDATE</>'s target table.
186       Note that <literal>WHERE CURRENT OF</> cannot be
187       specified together with a Boolean condition.  See
188       <xref linkend="sql-declare">
189       for more information about using cursors with
190       <literal>WHERE CURRENT OF</>.
191      </para>
192     </listitem>
193    </varlistentry>
194
195    <varlistentry>
196     <term><replaceable class="PARAMETER">output_expression</replaceable></term>
197     <listitem>
198      <para>
199       An expression to be computed and returned by the <command>UPDATE</>
200       command after each row is updated.  The expression can use any
201       column names of the <replaceable class="PARAMETER">table</replaceable>
202       or table(s) listed in <literal>FROM</>.
203       Write <literal>*</> to return all columns.
204      </para>
205     </listitem>
206    </varlistentry>
207
208    <varlistentry>
209     <term><replaceable class="PARAMETER">output_name</replaceable></term>
210     <listitem>
211      <para>
212       A name to use for a returned column.
213      </para>
214     </listitem>
215    </varlistentry>
216   </variablelist>
217  </refsect1>
218
219  <refsect1>
220   <title>Outputs</title>
221
222   <para>
223    On successful completion, an <command>UPDATE</> command returns a command
224    tag of the form
225 <screen>
226 UPDATE <replaceable class="parameter">count</replaceable>
227 </screen>
228    The <replaceable class="parameter">count</replaceable> is the number
229    of rows updated.  If <replaceable class="parameter">count</replaceable> is
230    0, no rows matched the <replaceable
231    class="parameter">condition</replaceable> (this is not considered
232    an error).
233   </para>
234
235   <para>
236    If the <command>UPDATE</> command contains a <literal>RETURNING</>
237    clause, the result will be similar to that of a <command>SELECT</>
238    statement containing the columns and values defined in the
239    <literal>RETURNING</> list, computed over the row(s) updated by the
240    command.
241   </para>
242  </refsect1>
243
244  <refsect1>
245   <title>Notes</title>
246
247   <para>
248    When a <literal>FROM</> clause is present, what essentially happens
249    is that the target table is joined to the tables mentioned in the
250    <replaceable>from_list</replaceable>, and each output row of the join
251    represents an update operation for the target table.  When using
252    <literal>FROM</> you should ensure that the join
253    produces at most one output row for each row to be modified.  In
254    other words, a target row shouldn't join to more than one row from
255    the other table(s).  If it does, then only one of the join rows
256    will be used to update the target row, but which one will be used
257    is not readily predictable.
258   </para>
259
260   <para>
261    Because of this indeterminacy, referencing other tables only within
262    sub-selects is safer, though often harder to read and slower than
263    using a join.
264   </para>
265  </refsect1>
266
267  <refsect1>
268   <title>Examples</title>
269
270   <para>
271    Change the word <literal>Drama</> to <literal>Dramatic</> in the
272    column <structfield>kind</> of the table <structname>films</structname>:
273
274 <programlisting>
275 UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama';
276 </programlisting>
277   </para>
278
279   <para>
280    Adjust temperature entries and reset precipitation to its default
281    value in one row of the table <structname>weather</structname>:
282
283 <programlisting>
284 UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT
285   WHERE city = 'San Francisco' AND date = '2003-07-03';
286 </programlisting>
287   </para>
288
289   <para>
290    Perform the same operation and return the updated entries:
291
292 <programlisting>
293 UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT
294   WHERE city = 'San Francisco' AND date = '2003-07-03'
295   RETURNING temp_lo, temp_hi, prcp;
296 </programlisting>
297   </para>
298
299   <para>
300    Use the alternative column-list syntax to do the same update:
301 <programlisting>
302 UPDATE weather SET (temp_lo, temp_hi, prcp) = (temp_lo+1, temp_lo+15, DEFAULT)
303   WHERE city = 'San Francisco' AND date = '2003-07-03';
304 </programlisting>
305   </para>
306
307   <para>
308    Increment the sales count of the salesperson who manages the
309    account for Acme Corporation, using the <literal>FROM</literal>
310    clause syntax:
311 <programlisting>
312 UPDATE employees SET sales_count = sales_count + 1 FROM accounts
313   WHERE accounts.name = 'Acme Corporation'
314   AND employees.id = accounts.sales_person;
315 </programlisting>
316   </para>
317
318   <para>
319    Perform the same operation, using a sub-select in the
320    <literal>WHERE</literal> clause:
321 <programlisting>
322 UPDATE employees SET sales_count = sales_count + 1 WHERE id =
323   (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation');
324 </programlisting>
325   </para>
326
327   <para>
328    Attempt to insert a new stock item along with the quantity of stock. If
329    the item already exists, instead update the stock count of the existing
330    item. To do this without failing the entire transaction, use savepoints:
331 <programlisting>
332 BEGIN;
333 -- other operations
334 SAVEPOINT sp1;
335 INSERT INTO wines VALUES('Chateau Lafite 2003', '24');
336 -- Assume the above fails because of a unique key violation,
337 -- so now we issue these commands:
338 ROLLBACK TO sp1;
339 UPDATE wines SET stock = stock + 24 WHERE winename = 'Chateau Lafite 2003';
340 -- continue with other operations, and eventually
341 COMMIT;
342 </programlisting>
343   </para>
344
345   <para>
346    Change the <structfield>kind</> column of the table
347    <structname>films</structname> in the row on which the cursor
348    <literal>c_films</> is currently positioned:
349 <programlisting>
350 UPDATE films SET kind = 'Dramatic' WHERE CURRENT OF c_films;
351 </programlisting>
352   </para>
353  </refsect1>
354
355  <refsect1>
356   <title>Compatibility</title>
357
358   <para>
359    This command conforms to the <acronym>SQL</acronym> standard, except
360    that the <literal>FROM</literal> and <literal>RETURNING</> clauses
361    are <productname>PostgreSQL</productname> extensions, as is the ability
362    to use <literal>WITH</> with <command>UPDATE</>.
363   </para>
364
365   <para>
366    According to the standard, the column-list syntax should allow a list
367    of columns to be assigned from a single row-valued expression, such
368    as a sub-select:
369 <programlisting>
370 UPDATE accounts SET (contact_last_name, contact_first_name) =
371     (SELECT last_name, first_name FROM salesmen
372      WHERE salesmen.id = accounts.sales_id);
373 </programlisting>
374    This is not currently implemented &mdash; the source must be a list
375    of independent expressions.
376   </para>
377
378   <para>
379    Some other database systems offer a <literal>FROM</> option in which
380    the target table is supposed to be listed again within <literal>FROM</>.
381    That is not how <productname>PostgreSQL</productname> interprets
382    <literal>FROM</>.  Be careful when porting applications that use this
383    extension.
384   </para>
385  </refsect1>
386 </refentry>