Taking the following two table variables, is there any (faster/shorter/more efficient) alternative to delete any data from @tbl_big
that doesn't exist within @tbl_small
? The reason is that I have a large selection of data, and based on optional parameters (in a procedure) I filter the data down further before presenting to the user.
The userId
column is indexed in the physical table these table variable columns are populated from.
DECLARE @tbl_big TABLE (userID int);
INSERT INTO @tbl_big (userID) VALUES (1),(5),(10),(20),(30),(40),(60),(100);
DECLARE @tbl_small TABLE (userID int);
INSERT INTO @tbl_small (userID) VALUES (1),(5),(10),(20)
-- this deletes 30,40,60,100 from @tbl_big
DELETE FROM
@tbl_big
WHERE
(userID NOT IN (SELECT userID FROM @tbl_small));
SELECT * from @tbl_big;
http://www.sqlfiddle.com/#!6/d41d8/12674
I did wonder whether INTERSECT
or EXCEPT
might do this but can't figure them out.
Update: EXCEPT
/INTERSECT
findings included as an answer. I'm not sure if there's a shorter way from a coding perspective...?