Practical 4 - Deleting Data - CSU357P - Shoolini U

Practical 4: Daleting Data

4. Deleting Records

The DELETE statement is used to delete records or rows from a table.

4.1. Syntax

To delete records from a table, use the following syntax:


DELETE FROM "tablename"
WHERE "columnname" OPERATOR "value"
[AND|OR "columnname" OPERATOR "value"];

Note: The WHERE clause is optional. If omitted, all records will be deleted.

4.2. Examples

Consider the table employee.

4.2.1. Example 1: Delete all records

DELETE FROM employee;

If you leave off the WHERE clause, all records will be deleted!

4.2.2. Example 2: Delete specific records

DELETE FROM employee
WHERE lastname = 'May';

DELETE FROM employee
WHERE firstname = 'Mike' OR firstname = 'Eric';

4.3. Exercise

Use the SELECT statement to verify your deletions:

  1. Jonie Weber-Williams just quit, remove her record from the table.
  2. It's time for budget cuts. Remove all employees who are making over 70000 dollars.
  3. Create at least two of your own DELETE statements.
  4. Issue a command to delete all records from the table.

4.4. Deleting Records Answers

4.4.1. Answer 1

Jonie Weber-Williams just quit, remove her record from the table:


DELETE FROM myemployees_ts0211
WHERE lastname = 'Weber-Williams';
4.4.2. Answer 2

It's time for budget cuts. Remove all employees who are making over 70000 dollars:


DELETE FROM myemployees_ts0211
WHERE salary > 70000;
4.4.3. Answer 3

Create at least two of your own DELETE statements:


-- Delete employees from the "Sales" department
DELETE FROM myemployees_ts0211
WHERE department = 'Sales';

-- Delete employees hired before the year 2000
DELETE FROM myemployees_ts0211
WHERE hire_date < '2000-01-01';
4.4.4. Answer 4

Delete all records from the table:


DELETE FROM myemployees_ts0211;

4.5. Challenge Questions

Test your understanding with the following questions:

  1. Remove all employees from the "HR" department.
  2. Delete records of employees whose first name starts with 'A'.
  3. Remove employees who have been with the company for more than 20 years.
  4. Delete records of employees who are not assigned to any project.