In PostgreSQL, updating data in tables is primarily achieved using the UPDATE statement. The UPDATE statement allows you to modify one or more rows within a table. The basic structure of the UPDATE statement is as follows:
sqlUPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
The SET clause specifies the columns to update and their new values. The WHERE clause is optional and is used to define which rows should be updated. If the WHERE clause is omitted, all rows in the table will be updated for the specified columns.
Example
Assume we have a table named employees with the following structure:
| id | name | salary |
|---|---|---|
| 1 | Alice | 50000 |
| 2 | Bob | 60000 |
| 3 | Carol | 55000 |
If we need to update the salary of the employee named 'Alice' to 52000, we can use the following SQL statement:
sqlUPDATE employees SET salary = 52000 WHERE name = 'Alice';
This statement locates the row in the employees table where the name column matches 'Alice' and updates the salary column to 52000.
If we need to adjust salaries for all employees, such as increasing all salaries by 10%, we can omit the WHERE clause as follows:
sqlUPDATE employees SET salary = salary * 1.10;
This statement updates the salary column for all rows in the employees table to 1.10 times the original value.
In summary, using the UPDATE statement for data modification is highly flexible, and with an appropriate WHERE clause, you can precisely control which rows are updated. In practical applications, it is crucial to write appropriate UPDATE statements based on specific data requirements and business needs.