Reading history

SQL UPDATE and DELETE With JOIN: Changing Rows From Another Table

5 min read 0 views

Learn to update and delete rows using another table in SQL: UPDATE ... FROM, correlated subqueries, EXISTS and NOT EXISTS, RETURNING and safe previews.

A plain UPDATE changes rows using values from the same row. Real tasks often need values from another table: add bonus marks listed in a separate sheet, copy each student’s average into their record, or delete orders from blocked customers. This lesson shows the two ways to do that: UPDATE ... FROM with a join, and correlated subqueries, plus a safe habit for every change you make.

In this lesson you will learn

  • Updating rows with values from another table using UPDATE ... FROM
  • The correlated subquery version that works everywhere
  • Deleting rows that match, or do not match, another table
  • Seeing changed rows with RETURNING
  • Previewing a change before running it

You should know INSERT, UPDATE and DELETE, joins and subqueries.

Updating From Another Table

-- A table of bonus marks to apply, one row per student and course
CREATE TABLE bonus (student_id INTEGER, course_id INTEGER, extra INTEGER);
INSERT INTO bonus VALUES (1, 102, 3), (5, 102, 5), (6, 201, 6);

-- UPDATE ... FROM: join the target table to another table
UPDATE enrollments
SET marks = marks + b.extra
FROM bonus AS b
WHERE enrollments.student_id = b.student_id
  AND enrollments.course_id = b.course_id;

SELECT student_id, course_id, marks
FROM enrollments
WHERE (student_id, course_id) IN (SELECT student_id, course_id FROM bonus);

-- Correlated subquery version: works in almost every database
ALTER TABLE students ADD COLUMN avg_marks REAL;
UPDATE students
SET avg_marks = (SELECT ROUND(AVG(marks), 1)
                 FROM enrollments e
                 WHERE e.student_id = students.id);
SELECT name, avg_marks FROM students ORDER BY id;

Output

+------------+-----------+-------+
| student_id | course_id | marks |
+------------+-----------+-------+
| 1          | 102       | 95    |
| 5          | 102       | 81    |
| 6          | 201       | 70    |
+------------+-----------+-------+
(3 rows)

+--------+-----------+
| name   | avg_marks |
+--------+-----------+
| Nusrat | 91.5      |
| Arif   | 81.0      |
| Tania  | 92.5      |
| Imran  | 72.0      |
| Mitu   | 81.0      |
| Rafi   | 70.0      |
| Sabbir | 85.0      |
| Nadia  | NULL      |
+--------+-----------+
(8 rows)
  • UPDATE enrollments ... FROM bonus joins each enrollment to the bonus table. The WHERE clause is the join condition. Only the three matching rows change: Nusrat’s 92 becomes 95, Mitu’s 76 becomes 81 and Rafi’s 64 becomes 70.
  • In the SET clause, b.extra reads from the joined table, and marks refers to the row being updated.
  • The second update uses a correlated subquery: for each student, the inner query averages that student’s marks (e.student_id = students.id). Nadia has no enrollments, so her average is NULL.
  • Note that Nusrat’s average (91.5) already includes her bonus, because the first update ran before it.

Syntax differs between databases. SQLite and PostgreSQL use UPDATE t SET ... FROM other WHERE .... MySQL writes the join directly: UPDATE enrollments e JOIN bonus b ON ... SET e.marks = e.marks + b.extra. SQL Server uses UPDATE e SET ... FROM enrollments e JOIN bonus b ON .... The correlated subquery form works in all of them.

Deleting With Another Table

-- Delete rows that have a match in another table
CREATE TABLE blocked (customer TEXT);
INSERT INTO blocked VALUES ('Tuhin');

DELETE FROM orders
WHERE EXISTS (SELECT 1 FROM blocked b WHERE b.customer = orders.customer);
SELECT COUNT(*) AS orders_left FROM orders;

-- Delete departments that no student belongs to
DELETE FROM departments
WHERE code NOT IN (SELECT dept FROM students WHERE dept IS NOT NULL);
SELECT code, name FROM departments;

-- Always preview first: same WHERE, but SELECT instead of UPDATE
SELECT id, customer, amount
FROM orders
WHERE status = 'pending' AND amount < 1000;
UPDATE orders SET status = 'cancelled'
WHERE status = 'pending' AND amount < 1000
RETURNING id, customer, status;

Output

+-------------+
| orders_left |
+-------------+
| 7           |
+-------------+
(1 row)

+------+-------------------------+
| code | name                    |
+------+-------------------------+
| CSE  | Computer Science        |
| EEE  | Electrical Engineering  |
| BBA  | Business Administration |
+------+-------------------------+
(3 rows)

+----+----------+--------+
| id | customer | amount |
+----+----------+--------+
| 5  | Rina     | 650    |
+----+----------+--------+
(1 row)

+----+----------+-----------+
| id | customer | status    |
+----+----------+-----------+
| 5  | Rina     | cancelled |
+----+----------+-----------+
(1 row)
  • WHERE EXISTS (...) deletes an order when its customer appears in blocked. Tuhin’s single order is removed, leaving 7.
  • NOT IN (SELECT dept FROM students WHERE dept IS NOT NULL) removes departments with no students; here the ME department goes. The IS NOT NULL filter matters: if the subquery returned a NULL, NOT IN would match nothing at all. NOT EXISTS avoids that trap.
  • Running a SELECT with the same WHERE clause first shows exactly which rows will change. Only then run the UPDATE.
  • RETURNING makes the UPDATE report the rows it changed, which is a quick confirmation. SQLite and PostgreSQL support it; SQL Server has a similar OUTPUT clause.

A Safe Routine for Changes

  1. Write the WHERE clause first, in a SELECT, and check the rows and the count.
  2. Start a transaction with BEGIN.
  3. Run the UPDATE or DELETE, ideally with RETURNING.
  4. Check the result. COMMIT if it is right, ROLLBACK if not.

Common Mistakes

  1. Forgetting the join condition in UPDATE ... FROM. Every target row then matches every bonus row, and the result is unpredictable.
  2. Several matches per row. If the other table has two bonus rows for the same enrollment, only one of them is applied. Aggregate first, for example with SUM(extra) in a subquery.
  3. NOT IN with NULLs silently deleting nothing.
  4. Skipping the preview and changing far more rows than intended.

Practice Exercises

Exercise 1. Give every student in a department housed in “Block A” a CGPA increase of 0.05, using UPDATE ... FROM.

Show answer
UPDATE students
SET cgpa = cgpa + 0.05
FROM departments d
WHERE d.code = students.dept AND d.building = 'Block A';

Exercise 2. Delete enrollments for courses that no longer exist in the courses table, using NOT EXISTS.

Show answer
DELETE FROM enrollments
WHERE NOT EXISTS (SELECT 1 FROM courses c WHERE c.id = enrollments.course_id);

Frequently Asked Questions

Which is faster, UPDATE … FROM or a correlated subquery?

On large tables the join form is often faster, because the database can match the tables once instead of running the subquery for every row. With an index on the matching column, both are usually fine.

Can I update two tables in one statement?

Not in standard SQL or SQLite; one UPDATE changes one table. Run two statements inside one transaction so both succeed or both fail. MySQL is an exception and allows multi-table updates.

Summary

  • UPDATE ... FROM joins another table to supply new values.
  • A correlated subquery does the same job in every database.
  • Use EXISTS and NOT EXISTS to delete rows based on another table.
  • Preview with SELECT, wrap in a transaction, confirm with RETURNING.

Next: Hierarchical Data and Recursive Queries.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *