Over time, databases can become very large, leading to deteriorating performance. Periodically removing obsolete or inactive records can improve performance and reduce storage requirements by decreasing the number of rows to sort or search through. Reducing database size also frees up disk space that might be needed for other purposes, such as swap space[1].
Caution should be exercised when deleting data. It's a good practice to archive data before deleting it from a production database[3].
Use the DELETE statement to remove rows from a SQL database. The syntax[2] is similar to the SELECT statement, but you do not specify column names since the entire row is deleted. The following DELETE statement will remove all rows from the BookTable table:
DELETE FROM BookTable
This demonstrates how easily an entire table's data can be removed! For a safer, more practical example, consider the book Maintaining Your Moped, which has had poor sales and will no longer be carried by VirtualBookShelf.com. The following diagrams show how the DELETE statement removes only this record from BookTable:
1. Table Data
ItemNo
Title
Author
A500-010
Active Server Pages Black Book
Williams, Barber, N
A200-005
AIM/FAR 1999
Spence
A700-001
Hawaii On $10 a Day
Pincher
A205-001
How To Build a Space Shuttle
O'Really
A200-001
How To Fly a Space Shuttle
O'Really
A200-010
Instrument Flying
Thom
A345-001
Maintaining Your Moped
Jones
A550-001
Mythical Man-Month
Brooks
A540-010
Software Metrics
Fenton
A505-001
UNIX Unleashed
Burk & Horvath
A500-001
Using Visual InterDev 6.0
Smarts
1) BookTable before the deletion.
DELETE FROM BookTable
WHERE Title = 'Maintaining Your Moped'
2) The DELETE statement deletes all rows where the title is Maintaining Your Moped. More complex WHERE clauses can use comparison, logical, and other operators.
2. Table Data
ItemNo
Title
Author
A500-010
Active Server Pages Black Book
Williams, Barber, N
A200-005
AIM/FAR 1999
Spence
A700-001
Hawaii On $10 a Day
Pincher
A205-001
How To Build a Space Shuttle
O'Really
A200-001
How To Fly a Space Shuttle
O'Really
A200-010
Instrument Flying
Thom
A550-001
Mythical Man-Month
Brooks
A540-010
Software Metrics
Fenton
A505-001
UNIX Unleashed
Burk & Horvath
A500-001
Using Visual InterDev 6.0
Smarts
3) BookTable after the DELETE statement executes.
To practice, verify a row exists before deleting it. For example, to check for a test row in the Stores table:
SELECT *
FROM Stores
WHERE StoreCode = 'TEST';
If the row exists, you can safely delete it using a DELETE statement with a similar WHERE clause. The next lesson wraps up this module with a quiz to test your knowledge of basic SQL statements.
[1]swap space: Disk space used by the operating system to temporarily store information removed from main memory.
[2]SQL syntax: Most database actions are performed with SQL statements.
[3]production database: A database used in a live production environment.