The mystique of the DELETE FROM FROM

Recently I came across a CRM query which used FROM twice in the DELETE statement.

Below is an example of it in action and yes a warning the results can be a bit perplexing.
 

-- Create a table
 CREATE TABLE your_table
 (
  id int IDENTITY (1,1)
 ,y_n char(1) NULL
 );
 GO
 -- Create a view
 CREATE VIEW your_view
 AS
 SELECT id,y_n
 FROM your_table
 WHERE y_n = 'y';
 GO

 -- Insert some data into the table
 INSERT INTO your_table (y_n)
 VALUES
  ('y')
 ,('y')
 ,('y')
 ,('y')
 ,('n');
 GO

image1_1

-- First DELETE test
-- With the view after the first FROM with 'n'
BEGIN TRAN
DELETE 
FROM your_view
FROM your_table t
WHERE t.y_n = 'n';

 -- You get 1 row returned
SELECT * FROM [your_table] WITH (NOLOCK);

ROLLBACK

image2

-- Second DELETE test
-- With the view after the first FROM with 'y'
BEGIN TRAN
DELETE 
FROM your_view
FROM your_table t
WHERE t.y_n = 'y';

-- You also get the same row returned
SELECT * FROM your_table WITH (NOLOCK);

ROLLBACK

image3

-- Third DELETE test
-- With the table after the first FROM with 'n'
BEGIN TRAN
DELETE 
FROM your_table
FROM your_view v
WHERE v.y_n = 'n';

-- You get all rows returned
SELECT * FROM your_table WITH (NOLOCK); 

ROLLBACK

image4

-- Final DELETE test
-- With the table after the first FROM with 'y'
BEGIN TRAN
DELETE 
FROM your_table
FROM your_view v
WHERE v.y_n = 'y';

-- All rows are now deleted
SELECT * FROM your_table WITH (NOLOCK);

ROLLBACK

image5
To remove the table and view use:

DROP VIEW your_view;
DROP TABLE your_table;

image6

Leave a Reply