Postgresql Update Table From Another Table

6 min read

Knowing how to execute a postgresql update table from another table operation is an essential skill for database administrators and developers who need to synchronize data across related tables. Whether you are correcting outdated records, importing corrected values from a staging table, or maintaining consistency between operational and reporting tables, PostgreSQL provides a flexible syntax that lets you modify one table using values from another. This guide walks you through the core syntax, practical examples, advanced techniques, and performance considerations so you can update tables confidently and safely.

Real talk — this step gets skipped all the time.

What Does It Mean to Update a PostgreSQL Table from Another Table?

In a relational database, data is often split across multiple tables to reduce redundancy and improve integrity. Even so, there are many situations where information in one table needs to reflect changes made in another. Take this: you might have a customers table that stores current contact details, and a customer_updates table that contains newly verified phone numbers and addresses. Instead of manually editing each row, you can use a single SQL statement to push those changes from the source table into the target table.

This operation is commonly referred to as a PostgreSQL UPDATE from another table, or an UPDATE with a FROM clause. It functions similarly to an UPDATE with a JOIN, allowing you to match rows between two tables and apply changes only where the join condition is true And it works..

The Core Syntax: UPDATE ... FROM

PostgreSQL extends the standard SQL UPDATE statement by allowing a FROM clause immediately after the SET clause. This lets you reference additional tables while updating the target table That's the part that actually makes a difference..

The basic syntax looks like this:

UPDATE target_table
SET column1 = source_table.column1,
    column2 = source_table.column2
FROM source_table
WHERE target_table.join_column = source_table.join_column;

Here is what each part does:

  • target_table: The table you want to modify.
  • SET: Specifies which columns to update and where to pull the new values from.
  • FROM source_table: Introduces the second table that provides the update values.
  • WHERE: Defines the relationship between the target and source tables, usually by matching primary and foreign keys.

Only rows in the target table that satisfy the WHERE condition will be updated. If a target row has no matching row in the source table, it remains unchanged.

A Practical Example

Imagine you manage an e-commerce database. You have a products table with current prices and a price_corrections table with updated pricing information.

products table:

product_id product_name price
101 Wireless Mouse 25.00
102 Mechanical Keyboard 85.00
103 USB-C Hub 40.

price_corrections table:

product_id corrected_price
101 22.50
103 35.00

To update the products table using the price_corrections table, you would run:

UPDATE products
SET price = price_corrections.corrected_price
FROM price_corrections
WHERE products.product_id = price

### Extending the FROM Clause

The `FROM` clause is not limited to a single source table. PostgreSQL permits any of the following:

* **Multiple tables** – you can list as many tables as you need, separating them with additional `JOIN` keywords.  
  ```sql
  UPDATE orders o
  SET total_amount = oi.quantity * oi.unit_price + oi.tax
  FROM order_items oi
  JOIN tax_rates tr ON tr.region = o.shipping_region
  WHERE o.id = oi.order_id
    AND tr.rate_date = CURRENT_DATE;

In this example the orders row is updated using data from order_items and the appropriate tax rate.

  • Sub‑queries – a FROM clause can reference a derived table created by a sub‑select, which is handy when the update logic is too complex for a simple join.

    UPDATE customers c
    SET status = s.new_status
    FROM (
        SELECT customer_id,
               CASE
                   WHEN last_order_date < CURRENT_DATE - INTERVAL '2 years' THEN 'inactive'
                   ELSE 'active'
               END AS new_status
        FROM (
            SELECT customer_id, MAX(order_date) AS last_order_date
            FROM orders
            GROUP BY customer_id
        ) sub
    ) s
    WHERE c.customer_id = s.customer_id;
    
  • CTE (Common Table Expression) references – a CTE can be defined before the UPDATE and then used in the FROM clause, providing readability and the ability to reuse intermediate results Worth keeping that in mind..

    WITH price_adj AS (
        SELECT product_id,
               price * 0.95 AS new_price   -- 5 % discount
        FROM price_updates
        WHERE effective_date = CURRENT_DATE
    )
    UPDATE products p
    SET price = pa.new_price
    FROM price_adj pa
    WHERE p.product_id = pa.product_id;
    

Updating with the RETURNING Clause

When an UPDATE … FROM statement modifies multiple rows, it can be useful to inspect the changes that were made. PostgreSQL allows a RETURNING clause that returns rows from the target table after the update:

UPDATE inventory i
SET stock = s.available_qty
FROM shipments s
WHERE i.product_id = s.product_id
  AND i.warehouse = s.warehouse
RETURNING i.product_id, i.stock, s.available_qty;

The result set can be consumed by an application, logged, or fed into another CTE for further processing Simple, but easy to overlook. Surprisingly effective..

Performance Considerations

  • Indexes – the join condition in the WHERE clause should be supported by an index on the participating columns (typically primary‑key or foreign‑key columns). Without an appropriate index the planner may resort to a sequential scan, which can degrade performance on large tables But it adds up..

  • Planning – PostgreSQL evaluates the entire FROM clause during planning. If the source set is huge, consider materialising it in a temporary table or a CTE to limit the amount of data that needs to be examined.

  • Row‑level triggers – when UPDATE … FROM fires row‑level triggers, the trigger sees the new values that have already been written to the target table. Be aware that any side‑effects (e.g., inserting into audit tables) will happen for each row that satisfies the join condition Most people skip this — try not to..

  • Transaction scope – the statement runs in a single transaction. If you need to update two unrelated tables atomically, wrap both statements in an explicit transaction block, or use a single UPDATE … FROM that touches both tables via a CTE.

Common Pitfalls

  1. Accidentally updating the wrong rows – forgetting to include the join condition (or using an overly broad WHERE) can cause mass updates. Always test the WHERE clause first with a SELECT to verify the rows that will be affected.

  2. Using the same table as both target and source – while PostgreSQL permits a self‑join, it can lead to unintended recursion if the WHERE clause does not correctly restrict the rows. In such cases, a CTE is often clearer Worth keeping that in mind..

  3. NULL handling – if the source column is NULL, the target column will be set to NULL as well. To preserve existing values when the source is missing, incorporate a COALESCE expression:

    
    
   UPDATE products p
   SET price = COALESCE(s.new_price, p.price)
   FROM staged_prices s
   WHERE p.product_id = s.product_id;

This pattern is especially handy when the source table contains only partial updates.

  1. Locking and concurrency – UPDATE … FROM acquires row‑level locks on the target rows for the duration of the transaction. Long‑running updates can block concurrent writers. If you are updating a large fraction of a table, consider batching the operation into smaller chunks (e.g., using a LIMIT in a CTE) to reduce lock contention and keep transaction logs manageable.

  2. Volatile expressions – expressions in the SET clause are evaluated once per target row. If the expression references a volatile function (such as random() or nextval()), the result may differ from what you expect when the same expression appears in the FROM clause. Always test such queries carefully.

Wrapping Up

UPDATE … FROM is one of PostgreSQL’s most powerful tools for keeping related tables in sync. By combining it with CTEs, RETURNING, and careful indexing, you can perform complex multi‑table modifications in a single, atomic statement. The key is to treat the FROM clause as a join: verify the join conditions with a SELECT first, watch out for NULL values, and keep an eye on performance when the source set grows large. With these practices in mind, you can write updates that are both correct and efficient—and avoid the classic mistake of accidentally rewriting an entire table when you meant to touch just a handful of rows Not complicated — just consistent..

New This Week

What's Just Gone Live

Same World Different Angle

Up Next

Thank you for reading about Postgresql Update Table From Another Table. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home