Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MySQL DELETE Statement

MySQL DELETE Statement

You can use the DELETE FROM command to delete records from a MySQL table.

You can execute this command at the mysql> command prompt or in a PHP script.

Syntax

The following is the general syntax for the DELETE statement to delete data from a MySQL table:



DELETE FROM table_name

WHERE condition;

Parameter Description:

More notes:

The WHERE clause is very useful when you want to delete specific records from a table.

Example

The following examples demonstrate how to use the DELETE statement.

  1. Delete rows that meet the condition:


DELETE FROM students

WHERE graduation_year = 2021;

The above SQL statement deletes all records of students whose graduation_year is 2021 from the students table.

  1. Delete all rows:


DELETE FROM orders;

The above SQL statement deletes all records from the orders table, but the table structure remains unchanged.

  1. Delete rows that meet the condition using a subquery:


DELETE FROM customers

WHERE customer_id IN (

    SELECT customer_id

    FROM orders

    WHERE order_date < '2023-01-01'

);

The above SQL statement uses a subquery to delete the customers corresponding to orders placed before '2023-01-01' in the orders table.

Note: When using the DELETE statement, make sure you provide sufficient conditions to ensure that only the rows you want to delete are removed. If you do not provide a WHERE clause, all rows in the table will be deleted, which may lead to unpredictable results.


Deleting Data from the Command Line

Here we will use a WHERE clause in the DELETE command to delete selected data from the MySQL table runoob_tbl.

Example

The following example will delete the record in the runoob_tbl table where runoob_id is 3:

DELETE statement:

mysql

use

RUNOOB

;

Database

changed

mysql

DELETE

FROM

runoob_tbl

WHERE

runoob_id

=

3

;

Query

OK

,

1

row

affected

(

0.23

sec

)


Deleting Data with a PHP Script

PHP uses the mysqli_query() function to execute SQL statements. You can use the DELETE command with or without a WHERE clause.

This function has the same effect as executing SQL commands at the mysql> command prompt.

Example

The following PHP example will delete the record in the runoob_tbl table where runoob_id is 3:

MySQL DELETE Clause Test: