Creating and Running Delete Queries
Rather than just modify table data, Delete queries
permanently remove from a table any records that meet specific
criteria; they’re often used to remove old records. You might want to
use a Delete query to delete all orders from the previous year, for
example.
It’s important to remember that if you have turned
on the Cascade Update Related Fields Referential Integrity setting and
the Update query tries to modify a primary key field, Access updates
the foreign key of each corresponding record in related tables. If you
have not turned on the Cascade Update Related Fields setting and you
have enforced referential integrity, the Update query doesn’t allow you
to modify the offending records.
|
Build a Delete Query
To build a Delete query, follow these steps:
1. | While in a query’s Design view, select Delete from the Query Type group on the Design tab of the Ribbon.
|
2. | Add to the query grid the criteria you want. The query shown in Figure 3 deletes all orders with a Status ID of 3 (closed).
|
3. | Click Run in the Results group on the Design tab of the Ribbon. The message box shown in Figure 4 appears.
|
4. | Click Yes to permanently remove the records from the table.
The SQL behind a Delete query looks like this:
DELETE tblTimeCards.DateEntered FROM tblTimeCards WHERE (((tblTimeCards.DateEntered)<Date()-365)); |
It’s often useful to view the results of an Action
query before you actually affect the records included in the criteria.
To view the records affected by an Action query, you click the View
button in the Results group on the Design tab of the Ribbon before you
select Run. All records that will be affected by the Action query
appear in Datasheet view. If necessary, you can temporarily add key
fields to the query to get more information about the records that are
about to be affected.
|
Remember that if you turn on the Cascade Delete
Related Records Referential Integrity setting, Access deletes all
corresponding records in related tables. If you do not turn on the
Cascade Delete Related Records setting and you do enforce referential
integrity, the Delete query doesn’t allow you to delete the offending
records. If you want to delete the records on the “one” side of the
relationship, first you need to delete all the related records on the
“many” side.