PostgreSQL DELETE

PostgreSQL DELETE Statement (Beginner → Advanced)
In PostgreSQL DELETE statement is used to remove rows (records) from a table.
It is a DML command and is transaction-safe, meaning it can be rolled back.
What is DELETE in PostgreSQL?
DELETEremoves one or more rows from a table based on a condition.
- Without
WHERE, all rows are deleted (table structure remains).
Basic DELETE with WHERE (Most Important)
- Deletes only the row with
id = 5 - Safe and recommended usage
Delete Multiple Rows
- Deletes all students who failed
Delete All Rows from a Table
- Removes all rows
- Slower than
TRUNCATE Can be rolled back
DELETE with RETURNING (PostgreSQL Special)
PostgreSQL allows you to see deleted rows.
- Shows deleted rows
- Very useful for auditing & debugging
DELETE Using a Subquery
- Deletes based on another table’s data
DELETE with USING (JOIN Delete)
- PostgreSQL equivalent of
DELETE JOIN - Powerful and commonly used
DELETE with LIMIT (Not Supported)
Correct PostgreSQL Way:
DELETE and Transactions
or
- PostgreSQL fully supports rollback for
DELETE
DELETE vs TRUNCATE vs DROP (Very Important)
| Feature | DELETE | TRUNCATE | DROP |
|---|---|---|---|
| Removes rows | Yes | Yes | No |
| Removes table | No | No | Yes |
| WHERE allowed | Yes | No | No |
| Rollback | Yes | No | No |
| Speed | Slower | Faster | Fastest |
- Use
DELETEwhen conditions or rollback are required
Performance Tips
Always use
WHEREwith indexed columnsAvoid deleting large datasets at once
Use batch deletes for big tables
Prefer
TRUNCATEfor full cleanup
Common Mistakes
- Forgetting
WHEREclause - Using
DELETEinstead ofTRUNCATE ExpectingLIMITto work directly- Not using transactions in production
Interview Questions (Must Prepare)
How does
DELETEwork in PostgreSQL?What is
RETURNINGin PostgreSQL?Difference between
DELETEandTRUNCATECan
DELETEbe rolled back?How to delete rows using another table?
Why PostgreSQL does not support
DELETE LIMIT?
Real-Life Use Cases
Removing inactive users
Cleaning old logs
GDPR data deletion
Fixing incorrect records
Maintenance jobs
Summary
DELETEremoves rows, not the table- Use
WHEREto avoid full deletion - PostgreSQL supports
RETURNING Fully transactional (rollback supported)- Use
USINGfor join-based deletes - Critical for safe database operations & interviews
