SQL Tutorial
In SQL, the DELETE
statement is used to remove one or more records from a table.
Here is the basic syntax for DELETE
:
DELETE FROM table_name WHERE condition;
You replace table_name
with the name of the table you want to delete data from, and condition
with a condition that must be met for a record to be deleted.
For example, consider the following Students
table:
ID | Name | Age |
---|---|---|
1 | John Doe | 18 |
2 | Jane Doe | 20 |
3 | Mike Smith | 22 |
If you wanted to delete the record for 'John Doe', you would write:
DELETE FROM Students WHERE Name = 'John Doe';
After running this statement, the 'John Doe' record would be removed from the Students
table.
IMPORTANT: If you omit the WHERE
clause in a DELETE
statement, all records in the table will be deleted! Always make sure you include a WHERE
clause that specifies exactly which records you want to delete to prevent unintentional data loss.
Additionally, remember that DELETE
operations can often be rolled back (undone) if you're using transactions, while TRUNCATE
operations often cannot be. This is another reason to be careful with DELETE
.
Always remember to back up your data before performing DELETE
operations, especially if you're new to SQL or working with important data.
As always, consult the specific SQL dialect documentation for further details and to understand the nuances of the DELETE
operation.
Deleting Data from a Table in SQL:
DELETE FROM TableName WHERE Condition;
Using WHERE Clause in SQL DELETE:
DELETE FROM Employees WHERE Salary < 50000;
Deleting All Rows in a Table with SQL DELETE:
DELETE FROM TableName;
Deleting Specific Rows Based on Conditions:
DELETE FROM Orders WHERE OrderDate < '2023-01-01' AND Status = 'Cancelled';
Deleting Data from Multiple Tables in SQL:
DELETE Orders, OrderItems FROM Orders INNER JOIN OrderItems ON Orders.OrderID = OrderItems.OrderID WHERE Orders.CustomerID = 101;
SQL DELETE with JOIN Operations:
DELETE Employees FROM Employees INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID WHERE Departments.DepartmentName = 'ClosedDepartment';
Undoing or Rolling Back a DELETE Statement:
BEGIN TRANSACTION; DELETE FROM TableName WHERE Condition; -- ROLLBACK; -- Uncomment to rollback changes -- COMMIT; -- Uncomment to commit changes
Triggers and DELETE Operations in SQL:
CREATE TRIGGER ExampleTrigger ON TableName AFTER DELETE AS BEGIN -- Trigger logic here END;