The MySQL DELETE
statement is used to remove rows from a table. This statement is essential for managing and maintaining data integrity by removing unwanted or obsolete records.
DELETE FROM table_name
WHERE condition;
The DELETE
statement has the following components:
table_name
: The name of the table from which to delete the rows.condition
: The condition that specifies which rows to delete. If no condition is specified, all rows in the table will be deleted.Let's look at some examples of the MySQL DELETE
statement:
USE mydatabase;
This query sets the context to the database named mydatabase
.
Create a table to work with:
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE
);
This query creates a table named employees
with columns for id
, first_name
, last_name
, and email
.
Insert some initial rows into the table:
INSERT INTO employees (first_name, last_name, email)
VALUES ('John', 'Doe', 'john.doe@example.com'),
('Jane', 'Smith', 'jane.smith@example.com');
This query inserts two rows into the employees
table.
Delete a single row from the table:
DELETE FROM employees
WHERE first_name = 'John' AND last_name = 'Doe';
This query deletes the row where the first_name
is 'John' and the last_name
is 'Doe' from the employees
table.
Delete multiple rows from the table:
DELETE FROM employees
WHERE last_name = 'Doe';
This query deletes all rows where the last_name
is 'Doe' from the employees
table.
To verify that the rows have been deleted, you can select all rows from the table:
SELECT *
FROM employees;
This query retrieves all rows from the employees
table. The result will show the remaining rows after the deletions.
The MySQL DELETE
statement is a powerful tool for removing rows from a table. Understanding how to use the DELETE
statement is essential for effective data management and maintenance in MySQL.