SQL workshop: DELETE statement

Photo by Sam Pak on Unsplash

SQL workshop: DELETE statement

The DELETE statement in SQL is used to remove rows from a table based on a certain condition.

Syntax:

DELETE FROM table_name WHERE condition;

Important Points:

  1. Safety First: Always backup your data before performing DELETE operations, especially on production data.

  2. Use WHERE Clause Carefully: Without the WHERE clause, all rows in the table will be deleted!

  3. Performance Consideration: If you are deleting many rows, it may be more efficient to create a new table with only the rows you want to keep, then rename the table.

Example: To delete all employees with the first name 'John' from an employees table:

DELETE FROM employees WHERE first_name = 'John';

Workshop Exercise:

Setup:

Let's assume you have a table named students with the following data:

student_idnameagegrade
1Alice18A
2Bob19B
3Charlie20C
4David21D

Exercise Tasks:

  1. Basic Deletion:

    • Delete the record of the student with the name "Charlie".

    • After this operation, confirm that "Charlie" is no longer in the table.

  2. Condition Deletion:

    • Delete all students who have a grade less than 'C'.

    • Confirm that only students with grades 'A' and 'B' remain in the table.

  3. Full Deletion (CAUTION!):

    • Delete all records from the students table.

    • Confirm that the table is now empty.

Solutions:

  1. Basic Deletion:

     DELETE FROM students WHERE name = 'Charlie';
    
  2. Condition Deletion:

     DELETE FROM students WHERE grade > 'B';
    
  3. Full Deletion:

     DELETE FROM students;
    

After each task, participants can use the SELECT statement to view the table's contents and confirm their results:

SELECT * FROM students;

This exercise should give a practical understanding of how the DELETE statement works and the importance of using it with caution.

References

  1. SQL DELETE Statement