Updating Data in a Table
Data updating is performed to modify data in a database. You can update one row, all rows, or specified rows of data, or update data in a single column without affecting the data in the other columns.
The following types of information are required when the UPDATE statement is used to update a row:
- Table name and column names of the data to be updated
- New column data
- Rows of the data to be updated
- You can use a schema as a modifier of the table name. If no such modifier is specified, the table is located based on the default schema.
- In the statement, SET is followed by the target column and the new value of the column. The new value can be a constant or an expression.
- The table can contain the WHERE clause to filter the data that is equal to the specified condition.
- If the statement does not include the WHERE clause, all rows are updated.
- If the statement includes the WHERE clause, only the rows matching the clause condition are updated.
In the SET clause, the equal sign (=) indicates value setting. In the WHERE clause, the equal sign indicates comparison. The WHERE clause can specify a condition using the equal and other operators.
Generally, the SQL language does not provide a unique ID for a row of data. Therefore, it is impossible to directly specify the rows of the data to be updated. However, you can specify the rows by setting a condition that only the rows meet. If a table contains primary keys, you can specify a row by primary key.
The following is an example of updating data in the table:
- c_customer_sk in table customer_t1 must be changed from 9527 to 9876:
UPDATE customer_t1 SET c_customer_sk = 9876 WHERE c_customer_sk = 9527;
UPDATE customer_t1 SET c_customer_sk= c_customer_sk + 100 WHERE c_customer_sk= 9527;
UPDATE public.customer_t1 SET c_customer_sk= 9876 WHERE c_customer_sk= 9527;
- If the WHERE clause is not included, increase all the c_customer_sk values by 100.
UPDATE customer_t1 SET c_customer_sk = c_customer_sk + 100;
- c_customer_sk values greater than 9527 in table customer_t1 must be changed to 9876:
UPDATE customer_t1 SET c_customer_sk = 9876 WHERE c_customer_sk > 9527;
- You can run an UPDATE statement to update multiple columns by specifying multiple values in the SET clause. For example:
UPDATE customer_t1 SET c_customer_id = 'Admin', c_first_name = 'Local' WHERE c_customer_sk = 4421;
After data has been updated or deleted in batches, a large number of deletion markers are generated in the data file. During query, data that is marked out by these deletion markers needs to be scanned as well. In this case, the query performance deteriorates after batch updates or deletions. If data needs to be updated or deleted in batches frequently, you are advised to periodically do VACUUM FULL to maintain the query performance.