DELETE Operation
The DELETE statement is used to remove existing records from a SQL Server table.
When a record is no longer required, the DELETE statement can be used to remove it from the table. We can delete a single record or multiple records based on a condition.
What is DELETE?
The DELETE statement removes one or more existing rows from a table.
The WHERE clause is normally used to specify which records should be deleted.
DELETE Syntax
DELETE FROM table_name
WHERE condition;
Example Table
We will use the following Students table for the examples.
| StudentId | StudentName | Age | City |
|---|---|---|---|
| 101 | Rahul | 22 | Pune |
| 102 | Priya | 23 | Mumbai |
| 103 | Amit | 21 | Nashik |
| 104 | Neha | 22 | Pune |
Delete a Single Record
Suppose we want to remove the student whose StudentId is 104.
DELETE FROM Students
WHERE StudentId = 104;
Only the record with StudentId 104 will be removed.
Output
After executing the DELETE statement, the record with StudentId 104 is removed from the table.
| StudentId | StudentName | Age | City |
|---|---|---|---|
| 101 | Rahul | 22 | Pune |
| 102 | Priya | 23 | Mumbai |
| 103 | Amit | 21 | Nashik |
DELETE Using a Condition
We can delete multiple records when they satisfy a particular condition.
DELETE FROM Students
WHERE City = 'Mumbai';
This statement deletes all students whose City is Mumbai.
DELETE Using a Numeric Condition
Numeric columns can also be used in the WHERE condition.
DELETE FROM Students
WHERE Age < 22;
This removes all students whose age is less than 22.
DELETE Without WHERE
If the WHERE clause is omitted, the DELETE statement removes all rows from the table.
DELETE FROM Students;
Warning
The above statement deletes all records from the Students table. The table structure itself remains.
DELETE vs DROP
| DELETE | DROP |
|---|---|
| Removes rows from a table. | Removes the database object itself. |
| Table structure remains. | Table structure is removed. |
| Can use WHERE to remove selected rows. | Removes the complete table. |
Practical Example
Suppose a student permanently leaves an institute and their record needs to be removed from the Students table.
DELETE FROM Students
WHERE StudentId = 103;
The record belonging to StudentId 103 will be removed.
Important Points
- DELETE is used to remove existing records.
- WHERE is used to identify the records to delete.
- Multiple records can be deleted using a condition.
- Without WHERE, all rows can be deleted.
- DELETE removes rows but does not remove the table structure.
- Always verify the WHERE condition before executing DELETE.
Summary
In this section, we learned how the DELETE statement removes records from a SQL Server table. We covered deleting a single record, deleting multiple records using conditions, and the importance of using the WHERE clause.