PostgreSQL UPDATE Join
Summary: in this tutorial, you will learn how to use the PostgreSQL UPDATE
join syntax to update data in a table based on values in another table.
Introduction to the PostgreSQL UPDATE join syntax
Sometimes, you need to update data in a table based on values in another table. In this case, you can use the PostgreSQL UPDATE
join.
Here’s the basic syntax of the UPDATE
join statement:
To join a table (table1) with another table (table2) in the UPDATE
statement, you specify the joined table (table2) in the FROM
clause and provide the join condition in the WHERE
clause. The FROM
clause must appear immediately after the SET
clause.
For each row of the table table1
, the UPDATE
statement examines every row of the table table2
.
If the values in the c2
column of table table1
equals the values in the c2
column of table table2
, the UPDATE
statement updates the value in the c1
column of the table table1
the new value (new_value
).
PostgreSQL UPDATE JOIN example
Let’s take a look at an example to understand how the PostgreSQL UPDATE
join works. We will use the following database tables for the demonstration:
First, create a new table called product_segment
that stores the product segments such as grand luxury, luxury, and mass.
The product_segment
table has the discount
column that stores the discount percentage based on a specific segment. For example, products with the grand luxury segment have 5%
discount while luxury and mass products have 6%
and 10%
discounts respectively.
Second, create another table named product
that stores the product data. The product
table has the foreign key column segment_id
that links to the id
of the segment
table.
Third, suppose you have to calculate the net price of every product based on the discount of the product segment. To do this, you can apply the UPDATE
join statement as follows:
You can utilize the table aliases to make the query shorter like this:
This statement joins the product
table to the product_segment
table. If there is a match in both tables, it gets a discount from the product_segment
table, calculates the net price based on the following formula, and updates the net_price
column.
The following SELECT
statement retrieves the data of the product
table to verify the update:
The output indicates that the net_price
column has been updated with the correct values.
Summary
- Use the PostgreSQL
UPDATE
join statement to update data in a table based on values in another table.