Using Subqueries in DELETE

Using MySQLi Subqueries in DELETE
Subqueries are a fundamental component of SQL, enabling more complex and refined data manipulation. MySQLi (MySQL Improved) offers robust support for subqueries, allowing users to perform sophisticated operations efficiently.
This article focuses on using subqueries in the DELETE statement, a crucial aspect of database management.

Understanding Subqueries

A subquery, also known as an inner query or nested query, is a query within another SQL query. Subqueries can be used to filter data, perform calculations, or determine conditions in the outer query. They are typically enclosed in parentheses and can be placed in various SQL clauses, such as SELECT, INSERT, UPDATE, and DELETE. Subqueries can be categorized into three types:
  1. Single-row subqueries: These return a single row and a single column.
  2. Multiple-row subqueries: These return multiple rows but typically a single column.
  3. Multiple-column subqueries: These return multiple rows and multiple columns.
In the context of DELETE statements, subqueries are often used to specify the rows to be deleted based on data from other tables or the same table.

Using Subqueries in DELETE Statements

Basic Syntax

The basic syntax for a DELETE statement using a subquery is:
				
					DELETE FROM table1
WHERE column1 = (SELECT value FROM table2 WHERE condition);

				
			
Here, the WHERE clause contains a subquery that retrieves the value from another table (table2) based on a specified condition.

Practical Examples

Let’s explore some practical examples to understand how subqueries in DELETE statements work.

Example 1: Deleting Rows with a Single-row Subquery

Consider two tables: employees and departments.
  • employees table:
    • employee_id
    • first_name
    • last_name
    • department_id
    • hire_date
  • departments table:
    • department_id
    • department_name
    • location_id
Suppose you want to delete all employees who work in a specific department. You can achieve this using a subquery in the DELETE statement.
				
					DELETE FROM employees
WHERE department_id = (SELECT department_id FROM departments WHERE department_name = 'Sales');

				
			
In this example, the subquery (SELECT department_id FROM departments WHERE department_name = ‘Sales’) fetches the department ID for the ‘Sales’ department. The DELETE statement then removes all employees belonging to this department.

Example 2: Deleting Rows with a Multiple-row Subquery

Let’s say you want to delete all employees who work in departments located in a specific city. For this, you can use a multiple-row subquery.
				
					DELETE FROM employees
WHERE department_id IN (SELECT department_id FROM departments WHERE location_id = 3);

				
			
Here, the subquery (SELECT department_id FROM departments WHERE location_id = 3) retrieves the IDs of all departments in the specified location. The DELETE statement then removes all employees working in those departments.

Example 3: Deleting with a Correlated Subquery

A correlated subquery is a subquery that references columns from the outer query. This can be particularly useful when you need to delete rows based on a complex condition involving another table. Suppose you have an orders table and a customers table, and you want to delete orders placed by customers who have not made any purchases in the last year.
  • orders table:
    • order_id
    • customer_id
    • order_date
    • order_amount
  • customers table:
    • customer_id
    • customer_name
    • email
				
					DELETE FROM orders
WHERE customer_id IN (
    SELECT customer_id FROM customers
    WHERE customer_id NOT IN (
        SELECT customer_id FROM orders
        WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
    )
);

				
			
In this example, the inner subquery (SELECT customer_id FROM orders WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)) retrieves the IDs of customers who have made purchases in the last year. The outer subquery (SELECT customer_id FROM customers WHERE customer_id NOT IN (…)) identifies customers who are not in this list. Finally, the DELETE statement removes orders placed by these inactive customers.

Code Implementation using MySQLi in PHP

To implement these examples using MySQLi in PHP, follow the steps below:
  1. Establish a Database Connection
				
					<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

				
			
  1. Execute a DELETE Statement with a Subquery

Example 1: Single-row Subquery

				
					<?php
$department_name = 'Sales';

$sql = "DELETE FROM employees
        WHERE department_id = (SELECT department_id FROM departments WHERE department_name = ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $department_name);

if ($stmt->execute()) {
    echo "Records deleted successfully";
} else {
    echo "Error deleting records: " . $conn->error;
}

$stmt->close();
$conn->close();
?>

				
			

Example 2: Multiple-row Subquery

				
					<?php
$location_id = 3;

$sql = "DELETE FROM employees
        WHERE department_id IN (SELECT department_id FROM departments WHERE location_id = ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $location_id);

if ($stmt->execute()) {
    echo "Records deleted successfully";
} else {
    echo "Error deleting records: " . $conn->error;
}

$stmt->close();
$conn->close();
?>

				
			

Example 3: Correlated Subquery

				
					<?php
$sql = "DELETE FROM orders
        WHERE customer_id IN (
            SELECT customer_id FROM customers
            WHERE customer_id NOT IN (
                SELECT customer_id FROM orders
                WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
            )
        )";

if ($conn->query($sql) === TRUE) {
    echo "Records deleted successfully";
} else {
    echo "Error deleting records: " . $conn->error;
}

$conn->close();
?>

				
			

Best Practices

When using subqueries in DELETE statements, consider the following best practices:
  1. Indexing: Ensure relevant columns are indexed to improve the performance of subqueries.
  2. Testing: Test subqueries separately to verify their correctness before integrating them into DELETE statements.
  3. Performance: For large datasets, consider optimizing subqueries or using alternative approaches like joins if subqueries significantly impact performance.
  4. Security: Use prepared statements to prevent SQL injection, especially when incorporating user input into subqueries.

Conclusion

Subqueries in DELETE statements offer a powerful tool for managing and manipulating data in MySQL databases. By understanding and utilizing subqueries effectively, you can perform complex deletions that would otherwise require multiple steps or additional logic. This article has provided a comprehensive overview and practical examples of using subqueries in DELETE statements, along with PHP code snippets for implementation using MySQLi. With these insights, you can enhance your database operations and improve the efficiency and maintainability of your SQL queries.
Scroll to Top