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;
Advertisement728 x 90
Common Errors & Troubleshooting
- Forgetting
WHEREand deleting every row — the same trap asUPDATE; run the equivalentSELECTfirst 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 setON DELETE CASCADE/SET NULLon 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 theUSING/WHEREclause is selective enough; a loose join condition can match (and delete) far more rows than intended.
Key Takeaways
DELETE FROM table;with noWHEREremoves every row — always confirm the condition first.- For emptying an entire large table,
TRUNCATEis faster than an unconditionalDELETE. RETURNINGlets you see exactly which rows were deleted, in the same statement.
Advertisement320 x 100