MySQL DELETE statement to remove data from one ore more database tables.
To remove data from a table, you use the MySQL
DELETE
statement. The MySQL DELETE
statement allows you to remove records from not only one table but also multiple tables using a single DELETE
statement.MySQL delete from one table
To remove data from a single table, you use the following
DELETE
statement:
Followed the
DELETE FROM
clause is the table name that you want to delete records.
The
WHERE
clause specifies which rows you want to delete. If a record meets the WHERE
condition, it is deleted permanently from the table. If you omit the WHERE
clause, all records in the table are deleted.
The
DELETE
statement returns the number of rows deleted specified by the ROW_COUNT()
function.
Notice that the
ROW_COUNT()
function returns the number of rows inserted, updated or deleted by the last INSERT, UPDATE or DELETE
statementMySQL delete from a table examples
Suppose you want to remove employees whose
officeNumber
is 4, you use the DELETE
statement with the WHERE
clause as the following query:
To delete all employee records from the
employees
table, you use the DELETE
statement without theWHERE
clause as follows:
All employee records in the
employees
table were deleted.MySQL delete from multiple tables
To delete records from multiple tables, you use one of the following
DELETE
statements:
Let’s examine each statement in greater detail:
- Both
DELETE
statements delete records from multiple tables i.e.,table_1
,table_2
,… specified after theDELETE
keyword. - The first
DELETE
statement uses theFROM
clause while the second one use theUSING
clause. - The
WHERE
clause is used to determine which record to be deleted. - Both statements return the number of rows deleted from the multiple tables.
MySQL delete from multiple tables example
Suppose one office is closed and you want to remove all employee records in the
employees
table associated with that office and also the office itself in the offices
table, you can use the second form of the MySQL DELETE
statement
The following query removes the office record with the code is 1 in the
offices
table and also all employee records associated with the office 1 in the employees
table:
You can verify the changes by using the following SELECT statements to query data from both
employees
table and offices
table.
You can achieve the same effect by using the second form of the MySQL
DELETE
statement as follows:
1
2
3
4
|
DELETE FROM employees, offices
USING employees, offices
WHERE employees.officeCode = offices.officeCode AND
offices.officeCode = 1
|
0 comments:
Post a Comment