Delete Data (DELETE)
The Delete operation in CRUD is performed using the DELETE statement in SQL. It is used to remove one or more existing records from a table.
Database Preparation
Run this block to set up the Books table.
DROP TABLE IF EXISTS Books;
CREATE TABLE Books (
BookID INTEGER PRIMARY KEY,
Title VARCHAR(255),
Genre VARCHAR(50)
);
INSERT INTO Books (BookID, Title, Genre)
VALUES (1, 'The Hobbit', 'Fantasy'),
(2, '1984', 'Dystopian'),
(3, 'The Fellowship of the Ring', 'Fantasy'),
(4, 'Dune', 'Sci-Fi');
SELECT * FROM Books;
DELETE Statement
The DELETE statement is used to delete existing records in a table.
Syntax
DELETE FROM table_name WHERE condition;
Caution: The WHERE clause is extremely important. If you omit it, all records in the table will be deleted! This action cannot be undone.
Example
Operation: Delete the book with BookID 4 from the Books table.
Books Table Before:
| BookID | Title | Genre |
|---|---|---|
| 3 | The Fellowship of the Ring | Fantasy |
| 4 | Dune | Sci-Fi |
| Query: |
DELETE FROM Books WHERE BookID = 4;
-- Check the result
SELECT * FROM Books;
Books Table After:
| BookID | Title | Genre |
|---|---|---|
| 3 | The Fellowship of the Ring | Fantasy |
Hands-on Exercise
Task: Delete the book with BookID 1 from the Books table.
Your Query:
-- Write your query here
Expected Results:
| BookID | Title | Genre |
|---|---|---|
| 2 | 1984 | Dystopian |
| 3 | The Fellowship of the Ring | Fantasy |
| 4 | Dune | Sci-Fi |