SQL Tutorial



DELETE QUERY


DELETE Query in SQL

The DELETE statement in SQL is used to remove records from a table. It’s part of the Data Manipulation Language (DML) and allows you to delete one or more rows based on a specified condition.

πŸ“ Basic Syntax

The basic syntax of the DELETE query is as follows:

DELETE FROM table_name
WHERE condition;
  

Explanation: The WHERE clause is crucial in the DELETE statement. It specifies which records should be removed. Without the WHERE clause, all rows in the table will be deleted, which is often not desired.

πŸ’‘ Example 1: Delete a Single Record

Let's assume we have a table called Students with columns StudentID, Name, and Age.

-- Deleting a student with StudentID = 3
DELETE FROM Students
WHERE StudentID = 3;
  

This query deletes the record where the StudentID is 3 from the Students table.

πŸ’‘ Example 2: Delete Multiple Records

You can delete multiple records that match a certain condition:

-- Deleting students older than 25
DELETE FROM Students
WHERE Age > 25;
  

This query deletes all records from the Students table where the Age is greater than 25.

πŸš€ Try It Out!

Imagine you are managing a Books table with columns:

  • BookID: Unique identifier for each book
  • BookTitle: Title of the book
  • Author: Author of the book
  • Price: Price of the book

Your task: Write an SQL query to delete the book with BookID = 5 from the table.

Write the DELETE statement below:

πŸ’‘ What to Remember:

  • WHERE Clause: Always use a WHERE clause to specify which records to delete. Without it, all rows will be removed.
  • Data Integrity: Be careful when deleting data to ensure you’re not losing important information.
  • Backup: Before running a DELETE statement, it’s a good practice to back up your data, especially when deleting large amounts of information.

Conclusion

The DELETE statement is a powerful way to remove data from your tables. Always ensure you are targeting the correct rows using the WHERE clause to avoid accidental data loss.

Quick Tip:

If you are unsure about the rows you are deleting, first run a SELECT query with the same WHERE clause to preview the records you are about to remove.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review