Deleting Table Rows Using DELETE

Introduction

The DELETE statement in SQL allows you to remove rows from a table. Whether you are cleaning up data or enforcing business rules, learning how to use this statement effectively is crucial. In this guide, you will learn how to:

The DELETE Statement

The basic syntax of the DELETE statement is:

DELETE FROM table_name
WHERE condition;
      

Key points to remember:

Example Table

Let’s revisit the puppies table for practice:

name age_yrs breed weight_lbs microchipped
Cooper1Miniature Schnauzer181
Indie0.5Yorkshire Terrier131
Kota0.7Australian Shepherd260
Zoe0.8Korean Jindo321
Charley1.5Basset Hound250
Ladybird0.6Labradoodle201
Callie0.9Corgi160
Jaxson0.4Beagle191
Leinni1Miniature Schnauzer251
Max1.6German Shepherd650

Deleting Specific Rows

To delete rows based on a condition, use the WHERE clause. For example, to remove all puppies that are not microchipped (microchipped = 0):

DELETE FROM puppies
WHERE microchipped = 0;
      

After running this statement, verify the results using:

SELECT * FROM puppies;
      

The remaining rows will be:

name age_yrs breed weight_lbs microchipped
Cooper1Miniature Schnauzer181
Indie0.5Yorkshire Terrier131
Zoe0.8Korean Jindo321
Ladybird0.6Labradoodle201
Jaxson0.4Beagle191
Leinni1Miniature Schnauzer251

Understanding the WHERE Clause

The WHERE clause in a DELETE statement functions similarly to its use in SELECT statements. It identifies rows based on conditions such as:

Example: To delete puppies weighing more than 30 lbs:

DELETE FROM puppies
WHERE weight_lbs > 30;
      

Precautions When Using DELETE

The DELETE statement is powerful but potentially destructive. Here are best practices to follow:

What You Learned

Mastering the DELETE statement allows you to maintain and clean your database efficiently. Use it carefully and wisely to ensure data integrity.