SQL Tutorial menu

SQL DELETE

DELETE removes rows from a table.

DELETE Syntax

Example

sql
DELETE FROM table_name
WHERE condition;

The WHERE clause chooses which rows are removed. The table itself and its columns stay.

Delete One Row

Sana Iqbal (id 6) has left the institute:

Example

sql
DELETE FROM students
WHERE id = 6;
Output
1 row deleted.

Example

sql
SELECT id, name FROM students;
idname
1Ali Khan
2Ayesha Siddiqui
3Bilal Ahmed
4Fatima Noor
5Hamza Raza

Delete Several Rows

Any condition works. This removes all courses that are 3 months long:

Example

sql
DELETE FROM courses
WHERE duration_months = 3;
Output
2 rows deleted.
idtitleduration_months
1Web Development6
2Python Programming4

Delete All Rows

Without WHERE, every row is deleted:

Example

sql
DELETE FROM students;

The table still exists, but it is empty. You can still insert new rows into it.

Deleted rows cannot be brought back unless you have a backup or you are inside a transaction you have not committed yet. Run a SELECT with the same WHERE first and check the rows it shows.

DELETE, TRUNCATE and DROP

These three are easy to mix up:

StatementWhat it removesTable still exists?
DELETE FROM students WHERE ...;The matching rowsYes
DELETE FROM students;All rows, one by oneYes
TRUNCATE TABLE students;All rows, very fastYes
DROP TABLE students;The whole table and its dataNo

TRUNCATE is quicker than DELETE on large tables, but it cannot use a WHERE clause. You will learn DROP TABLE in the tables lesson.

Deleting Rows That Other Tables Use

What if you try to delete the Web Development course while Ali and Bilal are still in it? If the tables are linked with a foreign key, the database stops you with an error, so students do not point to a course that no longer exists:

Example

sql
DELETE FROM courses WHERE id = 1;
Output
ERROR: cannot delete or update a parent row: a foreign key constraint fails

The exact wording depends on the database. You must first move or delete the students in that course.

Exercise

Exercise

Which statement removes only the students who live in Lahore?

Learn SQL with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp