How do you perform an UPDATE statement using a JOIN in SQL Server (T-SQL)? | A1Lab@HumairaM to SQLEnglish • 2 days ago

How do you perform an UPDATE statement using a JOIN in SQL Server (T-SQL)?

message-square
0

In SQL Server (T-SQL), you update rows based on data from another table by specifying the target alias or table name in the UPDATE clause and joining tables in the FROM clause (UPDATE target_alias SET ... FROM dbo.target_table AS target_alias INNER JOIN dbo.source_table AS s ON ...). Always join on a key that maps cleanly to each target row—or aggregate first in a CTE/derived table—so you avoid non-deterministic overwrites and unintended row changes.


1. Standard UPDATE ... FROM ... JOIN Syntax

Use a clear alias in UPDATE <alias> and match it in FROM <schema>.<table_name> AS <alias> so the target table is explicit.

UPDATE o
SET
    o.discount_pct = c.tier_discount_pct,
    o.updated_at   = SYSUTCDATETIME()
FROM dbo.orders AS o
INNER JOIN dbo.customers AS c
    ON o.customer_id = c.customer_id
WHERE o.status = 'PENDING'
  AND c.is_active = 1;
  • UPDATE o updates dbo.orders (aliased as o).
  • Rows in dbo.orders without a matching dbo.customers row or outside the WHERE filter are left unchanged.

2. Updating from Aggregated Source Data (CTE)

If the joined table contains multiple rows per target key (such as line items per order), roll up the values first in a Common Table Expression (CTE) or subquery so each target row receives one deterministic value.

WITH order_totals AS (
    SELECT
        order_id,
        SUM(quantity * unit_price) AS calculated_total
    FROM dbo.order_items
    GROUP BY order_id
)
UPDATE o
SET
    o.total_amount = ot.calculated_total,
    o.updated_at   = SYSUTCDATETIME()
FROM dbo.orders AS o
INNER JOIN order_totals AS ot
    ON o.order_id = ot.order_id
WHERE o.status = 'DRAFT';
  • Pre-aggregating prevents ambiguity when multiple child rows match one parent row.

3. Using LEFT JOIN to Handle Missing Matches or Defaults

When a target row might or might not have a matching row in the joined table, use a LEFT JOIN and check for NULL or apply COALESCE().

UPDATE c
SET c.has_orders = CASE
    WHEN o.customer_id IS NOT NULL THEN 1
    ELSE 0
END
FROM dbo.customers AS c
LEFT JOIN (
    SELECT DISTINCT customer_id
    FROM dbo.orders
) AS o
    ON c.customer_id = o.customer_id;

4. Safe Execution Workflow in T-SQL

  1. Preview first with SELECT: Swap UPDATE o SET ... for a SELECT showing old and new values using the exact same FROM, JOIN, and WHERE clauses.
  2. Test inside a transaction: Run within BEGIN TRAN, inspect @@ROWCOUNT and sample output, then run COMMIT TRAN (or ROLLBACK TRAN to undo).
  3. Watch for multiple matches on the right side: If JOIN matches one target row to multiple source rows with different values, SQL Server updates the target row using whichever joined row is processed last—verify uniqueness on the join key first.