SQL

UPDATE with JOIN

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Update one table using values from another. Syntax varies by database — PostgreSQL uses `FROM`, MySQL puts the join in the `UPDATE` clause.
SQL
Raw
-- PostgreSQL — UPDATE ... FROM
UPDATE users u
SET    total_spent = s.total
FROM   (SELECT user_id, SUM(amount) AS total
        FROM   orders
        WHERE  paid_at IS NOT NULL
        GROUP  BY user_id) s
WHERE  u.id = s.user_id;

-- MySQL — UPDATE table1 JOIN table2
UPDATE users u
JOIN  (SELECT user_id, SUM(amount) AS total
       FROM   orders
       WHERE  paid_at IS NOT NULL
       GROUP  BY user_id) s
   ON s.user_id = u.id
SET u.total_spent = s.total;

-- SQL Server / Oracle (using MERGE — see separate snippet) or with a CTE
WITH s AS (SELECT user_id, SUM(amount) AS total FROM orders GROUP BY user_id)
UPDATE u SET total_spent = s.total FROM users u JOIN s ON s.user_id = u.id;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.