Search code examples
sqlsql-server-cesql-deletebulk

SQL Statement deleting entire table


I have two tables that both have an ID number which are linked together (AllUsers and AllProfiles). When the user presses a button, I want the AllUsers table to check for IDs it has that are not present in the AllProfiles table and delete them. I'm new to SQLCE and hacked this together. The problem is, it keeps deleting the entire table. Why?

DELETE FROM AllUsers
WHERE  EXISTS
    (SELECT       ID
     FROM         AllUsers
     WHERE        (ID NOT IN
                     (SELECT ID
                        FROM AllProfiles)))

Also, is this an efficient way of bulk deleting thousands of records? I tried Linq's DeleteAllOnSubmit but it was too slow. I'm hoping since the above is comparing two tables directly, it should be efficient. (I don't want to use cascading as I need control of each table individually)

EDIT - The SELECT statement correctly returns the missing IDs, so there's something wrong with the DELETE FROM AllUsers WHERE EXISTS part.


Solution

  • You're basically saying

    delete from allusers
    where TRUE -- this is pseudo, but you get the idea
    

    Your original query deletes the whole table because the only condition is boolean... if that returns data then it'll delete all the data. If your exists clause does not return data it would not delete any data.

    You want something like this (I'm not fluent with CE, but you should be able to make a minor modification if it doesn't 100% transport over to CE):

    delete from allusers
    where id not in
    (
        select id
        from allprofiles
    )