Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

DELETE πŸ“

Learning Goals

By the end of this section you will:

  • know how to delete records from a database

  • understand that relational databases require a specific deletion order

  • know how to delete data that is contained in mulitple tables.

The DELETE statement is used to delete existing records in a table.

Β 

Go to the W3schools Tutorial on the DELETE Statement and complete their exercises.

DELETE orderΒΆ

When deleting data that is stored in multiple tables, the order that entires are deleted is important. You cannot delete an entry where it’s primary key is used as a foreign keys in another table, ie. for the one-to-many cardinality, it is on the one side. Therefore, you need to start with the entry that is not associated with a foreign key.

Let’s look at the Movies database as an example.

movie erd

Say we wanted to delete Mel Gibson from the director database.

The steps that need to be taken areΒΆ

  1. Delete any records involving Mel Gibson movies from the movies_onhire table

delete_example_step_1.sql
DELETE FROM movies_onhire
WHERE movienumber IN (
	SELECT movienumb
	FROM movie
	WHERE dirnumb IN (
		SELECT dirnumb
		FROM director
		WHERE dirname = "Gibson, Mel"
		)	
	)
  1. Delete any movies from the movies table that have Mel Gibson as the director

delete_example_step_2.sql
DELETE FROM movie
WHERE dirnumb IN (
	SELECT dirnumb
	FROM director
	WHERE dirname = "Gibson, Mel"
	)
  1. Finally delete Mel Gibson from the director table

delete_example_step_3.sql
DELETE FROM director
WHERE dirname = 'Gibson, Mel'