PostgreSQL UPDATE Statement
If we need to update data in a PostgreSQL database, we can use the UPDATE statement.
Syntax
The following is the general SQL syntax for the UPDATE statement to modify data:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
- We can update one or multiple fields simultaneously.
- We can specify any condition in the WHERE clause.
Example
Create a COMPANY table (download COMPANY SQL file), with the following data content:
tutorialprodb# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
The following example updates the salary field for the record with id 3 in the COMPANY table:
tutorialprodb=# UPDATE COMPANY SET SALARY = 15000 WHERE ID = 3;
The result is as follows:
id | name | age | address | salary
----+-------+-----+------------+--------
1 | Paul | 32 | California | 20000
2 | Allen | 25 | Texas | 15000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall | 45000
7 | James | 24 | Houston | 10000
3 | Teddy | 23 | Norway | 15000
As seen from the result, the salary field value for the record with id 3 in the COMPANY table has been modified.
The following example updates both the salary and address fields simultaneously:
tutorialprodb=# UPDATE COMPANY SET ADDRESS = 'Texas', SALARY=20000;
The result is as follows:
id | name | age | address | salary
----+-------+-----+---------+--------
1 | Paul | 32 | Texas | 20000
2 | Allen | 25 | Texas | 20000
4 | Mark | 25 | Texas | 20000
5 | David | 27 | Texas | 20000
6 | Kim | 22 | Texas | 20000
7 | James | 24 | Texas | 20000
3 | Teddy | 23 | Texas | 20000
(7 rows)