So far, we’ve learned how to: - insert data - read data - update data Now let’s take a look at deleting data from a table. Deleting rows in PostgreSQL is actually very simpl
MSMuhammad SufiyanSoftware Engineer · 4d ago
Backend Engineering HubT-
So far, we’ve learned how to:
insert data
read data
update data
Now let’s take a look at deleting data from a table.
Deleting rows in PostgreSQL is actually very simple, but it’s also something you need to be very careful with.
Basic DELETE Syntax
The basic syntax for deleting rows looks like this:
delete from table_name
where condition;
delete from → tells PostgreSQL we want to remove data
table_name → the table we are deleting from
where → decides which rows should be deleted
Example: Deleting a Single City
Let’s say we want to delete Tokyo from our cities table.
delete from cities
where name = 'Tokyo';
What PostgreSQL does internally:
1. Looks at all rows in cities 2. Finds rows where name is Tokyo 3. Deletes those rows
In our case, only one row matches, so only that row gets deleted.
Very Important Rule About WHERE
The WHERE clause works exactly the same way as it does in UPDATE.
That means:
If your WHERE condition matches one row → one row is deleted
If it matches multiple rows → multiple rows are deleted
Dangerous Example (Be Careful)
Consider this query:
delete from cities
where name != 'Tokyo';
Let’s think about what this does.
It finds all rows where the name is not Tokyo
That includes:
Delhi
Shanghai
Sao Paulo
All of those rows will be deleted in one go.
This is why you must always be very precise with your WHERE clause when using DELETE.
Always Double-Check Before Deleting
A good habit is to first run a SELECT with the same WHERE condition.
Example:
select * from cities
where name = 'Tokyo';
If this returns exactly the row you expect, then you can safely run the DELETE.
Verifying the Delete
After deleting Tokyo, we can check the table again:
select * from cities;
You’ll see that Tokyo is no longer present in the result.
Adding the Row Back (INSERT Again)
Since we still want Tokyo for future examples, let’s insert it back.