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 oupdatesdbo.orders(aliased aso).- Rows in
dbo.orderswithout a matchingdbo.customersrow or outside theWHEREfilter 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
- Preview first with
SELECT: SwapUPDATE o SET ...for aSELECTshowing old and new values using the exact sameFROM,JOIN, andWHEREclauses. - Test inside a transaction: Run within
BEGIN TRAN, inspect@and sample output, then runCOMMIT TRAN(orROLLBACK TRANto undo). - Watch for multiple matches on the right side: If
JOINmatches 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.
