Delete with Join MYSQL

Learn via video courses
Topics Covered

Overview

The DELETE with JOIN statement in MySQL is used to delete records from one table and the corresponding records from another table. The matching records or rows in the join statements are dependent on the type of join we apply in our query, such as inner join, outer join, full join, etc. In this tutorial, we'll cover everything about the DELETE with JOIN statement in MySQL, including its introduction, types, and syntax.

Introduction

DELETE with JOIN in MySQL refers to using the MySQL DELETE statement in conjunction with a JOIN operation to delete data from one or more tables. The JOIN operation allows you to combine rows from two or more tables based on a related column between them.

The DELETE with JOIN operation is useful when you need to delete data from one table based on the values in another table.

It's important to note that when using DELETE with JOIN in MySQL, you should be cautious and ensure that you're only deleting the data you intend to delete. It's a good practice to test your query with a SELECT statement first to confirm the correct data is being returned before executing the DELETE statement.

Syntax of Delete with Join

The syntax for Delete with Join in MySQL is as follows:

where:

  • table1 is the name of the table you want to delete data from
  • table2 is the name of the table you want to join with
  • column is the column that both tables share, for the join operation
  • condition is the condition that specifies which rows to delete

Example:

Consider a simple database schema with two tables - customers and orders, where the orders table has a foreign key customer_id that references the id column of the customers table.

Customers Table:

orders Table:

iditemamountcustomer_id
1iPhone Case$19.991
2T-Shirt$29.992
3Shoes$99.991
4Headphones$49.993

Example 1: Delete all orders for the customer with the name "John":

Code:

Output:

orders Table:

iditemamountcustomer_id
2T-Shirt$29.992
4Headphones$49.993

Using INNER JOIN with DELETE

INNER JOIN is used to combine rows from two or more tables based on a related column between them. It returns only the rows that have matching values in both tables. When used with DELETE, INNER JOIN can be used to delete records from one table based on a matching condition in another table.

Consider a simple database schema with two tables - employees and departments, where the employees table has a foreign key dept_id that references the id column of the departments table.

employees Table:

idnamesalarydept_id
1John$500001
2Alice$600002
3Bob$550001

departments Table:

idname
1Marketing
2Sales
3Finance

Example 1: Delete all employees who work in the "Marketing" department.

Code:

Output:

employees Table:

idnamesalarydept_id
2Alice$600002

Example 2: Delete all employees whose salary is less than $55000 and who work in the "Marketing" department.

Code:

Output:

employees Table:

idnamesalarydept_id
2Alice$600002
3Bob$550001

Note that INNER JOIN is used to join the "employees" table with the "departments" table based on the foreign key "dept_id" in "employees" and the primary key "id" in "departments". The condition for deleting rows is specified in the WHERE clause.

Using LEFT JOIN with DELETE

LEFT JOIN is used to return all rows from the left table and matching rows from the right table. If there is no match in the right table, NULL values are returned. When used with DELETE, LEFT JOIN can be used to delete rows from one table based on a non-matching condition in another table.

Consider a simple database schema with two tables - employees and projects, where the employees table has a foreign key project_id that references the id column of the projects table.

employees Table:

idnamesalaryproject_id
1John500001
2Alice600002
3Bob55000NULL

Projects Table:

idname
1Project A
2Project B

Example 1: Delete all employees who are not assigned to any project.

Code:

Output:

employees Table:

idnamesalaryproject_id
1John500001
2Alice600002

Example 2: Delete all employees who work on projects that are not named "Project B".

Code:

Output:

employees Table:

idnamesalaryproject_id
1John500001
3Bob55000NULL

Note that LEFT JOIN is used to join the "employees" table with the "projects" table based on the foreign key "project_id" in "employees" and the primary key "id" in "projects". The condition for deleting rows is specified in the WHERE clause using the IS NULL operator to match rows in Example 1, and using the <> operator to match non-matching rows in Example 2.

Using RIGHT JOIN with DELETE

RIGHT JOIN is used to return all rows from the right table and matching rows from the left table, and if there is no match in the left table, NULL values are returned. When used with DELETE, RIGHT JOIN can be used to delete rows from one table based on a condition in another table.

Consider a simple database schema with two tables - employees and departments, where the employees table has a foreign key dept_id that references the id column of the departments table.

employees Table:

idnamesalarydept_id
1John500001
2Alice600002
3Bob55000NULL

departments Table:

idname
1Marketing
2Sales
3Finance

Example 1: Delete all departments that do not have any employees.

Code:

Output:

departments Table:

idname
1Marketing
2Sales

Example 2: Delete all employees who are not assigned to any department

Code:

Output:

employees Table:

idnamesalarydept_id
1John500001
2Alice600002

Note that RIGHT JOIN is used to join the "employees" table with the "departments" table based on the foreign key "dept_id" in "employees" and the primary key "id" in "departments". The condition for deleting rows is specified in the WHERE clause using the IS NULL operator. In Example 1, the "departments" table is on the right side of the join, while in Example 2, the "employees" table is on the right side of the join.

Combining Multiple Tables with DELETE

In MySQL, it is possible to combine multiple tables with DELETE using JOIN operations, just like with SELECT or UPDATE statements. This allows us to delete rows from multiple tables that match certain conditions at once.

Here's an example using a sample table:

Consider a database schema with three tables - customers, orders, and order_items, where the orders table has a foreign key customer_id that references the id column of customers table, and order_items table has a foreign key order_id that references the id column of orders table.

Customers Table:

orders Table:

idorder_datecustomer_id
12022-01-011
22022-02-012
32022-03-013
42022-04-012
52022-05-011

order_items Table:

idorder_idproduct_namequantity
11Apple2
21Orange5
32Banana3
43Mango1
54Pineapple2
65Watermelon1

Example: Delete all the records from the customer's table, all the orders from the orders table, and all the items in those orders from the order_items table where customer name= "Alice".

Code:

Output:

Customers Table:

orders Table:

idorder_datecustomer_id
12022-01-011
32022-03-013
52022-05-011

order_items Table:

idorder_idproduct_namequantity
11Apple2
21Orange5
43Mango1
65Watermelon1

The above query performs a multi-table delete operation, which deletes records from three tables: customers, orders, and order_items.

It first uses JOIN to link the three tables based on the specified conditions. In this case, it links the customers table with the orders table on the id column of customers and customer_id column of orders, and then links the orders table with the order_items table on the id column of orders and order_id column of order_items.

The WHERE clause specifies the condition for deleting records, which is that the name column of customers must be equal to "Alice". This means that all records related to the customer named Alice, including the customer record itself, all her orders, and all the items in those orders, will be deleted.

Therefore, this query will delete Alice's record from the customers table, all her orders from the orders table, and all the items in those orders from the order_items table.

Using Subqueries with DELETE

In MySQL, it is also possible to use subqueries with DELETE to delete rows that match certain conditions. A subquery is a query nested inside another query and can be used to retrieve data to be used in the DELETE statement.

Here's an example using a sample table:

Consider a database schema with a products table that has columns "id", "name", and "price".

Products Table:

idnameprice
1Apple2.50
2Orange1.50
3Banana0.75
4Mango3.00
5Pineapple4.50
6Watermelon5.00

Example: Delete all products that have a price less than or equal to 2.

Code:

Output:

Products Table:

idnameprice
1Apple2.50
4Mango3.00
5Pineapple4.50
6Watermelon5.00

In this example, we used a subquery inside the DELETE statement to delete all products that have a price less than or equal to 2. The subquery returns a list of product IDs that satisfy the condition, which is used in the WHERE clause of the DELETE statement to delete the corresponding rows from the "products" table.

It is also possible to use subqueries with other JOIN operations, such as INNER JOIN, LEFT JOIN, or RIGHT JOIN, to delete rows from multiple tables that match certain conditions. The syntax for using subqueries with DELETE is similar to that of SELECT, UPDATE, and other SQL statements that use subqueries.

Precautions to be Taken While Using Delete with Join

Using DELETE with JOIN in MySQL can be a powerful tool for manipulating data in databases, but it can also be dangerous if not used correctly. Here are some precautions to be taken when using DELETE with JOIN:

  • Always back up your data: Before performing any DELETE operation, it is important to take a backup of the data to ensure that you can restore it in case of any unintended consequences.
  • Use a WHERE clause: Always use a WHERE clause with the DELETE statement to ensure that you delete only the required rows. If the WHERE clause is not used, all the rows in the joined tables will be deleted.
  • Be aware of the relationships between tables: Be aware of the relationships between tables before performing a DELETE operation, as deleting a row in one table may affect the data in another table.
  • Use transactional processing: Use transactional processing when performing a DELETE operation with JOIN. This ensures that if any error occurs during the DELETE operation, the transaction can be rolled back to its original state.
  • Test in a development environment: Test the DELETE operation with JOIN in a development environment before performing it in a production environment.

Examples of scenarios where DELETE with JOIN should be used with caution:

  • Deleting a large number of rows: If you are deleting a large number of rows, ensure that you have sufficient resources to handle the DELETE operation. In some cases, it may be better to use a batch process to delete rows in smaller chunks.
  • Deleting rows from multiple tables: If you are deleting rows from multiple tables, ensure that you have a good understanding of the relationships between the tables, and the impact that deleting rows from one table will have on the other tables.
  • Using outer joins: When using outer joins, be aware that the result set may contain NULL values, and the DELETE operation may delete more rows than intended.

In summary, using DELETE with JOIN requires careful consideration of the relationships between tables and the impact of deleting rows of other tables. It is important to test the operation in a development environment before performing it in a production environment and to use transactional processing and backups to ensure data integrity.

Conclusion

Here are some key points to keep in mind regarding DELETE with JOIN in MySQL:

  • DELETE with JOIN is a powerful tool for manipulating data in MySQL databases.
  • It allows you to delete data from multiple tables that meet certain criteria.
  • There are different types of JOINs that can be used, including INNER JOIN, LEFT JOIN, and RIGHT JOIN.
  • Always use a WHERE clause to ensure that you delete only the required rows.
  • It is important to take a backup of the data before performing any DELETE operation.
  • Test the DELETE operation in a development environment before performing it in a production environment.
  • Finally, always follow best practices and take precautions to ensure the integrity and safety of your data.

See Also

  • DELETE in MySQL
  • JOINs in MySQL
  • WHERE clause in MySQL