バージョンごとのドキュメント一覧

UPDATE

UPDATE <refpurpose>update rows of a table</refpurpose> — テーブルの行を更新する

概要

[ WITH [ RECURSIVE ] with_query [, ...] ]
UPDATE [ ONLY ] table_name [ * ] [ [ AS ] alias ]
    SET { column_name = { expression | DEFAULT } |
          ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
          ( column_name [, ...] ) = ( sub-SELECT )
        } [, ...]
    [ FROM from_item [, ...] ]
    [ WHERE condition | WHERE CURRENT OF cursor_name ]
    [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]

説明

<title>Description</title>

<command>UPDATE</command> changes the values of the specified columns in all rows that satisfy the condition. Only the columns to be modified need be mentioned in the <literal>SET</literal> clause; columns not explicitly modified retain their previous values. UPDATEは、条件を満たす全ての行の指定した列の値を変更します。 SET句には、変更する列のみを指定する必要があります。 SET句にて明示的に指定されなかった列の値は変更されません。

There are two ways to modify a table using information contained in other tables in the database: using sub-selects, or specifying additional tables in the <literal>FROM</literal> clause. Which technique is more appropriate depends on the specific circumstances. データベース内の他のテーブルの情報を使用してテーブルを変更するには、2つの方法があります。 1つは副問い合わせを使用する方法、もう1つはFROM句で追加のテーブルを指定する方法です。 どちらの方法が適切であるかは状況次第です。

The optional <literal>RETURNING</literal> clause causes <command>UPDATE</command> to compute and return value(s) based on each row actually updated. Any expression using the table's columns, and/or columns of other tables mentioned in <literal>FROM</literal>, can be computed. The new (post-update) values of the table's columns are used. The syntax of the <literal>RETURNING</literal> list is identical to that of the output list of <command>SELECT</command>. RETURNING句を指定すると、UPDATEは実際に更新された各行に基づいて計算された値を返すようになります。 そのテーブルの列およびFROMで指定された他のテーブルの列を使用した式を計算することができます。 テーブル列の新しい(更新された後の)値が使用されます。 RETURNINGリストの構文はSELECTの出力リストと同一です。

You must have the <literal>UPDATE</literal> privilege on the table, or at least on the column(s) that are listed to be updated. You must also have the <literal>SELECT</literal> privilege on any column whose values are read in the <replaceable class="parameter">expressions</replaceable> or <replaceable class="parameter">condition</replaceable>. 更新を行うためには、そのテーブルまたは少なくとも更新対象の列についてUPDATE権限を持たなければなりません。 またexpressionsconditionで値を読み込む列に対するSELECT権限も必要になります。

パラメータ

<title>Parameters</title>
with_query

The <literal>WITH</literal> clause allows you to specify one or more subqueries that can be referenced by name in the <command>UPDATE</command> query. See <xref linkend="queries-with"/> and <xref linkend="sql-select"/> for details. WITH句によりUPDATE問い合わせ内で名前で参照可能な1つ以上の副問い合わせを指定することができます。 7.8SELECTを参照してください。

table_name

The name (optionally schema-qualified) of the table to update. If <literal>ONLY</literal> is specified before the table name, matching rows are updated in the named table only. If <literal>ONLY</literal> is not specified, matching rows are also updated in any tables inheriting from the named table. Optionally, <literal>*</literal> can be specified after the table name to explicitly indicate that descendant tables are included. 更新対象のテーブルの名前です(スキーマ修飾名でも可)。 テーブルの前にONLYを指定すると、指名されたテーブルでのみマッチする行が更新されます。 ONLYを指定しないと、指名したテーブルから継承されたすべてのテーブルでもマッチする行が同時に更新されます。 オプションで、テーブル名の後に*を指定して、明示的に子テーブルが含まれることを示すこともできます。

alias

A substitute name for the target table. When an alias is provided, it completely hides the actual name of the table. For example, given <literal>UPDATE foo AS f</literal>, the remainder of the <command>UPDATE</command> statement must refer to this table as <literal>f</literal> not <literal>foo</literal>. 対象テーブルの代替名です。 別名が指定されると、テーブルの実際の名前は完全に隠蔽されます。 たとえば、UPDATE foo AS fでは、UPDATE文の残りの部分ではfooではなくfとしてこのテーブルを参照しなければなりません。

column_name

The name of a column in the table named by <replaceable class="parameter">table_name</replaceable>. The column name can be qualified with a subfield name or array subscript, if needed. Do not include the table's name in the specification of a target column &mdash; for example, <literal>UPDATE table_name SET table_name.col = 1</literal> is invalid. table_nameで指名されたテーブル内の列名です。 必要に応じて、列名を副フィールド名や配列の指示子で修飾することも可能です。 対象列の指定にはテーブル名を含めないでください。 たとえば、UPDATE table_name SET table_name.col = 1は無効です。

expression

An expression to assign to the column. The expression can use the old values of this and other columns in the table. 列に代入する式です。 この式では、テーブル内の対象列やその他の列の変更前の値を使用することができます。

DEFAULT

Set the column to its default value (which will be NULL if no specific default expression has been assigned to it). An identity column will be set to a new value generated by the associated sequence. For a generated column, specifying this is permitted but merely specifies the normal behavior of computing the column from its generation expression. 列にデフォルト値を設定します(デフォルト式が割り当てられていない場合はNULLになります)。 IDENTITY列には関連するシーケンスにより生成された新しい値が設定されます。 生成列に対して、これを指定することは許されていますが、単に生成式から列を計算するという普通の振る舞いを指定するだけです。

sub-SELECT

A <literal>SELECT</literal> sub-query that produces as many output columns as are listed in the parenthesized column list preceding it. The sub-query must yield no more than one row when executed. If it yields one row, its column values are assigned to the target columns; if it yields no rows, NULL values are assigned to the target columns. The sub-query can refer to old values of the current row of the table being updated. その前の括弧内の列リストに列挙されているのと同じ数の出力列を生成するSELECT副問い合わせです。 副問い合わせは実行時に最大でも1行しか生成してはいけません。 1行だけ生成されたときは、各列の値が対象の列に代入されます。 1行も生成されなかったときは、対象の列にNULL値が代入されます。 副問い合わせは、更新対象のテーブルの現在行の古い値を参照することができます。

from_item

A table expression allowing columns from other tables to appear in the <literal>WHERE</literal> condition and update expressions. This uses the same syntax as the <link linkend="sql-from"><literal>FROM</literal></link> clause of a <command>SELECT</command> statement; for example, an alias for the table name can be specified. Do not repeat the target table as a <replaceable>from_item</replaceable> unless you intend a self-join (in which case it must appear with an alias in the <replaceable>from_item</replaceable>). WHERE条件や更新用の式において、他のテーブルの列を指定するために使用するテーブル式です。 これはSELECT文のFROM句と同じ文法を使います。例えば、テーブル名の別名が指定できます。 自己結合を行う場合を除き、from_itemに更新対象のテーブルを繰り返してはいけません(自己結合を行う場合は、from_item内で更新対象のテーブルとその別名を指定しておく必要があります)。

condition

An expression that returns a value of type <type>boolean</type>. Only rows for which this expression returns <literal>true</literal> will be updated. boolean型の値を返す式です。 この式がtrueを返す行のみが更新されます。

cursor_name

The name of the cursor to use in a <literal>WHERE CURRENT OF</literal> condition. The row to be updated is the one most recently fetched from this cursor. The cursor must be a non-grouping query on the <command>UPDATE</command>'s target table. Note that <literal>WHERE CURRENT OF</literal> cannot be specified together with a Boolean condition. See <xref linkend="sql-declare"/> for more information about using cursors with <literal>WHERE CURRENT OF</literal>. WHERE CURRENT OF条件で使用されるカーソルの名前です。 更新対象の行は、そのカーソルからもっとも最近に取り出された行です。 カーソルはUPDATEの対象テーブルに対するグループ化のない問い合わせでなければなりません。 WHERE CURRENT OFを論理条件といっしょに指定することはできません。 WHERE CURRENT OF付きのカーソル使用に関する情報についてはDECLAREを参照してください。

output_expression

An expression to be computed and returned by the <command>UPDATE</command> command after each row is updated. The expression can use any column names of the table named by <replaceable class="parameter">table_name</replaceable> or table(s) listed in <literal>FROM</literal>. Write <literal>*</literal> to return all columns. 各行を更新した後に計算され、UPDATEによって返される式です。 この式には、table_nameまたはFROMで指定したテーブル(複数可)の任意の列名を使用することができます。 すべての列を返す場合は*と記載してください。

output_name

A name to use for a returned column. 返される列で使用される名前です。

出力

<title>Outputs</title>

On successful completion, an <command>UPDATE</command> command returns a command tag of the form 正常に処理が終わると、UPDATEコマンドは以下の形式のコマンドタグを返します。

UPDATE count

The <replaceable class="parameter">count</replaceable> is the number of rows updated, including matched rows whose values did not change. Note that the number may be less than the number of rows that matched the <replaceable class="parameter">condition</replaceable> when updates were suppressed by a <literal>BEFORE UPDATE</literal> trigger. If <replaceable class="parameter">count</replaceable> is 0, no rows were updated by the query (this is not considered an error). countは、合致したが変更されなかった行を含む、更新された行数を意味します。 BEFORE UPDATEトリガにより更新が抑制された場合に、conditionに合致した行数より少なくなる可能性があることに注意してください。 countが0の場合はconditionに一致する行がなかったことを意味します (これはエラーとはみなされません)。

If the <command>UPDATE</command> command contains a <literal>RETURNING</literal> clause, the result will be similar to that of a <command>SELECT</command> statement containing the columns and values defined in the <literal>RETURNING</literal> list, computed over the row(s) updated by the command. UPDATEコマンドがRETURNING句を持つ場合、その結果は、RETURNINGリストで定義した列と値を持ち、そのコマンドで更新された行全体に対して計算を行うSELECT文の結果と似たものになるでしょう。

注釈

<title>Notes</title>

When a <literal>FROM</literal> clause is present, what essentially happens is that the target table is joined to the tables mentioned in the <replaceable>from_item</replaceable> list, and each output row of the join represents an update operation for the target table. When using <literal>FROM</literal> you should ensure that the join produces at most one output row for each row to be modified. In other words, a target row shouldn't join to more than one row from the other table(s). If it does, then only one of the join rows will be used to update the target row, but which one will be used is not readily predictable. FROM句が存在する場合、基本的に、対象テーブルとfrom_itemリストで指定されたテーブルが結合され、この結合の出力行が対象テーブルの更新操作の結果となります。 FROM句を使用する場合、更新対象テーブルの1行に対して、結合結果が複数行にならないように注意してください。 言い換えると、対象テーブルの個々の行は、他テーブルの複数の行と結合すべきではありません。 結合結果が複数行になった場合、対象行の更新には結合結果のいずれか1行のみが使用されますが、どの行が使用されるかは簡単には予測できません。

Because of this indeterminacy, referencing other tables only within sub-selects is safer, though often harder to read and slower than using a join. このような不定性の問題があるため、他テーブルの参照は副問い合わせ内のみに留めておいた方がより安全です(ただし、結合よりも可読性や実行速度は低下します)。

In the case of a partitioned table, updating a row might cause it to no longer satisfy the partition constraint of the containing partition. In that case, if there is some other partition in the partition tree for which this row satisfies its partition constraint, then the row is moved to that partition. If there is no such partition, an error will occur. Behind the scenes, the row movement is actually a <command>DELETE</command> and <command>INSERT</command> operation. パーティションテーブルの場合、行を更新することによって含んでいるパーティションのパーティション制約を満たさなくなることがありえます。 その場合、この行がそのパーティション制約を満たす他のパーティションがパーティションツリー内にあれば、行はそのパーティションに移されます。 もし、そのようなパーティションがなければ、エラーが発生します。 舞台裏では、行の移動は実際はDELETEINSERT操作です。

There is a possibility that a concurrent <command>UPDATE</command> or <command>DELETE</command> on the row being moved will get a serialization failure error. Suppose session 1 is performing an <command>UPDATE</command> on a partition key, and meanwhile a concurrent session 2 for which this row is visible performs an <command>UPDATE</command> or <command>DELETE</command> operation on this row. In such case, session 2's <command>UPDATE</command> or <command>DELETE</command> will detect the row movement and raise a serialization failure error (which always returns with an SQLSTATE code '40001'). Applications may wish to retry the transaction if this occurs. In the usual case where the table is not partitioned, or where there is no row movement, session 2 would have identified the newly updated row and carried out the <command>UPDATE</command>/<command>DELETE</command> on this new row version. 移される行に対して同時に実行されるUPDATEDELETEのために直列化の失敗エラーになる可能性があります。 セッション1がパーティションキーに対してUPDATEを実行中であるとしましょう。一方、同時に実行しているセッション2に対してこの行は可視であり、セッション2はこの行に対してUPDATEまたはDELETE操作をするとしましょう。 その場合、セッション2のUPDATEまたはDELETEは、行の移動を検出し、直列化の失敗エラー(常にSQLSTATE値が'40001'で返る)を発生させます。 これが起きた場合には、アプリケーションはトランザクションを再試行すると良いでしょう。 テーブルがパーティション化されていない、または、行の移動がない通常の場合には、セッション2は新しく更新された行を特定し、この新しい行のバージョンに対してUPDATE/DELETEを実行します。

Note that while rows can be moved from local partitions to a foreign-table partition (provided the foreign data wrapper supports tuple routing), they cannot be moved from a foreign-table partition to another partition. (外部データラッパーがタプルルーティングをサポートしていれば)行をローカルパーティションから外部テーブルパーティションへ移動できますが、外部テーブルパーティションから別のパーティションに移動できないことに注意してください。

An attempt of moving a row from one partition to another will fail if a foreign key is found to directly reference an ancestor of the source partition that is not the same as the ancestor that's mentioned in the <command>UPDATE</command> query. あるパーティションから別のパーティションへ行を移動しようとしても、UPDATE問い合わせで指定された祖先とは異なる移動元のパーティションの祖先を外部キーが直接参照していることが判明した場合、失敗します。

<title>Examples</title>

Change the word <literal>Drama</literal> to <literal>Dramatic</literal> in the column <structfield>kind</structfield> of the table <structname>films</structname>: filmsテーブルのkind列にあるDramaという単語をDramaticに変更します。

UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama';

Adjust temperature entries and reset precipitation to its default value in one row of the table <structname>weather</structname>: weatherテーブルの特定の行に対し、気温に関する項目を調整し、降水量をデフォルト値に戻します。

UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT
  WHERE city = 'San Francisco' AND date = '2003-07-03';

Perform the same operation and return the updated entries: 同じ操作を行い、更新された項目を返します。

UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT
  WHERE city = 'San Francisco' AND date = '2003-07-03'
  RETURNING temp_lo, temp_hi, prcp;

Use the alternative column-list syntax to do the same update: もう一つの方法である列リスト構文を使用して同じ更新を行います。

UPDATE weather SET (temp_lo, temp_hi, prcp) = (temp_lo+1, temp_lo+15, DEFAULT)
  WHERE city = 'San Francisco' AND date = '2003-07-03';

Increment the sales count of the salesperson who manages the account for Acme Corporation, using the <literal>FROM</literal> clause syntax: FROM句の構文を使用して、Acme Corporationを顧客とするセールスパーソンのセールスカウントを1増加させます。

UPDATE employees SET sales_count = sales_count + 1 FROM accounts
  WHERE accounts.name = 'Acme Corporation'
  AND employees.id = accounts.sales_person;

Perform the same operation, using a sub-select in the <literal>WHERE</literal> clause: WHERE句で副問い合わせを使用して、同じ操作を行います。

UPDATE employees SET sales_count = sales_count + 1 WHERE id =
  (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation');

Update contact names in an accounts table to match the currently assigned salespeople: accountsテーブルのコンタクト先の氏名を、現在アサインされているセールスパーソンと一致するよう更新します。

UPDATE accounts SET (contact_first_name, contact_last_name) =
    (SELECT first_name, last_name FROM employees
     WHERE employees.id = accounts.sales_person);

A similar result could be accomplished with a join: 同じような結果は結合を使っても得ることができます。

UPDATE accounts SET contact_first_name = first_name,
                    contact_last_name = last_name
  FROM employees WHERE employees.id = accounts.sales_person;

However, the second query may give unexpected results if <structname>employees</structname>.<structfield>id</structfield> is not a unique key, whereas the first query is guaranteed to raise an error if there are multiple <structfield>id</structfield> matches. Also, if there is no match for a particular <structname>accounts</structname>.<structfield>sales_person</structfield> entry, the first query will set the corresponding name fields to NULL, whereas the second query will not update that row at all. ただし、employees.idが一意キーでない場合、2番目の問い合わせは予期しない結果をもたらすかもしれません。 一方で、最初の問い合わせは、複数のidがマッチしたときはエラーを発生することが保証されます。 また、あるaccounts.sales_personエントリにマッチするレコードがない場合、最初の問い合わせは対応する名前フィールドをNULLに設定しますが、2番目の問い合わせは、その行を全く更新しません。

Update statistics in a summary table to match the current data: summaryテーブルの統計情報を現在のデータに合うように更新します。

UPDATE summary s SET (sum_x, sum_y, avg_x, avg_y) =
    (SELECT sum(x), sum(y), avg(x), avg(y) FROM data d
     WHERE d.group_id = s.group_id);

Attempt to insert a new stock item along with the quantity of stock. If the item already exists, instead update the stock count of the existing item. To do this without failing the entire transaction, use savepoints: 新しい商品とその在庫数を挿入します。 既にその商品が存在している場合は、代わりに既存商品の在庫数を更新します。 トランザクション全体が失敗することがないようにこの操作を行うには、セーブポイントを使用してください。

BEGIN;

&#45;- other operations

-- 何かしらの他の操作を行います。
SAVEPOINT sp1;
INSERT INTO wines VALUES('Chateau Lafite 2003', '24');

&#45;- Assume the above fails because of a unique key violation,
&#45;- so now we issue these commands:

-- 上記のコマンドが一意キー違反により失敗したとします。
-- この場合、次のコマンドを実行します。
ROLLBACK TO sp1;
UPDATE wines SET stock = stock + 24 WHERE winename = 'Chateau Lafite 2003';

&#45;- continue with other operations, and eventually

-- 他の操作を続けた後、最後に次を実行します。
COMMIT;

Change the <structfield>kind</structfield> column of the table <structname>films</structname> in the row on which the cursor <literal>c_films</literal> is currently positioned: filmsテーブルにおいて、c_filmsカーソルが現在位置している行のkind列を変更します。

UPDATE films SET kind = 'Dramatic' WHERE CURRENT OF c_films;

互換性

<title>Compatibility</title>

This command conforms to the <acronym>SQL</acronym> standard, except that the <literal>FROM</literal> and <literal>RETURNING</literal> clauses are <productname>PostgreSQL</productname> extensions, as is the ability to use <literal>WITH</literal> with <command>UPDATE</command>. このコマンドは標準SQLに準拠しています。 ただしFROM句およびRETURNING句はPostgreSQLの拡張です。 UPDATEWITHが使用可能であることも同様に拡張です。

Some other database systems offer a <literal>FROM</literal> option in which the target table is supposed to be listed again within <literal>FROM</literal>. That is not how <productname>PostgreSQL</productname> interprets <literal>FROM</literal>. Be careful when porting applications that use this extension. 他のデータベースシステムには、FROMオプション内で、対象テーブルがFROM内に再度指定されることを前提として動作するものもあります。 これはPostgreSQLにおけるFROMの解釈方法とは異なります。 この拡張機能を使用するアプリケーションを移植する時は注意してください。

According to the standard, the source value for a parenthesized sub-list of target column names can be any row-valued expression yielding the correct number of columns. <productname>PostgreSQL</productname> only allows the source value to be a <link linkend="sql-syntax-row-constructors">row constructor</link> or a sub-<literal>SELECT</literal>. An individual column's updated value can be specified as <literal>DEFAULT</literal> in the row-constructor case, but not inside a sub-<literal>SELECT</literal>. 標準に従うと、括弧内の対象列名の部分リストに対する入力値は、正しい数の列を生成する任意の行値による式です。 PostgreSQLでは入力値として、行コンストラクタあるいはsub-SELECTしか許していません。 行コンストラクタを使う場合、個々の列の更新値をDEFAULTとして指定することができますが、sub-SELECTの内部ではできません。