In SQL Server (MS SQL), the DELETE
query is used to remove rows from a table. Here’s a basic overview of how to use it:
Basic Syntax
Examples
-
Delete Specific Rows
Suppose you have a table named
Employees
and you want to delete records for employees who are in the 'Sales' department.DELETE FROM Employees WHERE Department = 'Sales';This command will delete all rows where the
Department
column has the value 'Sales'. -
Delete All Rows
To delete all rows from a table but keep the table structure intact:
DELETE FROM Employees;Be careful with this command, as it removes all data from the table.
-
Delete with Joins
If you want to delete rows based on a condition involving another table, you can use a
JOIN
. For example, if you want to delete employees who belong to departments that are marked as inactive in another table calledDepartments
:DELETE E FROM Employees E INNER JOIN Departments D ON E.DepartmentID = D.DepartmentID WHERE D.Status = 'Inactive';This command deletes rows from
Employees
where the corresponding department inDepartments
has a status of 'Inactive'.
Important Considerations
-
Backup Data: Always ensure that you have a backup of your data before running a
DELETE
query, especially if it will affect a large number of rows. -
Transactions: You can use transactions to ensure that your
DELETE
operation is safe. For example:BEGIN TRANSACTION;
DELETE FROM Employees WHERE Department = 'Sales';
-- If everything looks good, commit the transaction
COMMIT TRANSACTION;
-- If something goes wrong, you can roll back the transaction -- ROLLBACK TRANSACTION; -
Foreign Key Constraints: Be aware of foreign key constraints that might prevent you from deleting rows if other tables depend on the rows you're trying to remove.