In SQL Server (T-SQL), you delete rows from a target table based on matching conditions in another table by specifying the target table or alias right after DELETE and joining the tables in the FROM clause (DELETE target_alias FROM dbo.target_table AS target_alias INNER JOIN dbo.other_table AS s ON ...). Always verify which table is being deleted from and test with a SELECT or inside a transaction (BEGIN TRAN / ROLLBACK TRAN) before committing.
1. Standard DELETE ... FROM ... INNER JOIN Syntax
Specify the alias of the table you want to delete rows from right after DELETE, and define the join and filter conditions in FROM and WHERE.
DELETE o
FROM dbo.orders AS o
INNER JOIN dbo.customers AS c
ON o.customer_id = c.customer_id
WHERE c.is_fraudulent = 1
AND o.status = 'CANCELLED';
DELETE odeletes only fromdbo.orders(aliased aso)—it does not delete rows fromdbo.customers.- Only rows in
dbo.ordersthat matchdbo.customersand satisfy theWHEREpredicate are removed.
2. Deleting Based on Multi-Column Matches or Subqueries/CTEs
When matching requires multiple keys or pre-filtered/aggregated rows from another table, join on all relevant columns or use a Common Table Expression (CTE).
WITH stale_sessions AS (
SELECT
s.session_id,
s.user_id
FROM dbo.user_sessions AS s
INNER JOIN dbo.users AS u
ON s.user_id = u.user_id
WHERE u.is_deleted = 1
AND s.last_activity_at < DATEADD(DAY, -30, SYSUTCDATETIME())
)
DELETE s
FROM dbo.user_sessions AS s
INNER JOIN stale_sessions AS ss
ON s.session_id = ss.session_id
AND s.user_id = ss.user_id;
3. Deleting Rows in Large Tables Safely (Batching)
Deleting millions of rows in a single DELETE ... JOIN statement can cause long table/page locks, transaction log growth, or blocking. Delete in batches using TOP (n) inside a loop or transaction:
WHILE 1 = 1
BEGIN
DELETE TOP (5000) o
FROM dbo.orders AS o
INNER JOIN dbo.customers AS c
ON o.customer_id = c.customer_id
WHERE c.account_status = 'CLOSED_TEST'
AND o.created_at < '2025-01-01';
IF @@ROWCOUNT = 0
BREAK;
END;
4. Safe Execution Checklist in T-SQL
- Preview matching rows with
SELECTfirst: Run aSELECTwith the exact sameFROM,INNER JOIN, andWHEREclauses to confirm the row count and target rows before changingSELECTtoDELETE <alias>. - Double-check the
DELETE <alias>target: Never writeDELETE FROM dbo.orders AS o INNER JOIN ...without specifying the target alias afterDELETE(standard SQL syntax differs from T-SQL here, and explicit aliasing prevents mistakes). - Check foreign key constraints and cascade behavior: If other tables reference the rows being deleted without
ON DELETE CASCADE, SQL Server will block the delete until child rows are handled. - Test inside a transaction: Wrap ad-hoc deletes in
BEGIN TRAN, check@, and runCOMMIT TRANonce verified (orROLLBACK TRANto revert).
