Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL, how to delete a row from one table if it doesn't have a corresponding row in another table?

Tags:

sql

How can I make:

DELETE FROM foo WHERE id=1 AND bar not contains id==1

To elaborate, how can I remove a row with id = 1, from table foo, only if there is not a row in table bar with id = 1.

like image 453
fmsf Avatar asked Nov 05 '08 01:11

fmsf


People also ask

Can we delete a row from a table based on another table?

Deleting rows based on another table. Sometimes we need to delete rows based on another table. This table might exist in the same database or not. We can use the table lookup method or SQL join to delete these rows.

How do I find records in one table but not another in SQL?

How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.

How do I delete a row from multiple tables in SQL?

The basic syntax of the DELETE query Typical syntax of the DELETE query in SQL Server looks as follows: DELETE FROM <table_name> WHERE <condition>; Parameters: <table_name>: a table name you want to delete rows from.


2 Answers

DELETE FROM foo WHERE id=1 AND NOT EXISTS (SELECT * FROM bar WHERE id=1)

I'm assuming you mean that foo and bar are tables, and you want to remove a record from foo if it doesn't exist in bar.

like image 136
Ned Batchelder Avatar answered Sep 24 '22 20:09

Ned Batchelder


using a join:

delete f
from   foo f
left
join   bar b on
       f.id = b.id 
where  f.id = 1 and
       b.id is null
like image 39
nathan_jr Avatar answered Sep 24 '22 20:09

nathan_jr