Database Management
- How to Add an Index
- How to Create a Table
- How to Delete a Table
- How to Rename a Table
- How to Truncate a Table
- How to Duplicate a Table
- How to Add a Column
- How to Remove a Column
- How to Change a Column Name
- How to Set a Column with Default Value
- How to Remove a Default Value to a Column
- How to Add a Not Null Constraint
- How to Remove a Not Null Constraint
- How to Drop an Index
- How to Create a View
- How to Drop a View
- How to Alter Sequence
Dates and Times
Analysis
- How to Use Coalesce
- How to Calculate Percentiles
- How to Get the First Row per Group
- How to Avoid Gaps in Data
- How to Do Type Casting
- How to Write a Common Table Expression
- How to Import a CSV
- How to Compare Two Values When One is Null
- How to Write a Case Statement
- How to Query a JSON Column
- How to Have Multiple Counts
- How to Calculate Cumulative Sum-Running Total
How to Delete in MySQL
Learn how to safely and efficiently delete records in MySQL using the DELETE
statement, with practical examples and essential best practices.
Introduction
Deleting data from a MySQL database is a common task for developers and database administrators. The DELETE
statement allows you to remove one or multiple rows from a table. However, you must use it with caution to avoid accidentally removing important data.
Basic Syntax
DELETE FROM table_name WHERE condition;
Example:
DELETE FROM customers WHERE id = 5;
This command deletes the customer with ID 5 from the customers
table.
Delete All Rows
If you omit the WHERE
clause, all rows will be deleted:
DELETE FROM customers;
Warning: This will empty the entire table. Always double-check before running it.
Using LIMIT
To delete a limited number of rows:
DELETE FROM customers ORDER BY created_at DESC LIMIT 10;
This deletes the 10 most recent customers.
Delete with JOIN
You can also delete rows based on related data in another table:
DELETE c FROM customers c
JOIN orders o ON c.id = o.customer_id
WHERE o.status = 'cancelled';
This removes customers who only have cancelled orders.
Best Practices
- Always use a
WHERE
clause to avoid deleting all rows by mistake. - Test your
WHERE
condition with aSELECT
query first. - Consider creating a backup before running mass delete operations.
- Use transactions (
START TRANSACTION
,COMMIT
,ROLLBACK
) when making critical changes.
Example with Transaction
START TRANSACTION;
DELETE FROM customers WHERE last_login < '2022-01-01';
COMMIT;
If anything goes wrong, you can use ROLLBACK;
before COMMIT
to cancel the delete.
Conclusion
The DELETE
statement is a powerful tool in MySQL, but it comes with great responsibility. Always validate your queries, use transactions when appropriate, and make sure you have backups for critical data. With these best practices, you can manage your data confidently and safely.