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
How to Join to First Row in SQL Server
Joining the first row in SQL Server can be a common requirement in various scenarios, such as when we need to retrieve specific data associated with the first occurrence of a particular group or when you want to fetch additional details related to the first record in a result set. In this article, W
4 min read
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 Select Row With Max Value in SQL Server
In SQL Server, retrieving rows that contain the maximum value for a specific column for each distinct value in another column can be a common and challenging task. This process is done by identifying the maximum value for each group and then selecting the corresponding rows. In this article, we'll e
6 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 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
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
How to Delete a File using R
In this article, we will discuss how to delete a file in R Programming Language. Directory in use: Method 1: Using file.remove() This is the simplest approach to delete a file as in this approach the user just needs to call the file.remove() function which is a bases function of the R programming la
2 min read
How to Use the IN Operator With a SubQuery?
The IN Operator in SQL allows to specifies multiple values in WHERE clause, it can help you to easily test if an expression matches any value in the list of values. The use of IN Operator reduces the need for multiple OR conditions in statements like SELECT, INSERT, UPDATE, and DELETE. Sub Queries:T
2 min read