Deleting Rows: DELETE, TRUNCATE and Removing Duplicates
How to remove rows safely: DELETE with WHERE, foreign keys that block deletes, deleting with subqueries and joins, archiving before deleting, TRUNCATE and how it differs from DELETE, finding and removing duplicate rows with ROW_NUMBER, soft deletes and large batch deletes.
kvi5hnuCode Sprout team member11 min readOn this page
DELETE removes rows from a table. Like UPDATE, it's short to write and easy to get wrong: without a WHERE clause, it removes every row. Unlike an UPDATE, the data is gone, not just changed, so a mistake can only be undone by rolling back the transaction or restoring a backup.
This article covers deleting rows by condition, how foreign keys protect related rows, deleting based on other tables, emptying tables with TRUNCATE, and a task almost every database eventually needs: removing duplicate rows.
The basic DELETE
DELETE FROM table
WHERE condition;
WHERE chooses the rows to remove, exactly as in a SELECT. Rows for which the condition is false or unknown stay. Without WHERE, every row is deleted, but the table itself remains, empty.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Delete the order lines of the cancelled order 105, then the order itself
DELETE FROM order_items WHERE order_id = 105;
DELETE FROM orders WHERE order_id = 105;
-- A WHERE that matches nothing deletes nothing, without an error
DELETE FROM orders WHERE order_id = 999;
SELECT order_id, status FROM orders ORDER BY order_id;
SELECT COUNT(*) AS order_lines FROM order_items;
order_id | status
----------+-----------
101 | shipped
102 | shipped
103 | delivered
104 | pending
106 | shipped
(5 rows)
order_lines
-------------
8
(1 row)
The cancelled order 105 had one order line. The order lines are deleted first, then the order, and the next section explains why that order matters. A DELETE whose WHERE matches nothing, like order_id = 999, isn't an error: it simply deletes 0 rows. If a delete was supposed to remove something, check the row count the database reports.
DELETE removes whole rows. To clear a single value, use UPDATE ... SET column = NULL.
Foreign keys protect related rows
A foreign key guarantees that every reference points to an existing row. Deleting a row that other rows still reference would break that guarantee, so by default the database refuses:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Foreign keys protect referenced rows
DELETE FROM customers WHERE customer_id = 3; -- Chen has an order and referred Farah
DELETE FROM orders WHERE order_id = 104; -- the order still has order lines
-- Delete the children first, then the parent
DELETE FROM order_items WHERE order_id = 104;
DELETE FROM orders WHERE order_id = 104;
SELECT order_id FROM orders ORDER BY order_id;
psql:/workspace/solution.sql:63: ERROR: update or delete on table "customers" violates foreign key constraint "customers_referred_by_fkey" on table "customers"
DETAIL: Key (customer_id)=(3) is still referenced from table "customers".
psql:/workspace/solution.sql:65: ERROR: update or delete on table "orders" violates foreign key constraint "order_items_order_id_fkey" on table "order_items"
DETAIL: Key (order_id)=(104) is still referenced from table "order_items".
order_id
----------
101
102
103
105
106
(5 rows)
- Chen (customer 3) can't be deleted, because Farah's
referred_bypoints to Chen. Chen also has an order, which references Chen as well. - Order 104 can't be deleted while its order lines reference it.
- Deleting the children first, then the parent, works: the order lines of 104, then order 104.
Instead of deleting children by hand, a foreign key can be declared with ON DELETE CASCADE, which deletes the referencing rows automatically, or ON DELETE SET NULL, which clears the reference. Article 53 covers these actions. They're convenient but powerful: one DELETE on a parent can silently remove thousands of rows across several tables.
Deleting based on other tables
The WHERE clause of a DELETE can use subqueries, which makes it possible to delete rows based on related data:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Customers who never ordered and referred nobody: delete them with NOT EXISTS
DELETE FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)
AND NOT EXISTS (SELECT 1 FROM customers r WHERE r.referred_by = c.customer_id);
SELECT customer_id, name FROM customers ORDER BY customer_id;
-- DELETE ... USING (PostgreSQL): delete the order lines of shipped orders
DELETE FROM order_items oi
USING orders o
WHERE o.order_id = oi.order_id
AND o.status = 'shipped';
SELECT order_id, product_id FROM order_items ORDER BY order_id, product_id;
customer_id | name
-------------+------------
1 | Asha Rao
2 | Ben Okafor
3 | Chen Wei
4 | Dana Cruz
(4 rows)
order_id | product_id
----------+------------
103 | 3
103 | 5
103 | 7
104 | 2
105 | 6
(5 rows)
The first statement removes customers who have never ordered and referred no one: two NOT EXISTS conditions (article 16). Eli and Farah are deleted. Removing rows that have no related rows is a common clean-up task, and NOT EXISTS is the safe way to write it. NOT IN with a subquery that can return NULL deletes nothing (article 16 explains why).
The second statement uses PostgreSQL's DELETE ... USING, which joins other tables to the target table, like UPDATE ... FROM. It deletes the order lines of every shipped order. As with UPDATE, the join syntax differs between databases:
-- MySQL and MariaDB: name the table to delete from, then join
DELETE oi
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
WHERE o.status = 'shipped';
-- SQL Server: DELETE alias FROM ... JOIN
DELETE oi
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
WHERE o.status = 'shipped';
-- Portable: a subquery
DELETE FROM order_items
WHERE order_id IN (SELECT order_id FROM orders WHERE status = 'shipped');
The subquery form works everywhere and is usually just as fast. SQLite has no join syntax for DELETE, so it always uses the subquery form. Oracle 23ai added direct joins in DELETE, as it did for UPDATE.
Archiving before deleting
Data that's no longer needed day to day often has to be kept somewhere: old orders, closed accounts, past log entries. The usual pattern is to copy the rows to an archive table with INSERT ... SELECT (article 31) and then delete them, in one transaction, so the rows can't be lost or duplicated if something fails between the two statements:
BEGIN;
INSERT INTO order_archive SELECT * FROM orders WHERE placed_on < DATE '2025-01-01';
DELETE FROM orders WHERE placed_on < DATE '2025-01-01';
COMMIT;
-- If other tables reference these rows, such as order_items, archive and delete those first, in the same transaction
PostgreSQL can do both in a single statement, with a DELETE ... RETURNING inside a CTE that feeds an INSERT (article 34).
TRUNCATE
TRUNCATE removes all rows from a table, much faster than DELETE without WHERE:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
CREATE TABLE import_log (
log_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
message TEXT NOT NULL
);
INSERT INTO import_log (message) VALUES ('started'), ('loaded 500 rows'), ('finished');
-- DELETE removes the rows but the identity keeps counting
DELETE FROM import_log;
INSERT INTO import_log (message) VALUES ('after DELETE');
SELECT * FROM import_log;
-- TRUNCATE ... RESTART IDENTITY empties the table and resets the counter
TRUNCATE import_log RESTART IDENTITY;
INSERT INTO import_log (message) VALUES ('after TRUNCATE');
SELECT * FROM import_log;
-- A table referenced by a foreign key can't be truncated on its own
TRUNCATE products;
log_id | message
--------+--------------
4 | after DELETE
(1 row)
log_id | message
--------+----------------
1 | after TRUNCATE
(1 row)
psql:/workspace/solution.sql:79: ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "order_items" references "products".
HINT: Truncate table "order_items" at the same time, or use TRUNCATE ... CASCADE.
DELETE removes rows one at a time, logs each one and fires any delete triggers. TRUNCATE deallocates the table's storage in one operation, so its speed doesn't depend on the number of rows. The other differences:
DELETE FROM t | TRUNCATE t | |
|---|---|---|
| Rows removed | those matching WHERE (all without it) | always all |
| Speed on large tables | slow: every row is processed and logged | fast: storage is released at once |
| Identity counter | keeps counting | reset by RESTART IDENTITY in PostgreSQL; always reset in MySQL and SQL Server |
| Delete triggers | fire | don't fire |
| Referenced by a foreign key | allowed, if no child rows reference the deleted rows | refused (PostgreSQL and Oracle 12c+ offer CASCADE) |
| Can be rolled back | yes | PostgreSQL and SQL Server: yes. MySQL and Oracle: no, it commits immediately |
In the example, after DELETE the next log entry got ID 4, because the identity counter continued from 3. After TRUNCATE ... RESTART IDENTITY, it started again from 1. TRUNCATE products fails because order_items references it. PostgreSQL's hint suggests TRUNCATE products, order_items or TRUNCATE ... CASCADE, which also empties every table that references it.
Use TRUNCATE for staging tables, test data and scratch tables, where you always want everything gone. Use DELETE for anything selective, anything that should fire triggers, and anything you might need to roll back in MySQL or Oracle. SQLite has no TRUNCATE, but it optimizes DELETE FROM t without WHERE in a similar way.
Removing duplicate rows
Duplicates get into tables that lack a unique constraint: a form submitted twice, an import run twice, or data merged from two systems. Removing them takes three steps: find them, delete all but one copy of each, and prevent new ones.
CREATE TABLE signups (
signup_id INTEGER PRIMARY KEY,
email TEXT NOT NULL,
signed_up DATE NOT NULL
);
INSERT INTO signups VALUES
(1, 'asha@example.com', DATE '2026-04-01'),
(2, 'ben@example.com', DATE '2026-04-02'),
(3, 'asha@example.com', DATE '2026-04-03'),
(4, 'chen@example.com', DATE '2026-04-03'),
(5, 'ben@example.com', DATE '2026-04-05'),
(6, 'asha@example.com', DATE '2026-04-06');
-- 1. Find the duplicates
SELECT email, COUNT(*) AS copies
FROM signups
GROUP BY email
HAVING COUNT(*) > 1
ORDER BY email;
-- 2. Delete every copy except the earliest signup per email
DELETE FROM signups
WHERE signup_id IN (
SELECT signup_id
FROM (SELECT signup_id,
ROW_NUMBER() OVER (PARTITION BY email
ORDER BY signed_up, signup_id) AS rn
FROM signups) AS numbered
WHERE rn > 1
);
SELECT * FROM signups ORDER BY signup_id;
-- 3. Stop it happening again
ALTER TABLE signups ADD CONSTRAINT signups_email_unique UNIQUE (email);
INSERT INTO signups VALUES (7, 'ben@example.com', DATE '2026-04-09');
email | copies
------------------+--------
asha@example.com | 3
ben@example.com | 2
(2 rows)
signup_id | email | signed_up
-----------+------------------+------------
1 | asha@example.com | 2026-04-01
2 | ben@example.com | 2026-04-02
4 | chen@example.com | 2026-04-03
(3 rows)
psql:/workspace/solution.sql:36: ERROR: duplicate key value violates unique constraint "signups_email_unique"
DETAIL: Key (email)=(ben@example.com) already exists.
- Find the duplicates with
GROUP BYandHAVING COUNT(*) > 1(article 19). Asha signed up three times and Ben twice. - Delete all but one copy.
ROW_NUMBER()partitioned byemailnumbers each email's rows, earliest first (article 27). Rows numbered 1 are kept, and the others are deleted by their primary key. The window'sORDER BYdecides which copy survives: here the earliest signup, withsignup_idas a tie-breaker. UseORDER BY signed_up DESCto keep the latest instead. - Prevent new duplicates with a
UNIQUEconstraint onemail. The final insert is rejected. Without the constraint, the clean-up would need repeating forever.

"Duplicate" means whatever your rule says: here, the same email. If rows count as duplicates only when several columns match, partition by all of them: PARTITION BY email, signed_up. Comparing emails case-insensitively needs PARTITION BY LOWER(email) and a unique index on LOWER(email) (article 55).
Other ways to delete duplicates:
-- Keep the lowest ID per email (not in MySQL: it can't read the target table in a subquery)
DELETE FROM signups
WHERE signup_id NOT IN (SELECT MIN(signup_id) FROM signups GROUP BY email);
-- MySQL: a self-join, deleting each row that has a copy with a lower ID
DELETE s1
FROM signups s1
JOIN signups s2 ON s2.email = s1.email AND s2.signup_id < s1.signup_id;
The ROW_NUMBER version also works in MySQL 8, because the window function forces MySQL to build the derived table first.
Duplicates with no key
If the duplicate rows are identical in every column, including any ID, there's nothing in the data to tell them apart for a DELETE. The options are:
- Rebuild the table: copy the distinct rows to a new table with
CREATE TABLE new AS SELECT DISTINCT * FROM old, then replace the old table. Remember to recreate constraints and indexes. - Use a physical row identifier, which each database has under a different name:
ctidin PostgreSQL,ROWIDin Oracle and SQLite. For example, in PostgreSQL:DELETE FROM t a USING t b WHERE a.ctid > b.ctid AND a.col1 = b.col1 AND .... These identifiers can change when rows are updated, so use them only within one statement. - In SQL Server, delete through a CTE:
WITH d AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY ... ORDER BY (SELECT NULL)) AS rn FROM t) DELETE FROM d WHERE rn > 1. SQL Server allows deleting from a CTE that's based on one table.
Then add a primary key.
Soft deletes
Many applications don't physically delete important rows. They mark them as deleted instead, with a column such as deleted_at TIMESTAMP, and filter them out of queries with WHERE deleted_at IS NULL. This soft delete keeps history, allows undoing, and avoids foreign key problems.
Its costs: every query must remember the filter (a view can apply it, article 56), unique constraints must ignore deleted rows (a partial unique index in PostgreSQL and SQLite, or a filtered index in SQL Server), and the table keeps growing. Privacy laws may also require some data to be truly deleted. Use soft deletes where the history has value, and real deletes elsewhere.
Deleting large amounts of data
Deleting millions of rows in one statement holds locks for a long time, generates a lot of log, and, if it fails near the end, takes as long to roll back. Common approaches:
- Delete in batches: delete a limited number of rows at a time, committing after each batch, until none are left. MySQL allows
DELETE ... LIMIT 10000, SQL ServerDELETE TOP (10000). In PostgreSQL, select a batch of keys in a subquery:WHERE id IN (SELECT id FROM t WHERE ... LIMIT 10000). - Keep what's left instead: when deleting most of a table, it's often faster to copy the rows to keep into a new table and swap the tables.
- Partitioning: tables partitioned by date can drop a whole old partition instantly, which is how large log and event tables are usually cleaned up.
In PostgreSQL, deleted rows leave dead space that VACUUM reclaims for reuse (article 61). The table file doesn't shrink on its own.
What's current
- Oracle 23ai added direct joins in
DELETEandUPDATE. - SQLite 3.35 added
RETURNINGtoDELETE. SQLite still has noTRUNCATEstatement. - PostgreSQL 17 made
VACUUMuse much less memory, which helps after large deletes.
Common questions
What's the difference between DELETE, TRUNCATE and DROP TABLE?
DELETE removes chosen rows. TRUNCATE removes all rows quickly. DROP TABLE removes the table itself, structure and all.
Why can't I delete a row?
Most often, a foreign key: other rows reference it. Delete or update the referencing rows first, or define the foreign key with ON DELETE CASCADE or SET NULL.
Can I undo a DELETE?
Only before the transaction commits, with ROLLBACK. After that, restore from a backup. Some databases offer extra recovery tools, such as Oracle's Flashback Query.
Does TRUNCATE reset the identity column?
In MySQL and SQL Server, yes. In PostgreSQL, only with RESTART IDENTITY.
How do I delete duplicates but keep one row?
Number the rows within each group of duplicates with ROW_NUMBER() and delete those numbered above 1. Then add a UNIQUE constraint.
Does deleting rows make the table file smaller?
Not immediately. The space is reused for new rows. Shrinking the file needs a rebuild, such as VACUUM FULL in PostgreSQL or OPTIMIZE TABLE in MySQL.
Summary
DELETE FROM table WHERE conditionremoves the matching rows. WithoutWHERE, it removes them all.- Foreign keys block deleting rows that are still referenced. Delete children first, or use
ON DELETEactions. - Subqueries such as
NOT EXISTS, or the join formsDELETE ... USINGandDELETE ... JOIN, delete rows based on other tables. - Archive with
INSERT ... SELECTandDELETEin one transaction. TRUNCATEempties a table quickly, but can't be selective, doesn't fire delete triggers, and in MySQL and Oracle can't be rolled back.- Remove duplicates by numbering them with
ROW_NUMBER()and deleting rows numbered above 1, then add aUNIQUEconstraint. - Consider soft deletes for history, and batches or partitions for very large deletes.
Practice questions
Write a DELETE that removes the products that have never been ordered.
Answer
DELETE FROM products p
WHERE NOT EXISTS (SELECT 1 FROM order_items oi WHERE oi.product_id = p.product_id);
It removes the Basecamp lantern. Products that have been ordered are referenced by order_items, so the foreign key would block deleting them anyway.
Why does DELETE FROM customers WHERE customer_id = 1 fail on the shop database?
Answer
Asha (customer 1) is referenced by two kinds of rows: Asha's orders 101 and 103 reference the customer, and Ben's and Chen's referred_by values point to Asha. The foreign keys reject the delete while those references exist.
A staging table is reloaded every night. Should the job empty it with DELETE or TRUNCATE?
Answer
TRUNCATE, if nothing references the table and no delete triggers are needed. It's much faster and reclaims the space immediately. In MySQL and Oracle, remember that it commits immediately and can't be rolled back.
Change the duplicate-removal query so that it keeps each email's most recent signup instead of the earliest.
Answer
Reverse the window's order:
DELETE FROM signups
WHERE signup_id IN (
SELECT signup_id
FROM (SELECT signup_id,
ROW_NUMBER() OVER (PARTITION BY email
ORDER BY signed_up DESC, signup_id DESC) AS rn
FROM signups) AS numbered
WHERE rn > 1
);
It keeps IDs 6 (asha), 5 (ben) and 4 (chen).
Why does DELETE FROM customers WHERE customer_id NOT IN (SELECT customer_id FROM orders) delete nothing on the shop database?
Answer
The guest order 106 has a NULL customer_id, so the subquery's results include NULL. x NOT IN (..., NULL) is never true, only false or unknown, so no row qualifies. Use NOT EXISTS, or add WHERE customer_id IS NOT NULL to the subquery.
Previous: Updating Rows With UPDATE: Expressions, Subqueries and Joins
Next: MERGE, Upserts and RETURNING: Insert-or-Update in One Statement

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.