The Cross-Table Delete in MySQL

08/06/2021

Contents

In this article, you will learn about the cross-table delete in MySQL.

The cross-table delete in MySQL

The Cross-Table Delete operation in MySQL allows you to delete data from one table based on data from another table. This operation is useful when you have related data across multiple tables and you need to delete specific data from one table based on the data in another table.

Here’s how to perform a Cross-Table Delete in MySQL:

Identify the related tables

The first step is to identify the tables that are related to each other. You need to know which table contains the data that needs to be deleted, and which table contains the data that will be used to identify the rows to delete.

For example, let’s say we have two tables: “customers” and “orders”. The “customers” table contains a list of customers, and the “orders” table contains a list of orders that were placed by those customers. We want to delete all the orders for customers who live in a specific city.

Write the DELETE statement

Next, you need to write the DELETE statement. The syntax for a Cross-Table Delete is as follows:

DELETE t1
FROM table1 t1
JOIN table2 t2
ON t1.column = t2.column
WHERE t2.column = 'value';

In this syntax, “t1” is the table that you want to delete data from, and “t2” is the table that you’re using to identify the rows to delete. The “JOIN” keyword specifies the relationship between the two tables, and the “ON” keyword specifies the columns to join on. The “WHERE” clause specifies the criteria for selecting the rows to delete.

Using our example, the DELETE statement would look like this:

DELETE o
FROM orders o
JOIN customers c
ON o.customer_id = c.customer_id
WHERE c.city = 'New York';

In this example, we’re deleting rows from the “orders” table (“o”), where the “customer_id” column in the “orders” table matches the “customer_id” column in the “customers” table (“c”), and the “city” column in the “customers” table is “New York”.

Execute the DELETE statement

Once you’ve written the DELETE statement, you can execute it to delete the rows from the table. It’s always a good idea to test your DELETE statement on a small dataset before running it on a large dataset to avoid accidentally deleting the wrong data.