How to delete records from a table when not found in another table?

Kiruthiga Vasudevan 20 Reputation points
2023-04-04T13:48:39.49+00:00

I have temp table with data #temp_table

User's image

I have a 2nd table with data - final_table

User's image

I want to delete records from final_table , those records that are not in the #temptable, for that projectID only. Meaning I need to delete this record from the final__table.

User's image

End result on the final_table should be -

User's image

I tried a couple of delete stmts, but they all end up deleting that one record for that projectID and also the other records for other projectIDs too.. Any help from anyone is highly appreciated. Thank you folks.

Azure SQL Database
SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-04-04T15:31:56.6033333+00:00

    join on project id, then delete missing.

    delete 
    from final_table f
    join #temp_table t on f.project_id = t.project_id
    where not exits (select * 
                      from #temp_table t2
                      where t2.project_id = f.project_id
                            and t2.pipeline_id = f.pipline_id)
    

    or just a where clause:

    delete 
    from final_table f
    where exits (select * 
                      from #temp_table t
                      where t.project_id = f.project_id)
    and not exits (select * 
                      from #temp_table t
                      where t.project_id = f.project_id
                            and t.pipeline_id = f.pipline_id)
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. VasimTamboli 5,215 Reputation points
    2023-04-04T14:15:57.5366667+00:00

    You can use a DELETE statement with a subquery to achieve this. Here's an example:

    DELETE FROM final_table
    WHERE projectID = 'ABC'
    AND NOT EXISTS (
        SELECT 1
        FROM #temp_table
        WHERE #temp_table.userID = final_table.userID
    )
    
    

    This statement deletes all records from final_table for the specified projectID where the userID does not exist in #temp_table. The NOT EXISTS subquery checks if a matching userID exists in #temp_table. Note that you should replace 'ABC' with the actual projectID you want to delete records for. If you want to delete records for multiple **projectID**s, you can include them in a WHERE clause with an IN operator, like this:

    DELETE FROM final_table
    WHERE projectID IN ('ABC', 'DEF')
    AND NOT EXISTS (
        SELECT 1
        FROM #temp_table
        WHERE #temp_table.userID = final_table.userID
    )
    
    

    This deletes records for both ABC and DEF **projectID**s that are not in #temp_table.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.