MySQL DELETE lets you delete entries from a table. You can use the command to remove one or all rows from the table.
What is MySQL DELETE?
MySQL works with tables and helps you to structure and store your data. To make sure that the database management system and stored entries are always up to date, data must be deleted from time to time. The command to use for this is MySQL DELETE. This function lets you specify exactly which data record should be deleted as well as add a note.
MySQL DELETE syntax
DELETE FROM table WHERE condition;
“FROM” tells the system from which table the record should be deleted. With “WHERE” you specify which condition a record must fulfill to be removed. If you omit the “WHERE” condition, the entire row is deleted.
MySQL DELETE example
How exactly MySQL DELETE works is best explained with a practical example. For this, we’ll imagine a company with a customer directory. This is stored in a table called “Customers”.
If we want to delete the customer “Jones”, you can use the MySQL DELETE command. The following is entered:
DELETE FROM Customers WHERE Name = "Jones";
The row will then be deleted from the table.
Delete all rows in MySQL DELETE
As mentioned above, you can also use the MySQL DELETE command to delete all rows from a table, but don’t want to delete the table itself. The command matching the above example looks like this:
DELETE FROM Customers;
This removes all entries while the table and its structure remain intact.
MySQL DELETE LIMIT
The addition “LIMIT” limits the number of rows to be deleted with MySQL DELETE. To do this, you first tell the system to sort the entries. The basic syntax looks like this:
DELETE FROM table ORDER BY: condition LIMIT: number;
For an example like the customer list above, you could use the MySQL DELETE command with the “LIMIT” addition like this:
DELETE FROM Customers ORDER BY Name LIMIT 2;
In this case, the system sorts all customers alphabetically by the first letter of their last names and then deletes the first two.
An alternative use of MySQL DELETE with “LIMIT” looks like this:
DELETE FROM Customers WHERE Country = “United States” ORDER BY Name LIMIT 2;
In this case, all customers from the United States would be sorted alphabetically and the first two entries would be deleted.