MySQL : DELETE Statement

The DELETE statement in MySQL is used to remove one or more rows from a table. It allows you to specify conditions to determine which rows should be deleted. Here's the basic syntax of the DELETE statement:


DELETE FROM table_name
WHERE condition;

 

  • table_name: The name of the table from which you want to delete rows.
  • WHERE: Optional clause that specifies the conditions that must be met for the deletion to occur. If omitted, all rows in the table will be deleted.

Here's an example to illustrate how to use the DELETE statement:

Let's say we have a table named `employees` with columns `employee_id`, `first_name`, `last_name`, and `department`. We want to delete the record of an employee with `employee_id` 101.


DELETE FROM employees
WHERE employee_id = 101;

This statement will delete the row corresponding to the employee with `employee_id` 101 from the `employees` table.

If you want to delete all rows in a table, you can omit the WHERE clause:


DELETE FROM employees;
 

This statement will delete all rows from the `employees` table, effectively emptying it.

You can also use more complex conditions to delete specific sets of rows. For example, to delete all employees in the 'Sales' department:


DELETE FROM employees
WHERE department = 'Sales';

 

Always exercise caution when using the DELETE statement, as it permanently removes data from your database. Make sure you have appropriate backups or confirm the deletion criteria to avoid accidental data loss.