How to Delete using INNER JOIN with SQL Server?
Last Updated :
24 Sep, 2024
In SQL Server, we can use INNER JOIN
within a DELETE
statement to remove data from one table based on matching records in another table. This method is useful when we need to delete records from a target table that have corresponding rows in another table.
Understanding DELETE with INNER JOIN
Understanding DELETE with INNER JOIN in SQL Server enables users to remove records from one table based on matching conditions in another table. This method ensures that only relevant rows are deleted and maintains data integrity.
By identifying the target table in the `DELETE` statement and using `INNER JOIN`, you can effectively manage relationships between tables and ensure that deletions are accurate.
Syntax for DELETE
using INNER JOIN
in SQL Server
DELETE target_table
FROM target_table
INNER JOIN joined_table ON target_table.column = joined_table.column
WHERE <condition>;
Setting up Environment
To understand DELETE
using INNER JOIN
in SQL Server, we will create 2 tables, insert data, and then write queries to delete rows based on matching conditions from another table.
-- Creating the 'orders' table
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE
);
-- Creating the 'customers' table
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(100)
);
-- Inserting data into the 'orders' table
INSERT INTO orders (order_id, customer_id, order_date)
VALUES (1, 1, '2023-09-01'),
(2, 2, '2023-09-02'),
(3, 3, '2023-09-03');
-- Inserting data into the 'customers' table
INSERT INTO customers (customer_id, customer_name)
VALUES (1, 'John Doe'),
(2, 'Alice Johnson'),
(3, 'Michael Brown');
Example of How to Use DELETE with INNER JOIN
in SQL Server
Example 1: Deleting Orders for Specific Customers Using INNER JOIN
Let's create a table called orders and customer and on these table, we will delete records from the orders
table where there is a matching customer in the customers
table
-- Step 1: Creating the 'orders' table
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE
);
-- Step 2: Creating the 'customers' table
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(100)
);
-- Step 3: Inserting data into the 'orders' table
INSERT INTO orders (order_id, customer_id, order_date)
VALUES
(1, 1, '2023-09-01'),
(2, 2, '2023-09-02'),
(3, 3, '2023-09-03');
-- Step 4: Inserting data into the 'customers' table
INSERT INTO customers (customer_id, customer_name)
VALUES
(1, 'John Doe'),
(2, 'Alice Johnson'),
(3, 'Michael Brown');
-- Step 5: Deleting orders for 'John Doe'
DELETE orders
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id
WHERE customers.customer_name = 'John Doe';
-- Step 6: Check remaining data in 'orders' table after delete
SELECT * FROM orders;
Output:
order_id | customer_id | order_date |
---|
2 | 2 | 2023-09-02 |
3 | 3 | 2023-09-03 |
Explanation: This query deletes the record from the orders
table where the customer name is 'John Doe' in the customers
table. After running the query, only the orders for 'Alice Johnson' and 'Michael Brown' remain.
Example 2: Deleting All Orders for Customers Who No Longer Exist
In this example, we will delete all orders where there is no matching customer record in the customers
table
-- Step 1: Creating the 'orders' table
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE
);
-- Step 2: Creating the 'customers' table
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(100)
);
-- Step 3: Inserting data into the 'orders' table
INSERT INTO orders (order_id, customer_id, order_date)
VALUES
(1, 1, '2023-09-01'),
(2, 2, '2023-09-02'),
(3, 3, '2023-09-03');
-- Step 4: Inserting data into the 'customers' table
INSERT INTO customers (customer_id, customer_name)
VALUES
(1, 'John Doe'),
(2, 'Alice Johnson'),
(3, 'Michael Brown');
-- Step 5: Deleting orders where there is no matching customer (This won't delete any records in our current setup)
DELETE orders
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id
WHERE customers.customer_id IS NULL;
-- Step 6: Check remaining data in 'orders' table (No change expected)
SELECT * FROM orders;
Output:
order_id | customer_id | order_date |
---|
1 | 1 | 2023-09-01 |
2 | 2 | 2023-09-02 |
3 | 3 | 2023-09-03 |
Explanation: In this example, we attempt to delete orders where there are no matching customer records in the customers
table. Since all customers exist in the customers
table, no orders are deleted and the table remains unchanged.
Conclusion
The use of DELETE
with INNER JOIN
in SQL Server offers a powerful method for managing related data across multiple tables. By using this technique, users can efficiently remove records that meet specific criteria, such as deleting orders associated with a customer. By understanding the above examples both the deletion of orders for specific customers and the attempt to remove orders for non-existent customers, highlighting the importance of maintaining accurate records in a relational database.
Similar Reads
INNER JOIN ON vs WHERE clause in SQL Server
In SQL Server, joining tables and filtering data are essential for retrieving meaningful information. The INNER JOIN operation is used to combine rows from multiple tables based on a matching condition, while the WHERE clause allows for further filtering of results. In this article, we will PL/SQL S
7 min read
Delete Views in SQL Server
In the area of relational databases, SQL Server is one of the most powerful and popular systems. It is flexible to make possible the development of complex data structures and their manipulation. SQL Server offers a crucial tool for managing data which is Delete Views. They allow users to delete row
4 min read
How to Declare a Variable in SQL Server?
In SQL Server, variables play a critical role in the dynamic execution of SQL scripts and procedures. Variables allow you to store and manipulate data temporarily within the scope of a batch or procedure. By using the DECLARE statement, you can create variables with specific data types, which can th
6 min read
How to Perform Batch Updates in SQL Server
The Update statement is a SQL keyword to update data in the database. We can update all the rows in the database or some values with the help of conditions. The update is a SQL keyword, and it falls under Data Manipulation Language (DML), as the name suggests it is used to manipulate the data. Updat
5 min read
How to Remove Times from Dates in SQL Server
In SQL Server, there are Date and DateTime data types to store Date and Time values. There can be situations when only the date value needs to be displayed or to do date calculations for date add, date difference functions, and between two dates from datetime values. So, to remove the Time part from
4 min read
How to Update a Column in a Table in SQL Server
In the database management area, updating columns in a table is a normal query and it is important software that ensures the accuracy and integrity of data. Whether we are making spelling corrections, editing or altering existing information, or being attentive to changing requirements, carrying out
4 min read
Update Date Field in SQL Server
The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using the UPDATE statements as per our requirement. With this article, we will learn how to Update the Date Field in SQL Server. In this article, we w
2 min read
INNER JOIN ON vs WHERE clause in MySQL
When working with MySQL queries that involve multiple tables, understanding how to effectively use INNER JOIN ON versus the WHERE clause can significantly impact query performance and clarity. These two SQL constructs serve distinct purposes in combining data from different tables based on specific
5 min read
How Inner Join works in LINQ to SQL
LINQ (Language Integrated Query) in C# provides a powerful way to query data from various data sources, including databases. In LINQ to SQL, which is specifically designed for working with relational databases, an inner join is a common operation used to combine records from two tables based on a sp
3 min read
When Should We Use CROSS APPLY Over INNER JOIN?
In SQL Server, both INNER JOIN and CROSS APPLY are used to combine data from multiple tables, but they serve different purposes and have distinct use cases. INNER JOIN is typically used to match rows between two tables based on a related column, returning only the rows where a match exists in both t
4 min read