Given a database table, we can delete records within the table or erase the entire table itself. Hence, when using the delete query in SQL one must be very careful.
Let’s look at both implementations of the delete statement.
WHERE
clause;DELETE FROM table_nameWHERE condition_statement;
Using the conditon_statement
one can delete single or multiple records from within the table, depending on the requirement. The condition itself can contain various conditions.
WHERE
condition is not implemented, hence using this implementation one will delete the entire table.DELETE FROM table_name;
Now that we know how to use the DELETE statement, let’s use it in practical examples for a better understanding.
CREATE TABLE pets(pet_name varchar(20),age int,pet_type varchar(20));INSERT INTO pets(pet_name,age,pet_type)VALUES("Doggo", 1, "Dog");INSERT INTO pets(pet_name,age,pet_type)VALUES("Kittiness", 2, "Cat");INSERT INTO pets(pet_name,age,pet_type)VALUES("Pupper", 3, "Dog");INSERT INTO pets(pet_name,age,pet_type)VALUES("Parry", 10, "Bird");INSERT INTO pets(pet_name,age,pet_type)VALUES("Bunny", 2, "Rabbit");INSERT INTO pets(pet_name,age,pet_type)VALUES("Mousey", 5, "Rodent");/*Printing the table*/SELECT *FROM pets;/*Deleting where type is Dog*/DELETE FROM petsWHERE pet_type = "Dog";/*Printing the table*/SELECT "";SELECT *FROM pets;
CREATE TABLE pets(pet_name varchar(20),age int,pet_type varchar(20));INSERT INTO pets(pet_name,age,pet_type)VALUES("Doggo", 1, "Dog");INSERT INTO pets(pet_name,age,pet_type)VALUES("Kittiness", 2, "Cat");INSERT INTO pets(pet_name,age,pet_type)VALUES("Pupper", 3, "Dog");INSERT INTO pets(pet_name,age,pet_type)VALUES("Parry", 10, "Bird");INSERT INTO pets(pet_name,age,pet_type)VALUES("Bunny", 2, "Rabbit");INSERT INTO pets(pet_name,age,pet_type)VALUES("Mousey", 5, "Rodent");/*Printing the table*/SELECT *FROM pets;/*Deleting where type is Bird or age is less than 3*/DELETE FROM petsWHERE pet_type = "Bird" OR age < 3;/*Printing the table*/SELECT "";SELECT *FROM pets;
WHERE
clause is usedCREATE TABLE pets(pet_name varchar(20),age int,pet_type varchar(20));INSERT INTO pets(pet_name,age,pet_type)VALUES("Doggo", 1, "Dog");INSERT INTO pets(pet_name,age,pet_type)VALUES("Kittiness", 2, "Cat");INSERT INTO pets(pet_name,age,pet_type)VALUES("Pupper", 3, "Dog");INSERT INTO pets(pet_name,age,pet_type)VALUES("Parry", 10, "Bird");INSERT INTO pets(pet_name,age,pet_type)VALUES("Bunny", 2, "Rabbit");INSERT INTO pets(pet_name,age,pet_type)VALUES("Mousey", 5, "Rodent");/*Printing the table*/SELECT *FROM pets;SELECT " ";/*Deleting the entire table*/DELETE FROM pets;/*Printing the table*/SELECT *FROM pets;