Movatterモバイル変換


[0]ホーム

URL:



Facebook
Postgres Pro
Facebook
Downloads
6.4. Returning Data from Modified Rows
Prev UpChapter 6. Data ManipulationHome Next

6.4. Returning Data from Modified Rows

Sometimes it is useful to obtain data from modified rows while they are being manipulated. TheINSERT,UPDATE, andDELETE commands all have an optionalRETURNING clause that supports this. Use ofRETURNING avoids performing an extra database query to collect the data, and is especially valuable when it would otherwise be difficult to identify the modified rows reliably.

The allowed contents of aRETURNING clause are the same as aSELECT command's output list (seeSection 7.3). It can contain column names of the command's target table, or value expressions using those columns. A common shorthand isRETURNING *, which selects all columns of the target table in order.

In anINSERT, the data available toRETURNING is the row as it was inserted. This is not so useful in trivial inserts, since it would just repeat the data provided by the client. But it can be very handy when relying on computed default values. For example, when using aserial column to provide unique identifiers,RETURNING can return the ID assigned to a new row:

CREATE TABLE users (firstname text, lastname text, id serial primary key);INSERT INTO users (firstname, lastname) VALUES ('Joe', 'Cool') RETURNING id;

TheRETURNING clause is also very useful withINSERT ... SELECT.

In anUPDATE, the data available toRETURNING is the new content of the modified row. For example:

UPDATE products SET price = price * 1.10  WHERE price <= 99.99  RETURNING name, price AS new_price;

In aDELETE, the data available toRETURNING is the content of the deleted row. For example:

DELETE FROM products  WHERE obsoletion_date = 'today'  RETURNING *;

If there are triggers (Chapter 39) on the target table, the data available toRETURNING is the row as modified by the triggers. Thus, inspecting columns computed by triggers is another common use-case forRETURNING.


Prev Up Next
6.3. Deleting Data Home Chapter 7. Queries
pdfepub
Go to PostgreSQL 15
By continuing to browse this website, you agree to the use of cookies. Go toPrivacy Policy.

[8]ページ先頭

©2009-2025 Movatter.jp