login

SQL DELETE Statement

SQL DELETE statement allows you to delete one or more rows from an existing database table. The SQL DELETE statement syntax is simple as follows :

	DELETE FROM [table_name_or_view_name]
	WHERE [conditions]

You specify table after DELETE FROM clause and your conditions in WHERE clause. The result is all rows or records which meets the conditions in where clause will be deleted. If you want to delete all records in a database table just simply ignore the WHERE condition. Here is the syntax:

	DELETE FROM [table_name_or_view_name]

So you get the table with empty data and remember that table itself still exists, only records in the table was deleted.

Here is an example of deleting all employees which have salary less than 2000$

DELETE FROM employees  
WHERE salary < 200

If the database server support transaction you should use it to operate delete operation to avoid losing data which can be occurred.

If you try to delete record(s) from a table which is constrained by a foreign key you can get error message from the database server. You can also set the cascade delete in the constraints of tables todelete all records in the many table when record in one table deleted (one-to-many relationship of tables). In the real world programming, you should develop your own strategy to face up to this problem. There are two common strategies in application which you need to delete records from table

  1. First you delete all child records which are associated with the record you are deleting without confirmation. This strategy is worth if all child records in child tables are nonsense to end-user, for examples some log information in log table...
  2. Otherwise you have or must to ask end-user to delete all child records before deleting the intended records. You can use SQL SELECT statement to get child records from child tables. There is a good strategy is you can create your own table to store the relationships of them for deleting operations later in the future.
Read On