In MySQL, The DELETE statement is used to remove one or more records from a table.
It's an essential part of database management, cleanup of unwanted records and efficiency of the database.
DELETE FROM tableName WHERE condition;
tableName: The name of the table from which we want to delete records.
WHERE: Specifies the condition that must be satisfied for the deletion to occur. If we omit the WHERE clause, all records in the table will be deleted.
condition: indicates the criteria that specify which records should be deleted. If we opt out condition from the query, all records in the table will be deleted unintentionally, which can be dangerous and is generally not recommended.
Removing Obsolete Data: When data becomes outdated or no longer relevant, such as expired coupon.
Data Cleanup: frequently cleaning up test data or data inserted incorrectly.
Archiving Data: Before archiving records to another storage medium, they are deleted from the primary database to save space.
Backup Data: Before performing a DELETE operation, especially when there is a large set of data, it is advisable to back up the table or database.
In the below example, we have applied conditions in `WHERE` clause for ex:- "product_code = `1001`" to filter the record from the table.
DELETE FROM products WHERE product_code = 1001;
The above command will filter out the record from the `products` table and delete the single record from the `products` table where `product_code` is equal to 1001.
In the below example, we have applied the condition to delete selective types of records from the `products` table where `category` is equal to `Electronic` in the `WHERE` clause.
DELETE products WHERE category = 'Electronic';
To Delete all records from the table, we can use the following syntax.
DELETE FROM tableName;
The below command will `DELETE` all records from the `products` table.
DELETE FROM products;
Be cautious while using the `DELETE` statement, especially when opting out of the `WHERE` clause, as it can delete all records from Table unintentionally.