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 o deletes only from dbo.orders (aliased as o)—it does not delete rows from dbo.customers.
  • Only rows in dbo.orders that match dbo.customers and satisfy the WHERE predicate 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

  1. Preview matching rows with SELECT first: Run a SELECT with the exact same FROM, INNER JOIN, and WHERE clauses to confirm the row count and target rows before changing SELECT to DELETE <alias>.
  2. Double-check the DELETE <alias> target: Never write DELETE FROM dbo.orders AS o INNER JOIN ... without specifying the target alias after DELETE (standard SQL syntax differs from T-SQL here, and explicit aliasing prevents mistakes).
  3. 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.
  4. Test inside a transaction: Wrap ad-hoc deletes in BEGIN TRAN, check @@ROWCOUNT, and run COMMIT TRAN once verified (or ROLLBACK TRAN to revert).