![]() |
VOOZH | about |
PL/SQL provides the DELETE statement to remove one or more records from a database table. It helps in maintaining data integrity by removing unwanted or outdated data.
Syntax:
DELETE FROM table_name
WHERE condition;
Key terms:
Firstly, create the employeeDetails table. Then, INSERT INTO is used to add rows with employee_id, name and department.
Query:
CREATE TABLE employeeDetails (
employee_id NUMBER(10) PRIMARY KEY,
name VARCHAR2(10),
department VARCHAR2(20)
);
-- Insert a single row
INSERT INTO employeeDetails (employee_id, name, department)
VALUES (101, 'John Smith', 'HR');
-- Insert another row
INSERT INTO employeeDetails (employee_id, name, department)
VALUES (102, 'Jane Doe', 'IT');
-- Insert a third row
INSERT INTO employeeDetails (employee_id, name, department)
VALUES (103, 'Mike Brown', 'Finance');
-- Insert a fourth row
INSERT INTO employeeDetails (employee_id, name, department)
VALUES (104, 'Lisa Wong', 'HR');
--Insert a fifth row
INSERT INTO employeeDetails (employee_id, name, department)
VALUES (105, 'Alice Grey', 'Marketing');
Output:
Create another table using CREATE TABLE with the required columns.Then, use INSERT INTO to add rows with department and name.
Query:
CREATE TABLE department (
department VARCHAR2(20),
name VARCHAR2(10)
);
--Insert a single row
INSERT INTO department (department, name)
VALUES ('HR', 'John Smith');
--Insert another row
INSERT INTO department (department, name)
VALUES ('Finance', 'Mike Brown');
--Insert third row
INSERT INTO department (department, name)
VALUES ('IT', 'Jane Doe');
Output:
To delete employees from the employeeDetails table whose department is IT, use the DELETE statement with a condition on the department column.
Query:
DELETE FROM employeeDetails
WHERE department = 'IT';
Output:
This example shows how to use DELETE with multiple conditions to remove specific rows from employeeDetails. For example, deleting an employee who works in HR and has employee_id = 101 using the AND operator.
Query:
DELETE FROM employeeDetails
WHERE department = 'HR' AND employee_id = 101;
Output:
The NOT EXISTS clause checks if no rows exist in a subquery. Using DELETE with a subquery helps remove rows based on missing related data. For example, it can delete employees whose departments no longer exist in the department table.
Query:
DELETE FROM employeeDetails e
WHERE NOT EXISTS (
SELECT 1 FROM department d
WHERE d.department = e.department
);
Output: