The DELETE statement in SQL Server is used to remove rows from a table based on a specified condition.


Syntax:

DELETE FROM table_name
WHERE condition;
  • Explanation:
    • table_name: The table from which rows are to be deleted.
    • WHERE: Specifies the condition to identify which rows to delete (mandatory to avoid deleting all rows).

Example:

  • Delete a specific row:
DELETE FROM employees
WHERE id = 1;
  • Delete multiple rows based on a condition:
DELETE FROM employees
WHERE age > 60;
  • Delete All data
DELETE FROM employees

اتكلمنا عن الموضوع دا قبل كدا في الـ Truncate vs Delete


Key Points:

  1. WHERE clause is critical to limit which rows are deleted. Without it, all rows in the table will be deleted.
  2. DELETE is logged in the transaction log, allowing rollback in case of errors.
  3. If there are foreign key constraints, DELETE may fail if the rows are referenced by another table.

Difference between DELETE and TRUNCATE:

  • DELETE: Can delete specific rows, can be rolled back, and does not reset IDENTITY values.
  • Truncate Table: Deletes all rows quickly, cannot be rolled back (unless inside a transaction), and resets IDENTITY values.