UPDATE

The UPDATE statement updates rows in a table.

Warning:

If you update a row that contains a column referenced by a foreign key constraint and has an ON UPDATE action, all of the dependent rows will also be updated.

Required privileges

The user must have the SELECT and UPDATE privileges on the table.

Synopsis

WITHcommon_table_expr,UPDATEtable_nameAStable_alias_nameSETcolumn_name=a_expr(column_name,)=(select_stmta_expr,),WHEREa_exprsort_clauselimit_clauseRETURNINGtarget_listNOTHING

Parameters

ParameterDescription
common_table_exprSee Common Table Expressions.
table_nameThe name of the table that contains the rows you want to update.
AS table_alias_nameAn alias for the table name. When an alias is provided, it completely hides the actual table name.
column_nameThe name of the column whose values you want to update.
a_exprThe new value you want to use, the aggregate function you want to perform, or the scalar expression you want to use.
DEFAULTTo fill columns with their default values, use DEFAULT VALUES in place of a_expr. To fill a specific column with its default value, leave the value out of the a_expr or use DEFAULT at the appropriate position.
column_nameThe name of a column to update.
select_stmtA selection query. Each value must match the data type of its column on the left side of =.
WHERE a_expra_expr must be a scalar expression that returns Boolean values using columns (e.g., <column> = <value>). Update rows that return TRUE.Without a WHERE clause in your statement, UPDATE updates all rows in the table.
sort_clauseAn ORDER BY clause. See Ordering Query Results for more details.
limit_clauseA LIMIT clause. See Limiting Query Results for more details.
RETURNING target_listReturn values based on rows updated, where target_list can be specific column names from the table, * for all columns, or computations using scalar expressions. To return nothing in the response, not even the number of rows updated, use RETURNING NOTHING.

Examples

Update a single column in a single row

  1. > SELECT * FROM accounts;
  1. +----+----------+----------+
  2. | id | balance | customer |
  3. +----+----------+----------+
  4. | 1 | 10000.50 | Ilya |
  5. | 2 | 4000.0 | Julian |
  6. | 3 | 8700.0 | Dario |
  7. | 4 | 3400.0 | Nitin |
  8. +----+----------+----------+
  9. (4 rows)
  1. > UPDATE accounts SET balance = 5000.0 WHERE id = 2;
  1. > SELECT * FROM accounts;
  1. +----+----------+----------+
  2. | id | balance | customer |
  3. +----+----------+----------+
  4. | 1 | 10000.50 | Ilya |
  5. | 2 | 5000.0 | Julian |
  6. | 3 | 8700.0 | Dario |
  7. | 4 | 3400.0 | Nitin |
  8. +----+----------+----------+
  9. (4 rows)

Update multiple columns in a single row

  1. > UPDATE accounts SET (balance, customer) = (9000.0, 'Kelly') WHERE id = 2;
  1. > SELECT * FROM accounts;
  1. +----+----------+----------+
  2. | id | balance | customer |
  3. +----+----------+----------+
  4. | 1 | 10000.50 | Ilya |
  5. | 2 | 9000.0 | Kelly |
  6. | 3 | 8700.0 | Dario |
  7. | 4 | 3400.0 | Nitin |
  8. +----+----------+----------+
  9. (4 rows)
  1. > UPDATE accounts SET balance = 6300.0, customer = 'Stanley' WHERE id = 3;
  1. > SELECT * FROM accounts;
  1. +----+----------+----------+
  2. | id | balance | customer |
  3. +----+----------+----------+
  4. | 1 | 10000.50 | Ilya |
  5. | 2 | 9000.0 | Kelly |
  6. | 3 | 6300.0 | Stanley |
  7. | 4 | 3400.0 | Nitin |
  8. +----+----------+----------+
  9. (4 rows)

Update using SELECT statement

  1. > UPDATE accounts SET (balance, customer) =
  2. (SELECT balance, customer FROM accounts WHERE id = 2)
  3. WHERE id = 4;
  1. > SELECT * FROM accounts;
  1. +----+----------+----------+
  2. | id | balance | customer |
  3. +----+----------+----------+
  4. | 1 | 10000.50 | Ilya |
  5. | 2 | 9000.0 | Kelly |
  6. | 3 | 6300.0 | Stanley |
  7. | 4 | 9000.0 | Kelly |
  8. +----+----------+----------+
  9. (4 rows)

Update with default values

  1. > UPDATE accounts SET balance = DEFAULT where customer = 'Stanley';
  1. > SELECT * FROM accounts;
  1. +----+----------+----------+
  2. | id | balance | customer |
  3. +----+----------+----------+
  4. | 1 | 10000.50 | Ilya |
  5. | 2 | 9000.0 | Kelly |
  6. | 3 | NULL | Stanley |
  7. | 4 | 9000.0 | Kelly |
  8. +----+----------+----------+
  9. (4 rows)

Update all rows

Warning:

If you do not use the WHERE clause to specify the rows to be updated, the values for all rows will be updated.

  1. > UPDATE accounts SET balance = 5000.0;
  1. > SELECT * FROM accounts;
  1. +----+---------+----------+
  2. | id | balance | customer |
  3. +----+---------+----------+
  4. | 1 | 5000.0 | Ilya |
  5. | 2 | 5000.0 | Kelly |
  6. | 3 | 5000.0 | Stanley |
  7. | 4 | 5000.0 | Kelly |
  8. +----+---------+----------+
  9. (4 rows)

Update and return values

In this example, the RETURNING clause returns the id value of the row updated. The language-specific versions assume that you have installed the relevant client drivers.

Tip:
This use of RETURNING mirrors the behavior of MySQL's last_insert_id() function.

Note:
When a driver provides a query() method for statements that return results and an exec() method for statements that do not (e.g., Go), it's likely necessary to use the query() method for UPDATE statements with RETURNING.

  1. > UPDATE accounts SET balance = DEFAULT WHERE id = 1 RETURNING id;
  1. +----+
  2. | id |
  3. +----+
  4. | 1 |
  5. +----+
  6. (1 row)
  1. # Import the driver.
  2. import psycopg2
  3. # Connect to the "bank" database.
  4. conn = psycopg2.connect(
  5. database='bank',
  6. user='root',
  7. host='localhost',
  8. port=26257
  9. )
  10. # Make each statement commit immediately.
  11. conn.set_session(autocommit=True)
  12. # Open a cursor to perform database operations.
  13. cur = conn.cursor()
  14. # Update a row in the "accounts" table
  15. # and return the "id" value.
  16. cur.execute(
  17. 'UPDATE accounts SET balance = DEFAULT WHERE id = 1 RETURNING id'
  18. )
  19. # Print out the returned value.
  20. rows = cur.fetchall()
  21. print('ID:')
  22. for row in rows:
  23. print([str(cell) for cell in row])
  24. # Close the database connection.
  25. cur.close()
  26. conn.close()

The printed value would look like:

  1. ID:
  2. ['1']
  1. # Import the driver.
  2. require 'pg'
  3. # Connect to the "bank" database.
  4. conn = PG.connect(
  5. user: 'root',
  6. dbname: 'bank',
  7. host: 'localhost',
  8. port: 26257
  9. )
  10. # Update a row in the "accounts" table
  11. # and return the "id" value.
  12. conn.exec(
  13. 'UPDATE accounts SET balance = DEFAULT WHERE id = 1 RETURNING id'
  14. ) do |res|
  15. # Print out the returned value.
  16. puts "ID:"
  17. res.each do |row|
  18. puts row
  19. end
  20. end
  21. # Close communication with the database.
  22. conn.close()

The printed value would look like:

  1. ID:
  2. {"id"=>"1"}
  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. _ "github.com/lib/pq"
  7. )
  8. func main() {
  9. //Connect to the "bank" database.
  10. db, err := sql.Open(
  11. "postgres",
  12. "postgresql://root@localhost:26257/bank?sslmode=disable"
  13. )
  14. if err != nil {
  15. log.Fatal("error connecting to the database: ", err)
  16. }
  17. // Update a row in the "accounts" table
  18. // and return the "id" value.
  19. rows, err := db.Query(
  20. "UPDATE accounts SET balance = DEFAULT WHERE id = 1 RETURNING id",
  21. )
  22. if err != nil {
  23. log.Fatal(err)
  24. }
  25. // Print out the returned value.
  26. defer rows.Close()
  27. fmt.Println("ID:")
  28. for rows.Next() {
  29. var id int
  30. if err := rows.Scan(&id); err != nil {
  31. log.Fatal(err)
  32. }
  33. fmt.Printf("%d\n", id)
  34. }
  35. }

The printed value would look like:

  1. ID:
  2. 1
  1. var async = require('async');
  2. // Require the driver.
  3. var pg = require('pg');
  4. // Connect to the "bank" database.
  5. var config = {
  6. user: 'root',
  7. host: 'localhost',
  8. database: 'bank',
  9. port: 26257
  10. };
  11. pg.connect(config, function (err, client, done) {
  12. // Closes communication with the database and exits.
  13. var finish = function () {
  14. done();
  15. process.exit();
  16. };
  17. if (err) {
  18. console.error('could not connect to cockroachdb', err);
  19. finish();
  20. }
  21. async.waterfall([
  22. function (next) {
  23. // Update a row in the "accounts" table
  24. // and return the "id" value.
  25. client.query(
  26. `UPDATE accounts SET balance = DEFAULT WHERE id = 1 RETURNING id`,
  27. next
  28. );
  29. }
  30. ],
  31. function (err, results) {
  32. if (err) {
  33. console.error('error updating and selecting from accounts', err);
  34. finish();
  35. }
  36. // Print out the returned value.
  37. console.log('ID:');
  38. results.rows.forEach(function (row) {
  39. console.log(row);
  40. });
  41. finish();
  42. });
  43. });

The printed value would like:

  1. ID:
  2. { id: '1' }

See also

Was this page helpful?
YesNo