Dofactory.com
Dofactory.com
Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

SQL UPDATE with JOIN

A SQL UPDATE statement can include JOIN operations.

An UPDATE can contain zero, one, or multiple JOIN operations.

The UPDATE affects records that satisfy the JOIN conditions.

UPDATE JOIN

Example

#

Increase the unit price by 10% for all products that have been sold before.

UPDATE P
   SET P.UnitPrice = P.UnitPrice * 1.1
  FROM Product P
  JOIN OrderItem I ON P.Id = I.ProductId

P and I are table aliases.

Result:  77 records updated

Syntax

JOIN syntax.

UPDATE table-name1
   SET column-name1 = value1, 
       column-name2 = value2, ...
  FROM table-name1 
  JOIN table-name2 ON column-name3 = column-name4
 WHERE condition

INNER JOIN syntax.

UPDATE table-name1
   SET column-name1 = value1, 
       column-name2 = value2, ...
  FROM table-name1 
 INNER JOIN table-name2 ON column-name3 = column-name4
 WHERE condition

JOIN is the same as INNER JOIN; the INNER keyword is optional.
JOIN, or INNER JOIN, is the most commonly used type of JOIN operation.


More Examples

UPDATE with LEFT JOIN

PRODUCT
Id
ProductName
SupplierId
UnitPrice
Package
IsDiscontinued
ORDERITEM
Id
OrderId
ProductId
UnitPrice
Quantity
Problem: Discontinue products that have not sold.
UPDATE P
   SET IsDiscontinued = 1
  FROM Product P
  LEFT JOIN OrderItem I ON P.Id = I.ProductId
 WHERE I.Id IS NULL

This UPDATE uses a LEFT JOIN operation.

Result:  1 record updated.

UPDATE with 3 JOINs

Problem: For customer Paul Henriot change the unit price to $25 for Queso Calibres in their order.
PRODUCT
Id
ProductName
SupplierId
UnitPrice
Package
IsDiscontinued
ORDERITEM
Id
OrderId
ProductId
UnitPrice
Quantity
ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount

UPDATE I
   SET I.UnitPrice = 25
  FROM Customer C
  JOIN [Order] O ON O.CustomerId = C.Id
  JOIN OrderItem I ON O.Id = I.OrderId 
  JOIN Product P ON P.Id = I.ProductId
 WHERE C.FirstName = 'Paul' AND C.LastName = 'Henriot'
   AND P.ProductName = 'Queso Cabrales'

This UPDATE performs 3 JOINs with 4 tables. C, O, I, and P are table aliases.

Result:  1 record updated

You may also like



Last updated on Dec 21, 2023

Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.