![]() |
VOOZH | about |
The MySQL DELETE statement is used to remove one or more existing records from a table. It helps in managing and cleaning data by deleting unwanted rows.
Syntax
DELETE FROM table_name
WHERE condition; Note: Be careful when using the DELETE statement in MySQL. Always use a DELETE statement with a WHERE clause.
Letβs look at some examples of the MySQL DELETE statement to understand its working and also cover different use cases of DELETE statement. First, we will create a demo table on which the DELETE statement will be applied:
This example deletes specific rows based on given conditions using the WHERE clause. It ensures only matching records are removed from the table.
Query:
DELETE FROM Students
WHERE Department = 'IT';
SELECT * FROM Students;
Output:
This example deletes all rows from the table by not using the WHERE clause. It is useful for clearing complete table data.
Query:
DELETE FROM Students;Output:
The DELETE statement with LIMIT allows you to restrict the number of rows deleted from a table. It is useful when you want to remove only a specific number of records.
Consider the Marks table below for the example:
Query:
DELETE FROM Marks
WHERE marks <= 50
ORDER BY marks ASC
LIMIT 2;
SELECT * FROM Marks;Output:
The DELETE statement with JOIN allows deleting rows from one or more tables based on matching conditions between them. It is useful when related data exists across multiple tables.
Consider the Customers and Orders table below for the example:
Query:
DELETE Customers, Orders FROM Customers INNER JOIN Orders ON Customers.id=Orders.customer_id WHERE Customers.id=156; SELECT * FROM Customers;
SELECT * FROM Orders;
Output:
Note:
- If foreign key constraints exist, ensure child rows are deleted first or use ON DELETE CASCADE to avoid errors.
- If only one table is specified after DELETE, rows are removed only from that table.
- Be cautious when using DELETE with JOIN, as it can affect multiple tables at once.