UPDATE

Synopsis

Use the UPDATE statement to modify the values of specified columns in all rows that meet certain conditions, and when conditions are not provided in WHERE clause, all rows are updated. UPDATE outputs the number of rows that are being updated.

Syntax

  1. update ::= [ WITH [ RECURSIVE ] with_query [ , ... ] ] UPDATE
  2. [ ONLY ] table_name [ * ] [ [ AS ] alias ] SET update_item
  3. [ , ... ] [ WHERE condition
  4. | WHERE CURRENT OF cursor_name ]
  5. [ returning_clause ]
  6. returning_clause ::= RETURNING { * | { output_expression
  7. [ [ AS ] output_name ] }
  8. [ , ... ] }
  9. update_item ::= column_name = column_value
  10. | ( column_names ) = [ ROW ] ( column_values )
  11. | ( column_names ) = ( query )
  12. column_values ::= { expression | DEFAULT } [ , ... ]
  13. column_names ::= column_name [ , ... ]

update

UPDATE - 图1

returning_clause

UPDATE - 图2

update_item

UPDATE - 图3

column_values

UPDATE - 图4

column_names

UPDATE - 图5

Semantics

Updating columns that are part of an index key including PRIMARY KEY is not yet supported.

  • While the WHERE clause allows a wide range of operators, the exact conditions used in the where clause have significant performance considerations (especially for large datasets). For the best performance, use a WHERE clause that provides values for all columns in PRIMARY KEY or INDEX KEY.

with_query

Specify the subqueries that are referenced by name in the UPDATE statement.

table_name

Specify the name of the table to be updated.

alias

Specify the identifier of the target table within the UPDATE statement. When an alias is specified, it must be used in place of the actual table in the statement.

column_name

Specify the column in the table to be updated.

expression

Specify the value to be assigned to a column. When the expression is referencing a column, the old value of this column is used to evaluate.

output_expression

Specify the value to be returned. When the output_expression is referencing a column, the new value of this column (updated value) is used to evaluate.

subquery

Specify the SELECT subquery statement. Its selected values will be assigned to the specified columns.

Examples

Create a sample table, insert a few rows, then update the inserted rows.

  1. yugabyte=# CREATE TABLE sample(k1 int, k2 int, v1 int, v2 text, PRIMARY KEY (k1, k2));
  1. yugabyte=# INSERT INTO sample VALUES (1, 2.0, 3, 'a'), (2, 3.0, 4, 'b'), (3, 4.0, 5, 'c');
  1. yugabyte=# SELECT * FROM sample ORDER BY k1;
  1. k1 | k2 | v1 | v2
  2. ----+----+----+----
  3. 1 | 2 | 3 | a
  4. 2 | 3 | 4 | b
  5. 3 | 4 | 5 | c
  6. (3 rows)
  1. yugabyte=# UPDATE sample SET v1 = v1 + 3, v2 = '7' WHERE k1 = 2 AND k2 = 3;
  1. UPDATE 1
  1. yugabyte=# SELECT * FROM sample ORDER BY k1;
  1. k1 | k2 | v1 | v2
  2. ----+----+----+----
  3. 1 | 2 | 3 | a
  4. 2 | 3 | 7 | 7
  5. 3 | 4 | 5 | c
  6. (2 rows)

See also