🐘 PostgreSQL Tutorial

DELETE FROM in PostgreSQL: Removing Rows Safely

Learn how to delete rows in PostgreSQL with DELETE FROM, why the WHERE clause is critical, deleting based on another table, and using RETURNING and TRUNCATE.

DELETE FROM in PostgreSQL

DELETE FROM removes rows from a table.

Basic Syntax

DELETE FROM table_name WHERE condition;

Example

DELETE FROM employees WHERE id = 5;

Just like UPDATE, omitting WHERE deletes every row in the table:

DELETE FROM employees;
-- removes ALL rows — the table itself still exists, just empty

If you genuinely need to empty a large table, TRUNCATE TABLE employees; does the same thing far faster (see the DROP vs TRUNCATE lesson).

Deleting Based on Another Table

DELETE FROM orders o
USING customers c
WHERE o.customer_id = c.id
AND c.is_banned = true;

RETURNING the Deleted Rows

DELETE FROM employees
WHERE department = 'Support'
RETURNING id, name;

Common Errors & Troubleshooting

  • Forgetting WHERE and deleting every row — the same trap as UPDATE; run the equivalent SELECT first to confirm which rows match before deleting.
  • ERROR: update or delete on table "customers" violates foreign key constraint — you tried to delete a row that other tables still reference; delete/reassign the dependent rows first, or set ON DELETE CASCADE/SET NULL on the foreign key if that's the intended behavior (see the Constraints lesson).
  • DELETE FROM orders o USING customers c WHERE ... deleting more than expected — double-check the join condition in the USING/WHERE clause is selective enough; a loose join condition can match (and delete) far more rows than intended.

Key Takeaways

  • DELETE FROM table; with no WHERE removes every row — always confirm the condition first.
  • For emptying an entire large table, TRUNCATE is faster than an unconditional DELETE.
  • RETURNING lets you see exactly which rows were deleted, in the same statement.