DELETE: Remove Data

The DELETE statement removes rows from a table.
You can delete one row, many rows or all rows.


Syntax

DELETE FROM table_name
WHERE condition;

Important: Always use a WHERE clause, unless you really want to delete every row.


Example 1: Delete One Employee

DELETE FROM employees
WHERE id = 1;

Output:

DELETE 1

This deletes the employee with id = 1. psql answers DELETE 1.


Example 2: Delete All Employees in the HR Department

DELETE FROM employees
WHERE department = 'HR';

SELECT COUNT(*) FROM employees;

Output:

DELETE 1
 count 
-------
    18
(1 row)

Alice was already deleted, so only one HR employee was left (Anna). 18 employees remain.


Common Mistake: Forgetting the WHERE Clause

DELETE FROM employees;

Mistake: This deletes every employee in the table. PostgreSQL does not ask you to confirm.

Tip: Before a big delete, run a SELECT with the same WHERE condition. Check that it shows only the rows you want to delete.

In the exercise, delete all the employees in one department.