Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete in MS Access when using JOIN's?

I am attempting to use the DELETE clause in MS Access and have an issue when also using the JOIN clause. I have notice this can be accomplished by using the DISTINCTROW key word.

For example, the following SQL statement does not allow for deletion:

DELETE Table1.*
FROM Table1 INNER JOIN Table2 ON Table1.Name=Table2.Name;

However, this statement does:

DELETE DISTINCTROW Table1.*
FROM Table1 INNER JOIN Table2 ON Table1.Name=Table2.Name;
  • Why does the DELETE work when using the DISTINCTROW key word?
  • More specifically, what is happening in the JET engine to require this?
like image 960
Curtis Inderwiesche Avatar asked Apr 07 '11 18:04

Curtis Inderwiesche


People also ask

How do you use Delete in MS Access?

Just open the table in Datasheet view, select the fields (columns) or records (rows) that you want to delete, and then press DELETE. Important: The information in this article is intended for use only with desktop databases. You cannot use delete or update queries in Access web apps.


2 Answers

Delete Table1.*
From Table1
Where Exists( Select 1 From Table2 Where Table2.Name = Table1.Name ) = True

To expand on my answer, the official SQL specification does not provide for using Joins in action queries specifically because it can create ambiguous results. Thus, it is better (and Access is much happier) if you can avoid using Joins in action queries like I have here. The reason that Access wants DISTINCTROW is that it is likely that the Join between the two tables would create duplicates of Table1 rows (i.e., there are multiple related rows in Table2) and thus Access gets confused. I've also found that if you try to use a Join and a primary key does not exist Access will balk. In general, it is better to avoid a join in an action query if you can.

like image 156
Thomas Avatar answered Oct 09 '22 11:10

Thomas


One problem to be aware of: This does NOT work with table/query aliases!

DELETE a.*
from tblA as A
where exists (select 1 from tblB as B where a.id=b.id)

Deletes ALL records in tblA! I tried it using alias for tblA and tblB seperately - same result (Access 2010).

Happens with SELECT as well (which I often use before deleting)...

like image 3
MarcusFey Avatar answered Oct 09 '22 10:10

MarcusFey