3 4
As you might expect, delete queries remove records from tables. Keep in mind that if you run a delete query, the query will delete the entire record, not just the field you specify in a criteria expression. This will become clearer when we look at a delete query's SQL equivalent later in this section.
Don't Neglect Your Relationships
Relationships are critically important to a delete query. In the sidebar "Updating Both Sides of a Relationship," you learned how to use a relationship to automatically update foreign key values in the "many" side of that relationship by making a change to the primary key value in the "one" side. The same behavior is possible when you run a delete query-which might or might not be exactly what you want. Using the right tools for the job will make it easier for you to troubleshoot any problems down the road.
To use a simple delete query to delete order records more than four years old based on the current date, follow these steps:
Figure 10-11. Turn on the cascading delete option.
<DateAdd("yyyy",-4,Now())
Figure 10-12. The expression limits the query to records that are at least four years old.
tip
Figure 10-13. Check the query in Datasheet view before you permanently delete the records.
Make a note of the first few and last few order numbers so that you can confirm later that the query actually deleted those records. Don't worry if your order numbers are different from the ones in the figure-the exact orders returned depends on the current date (Now). Notice that the record navigation bar displays the number of records the query will delete-in this example, that's 258 records.
Figure 10-14. Click Yes to run the query.
Remember when I mentioned how important relationships were when running delete queries and you made a copy of the Order Details table? You're about to learn why. Open the Order Details table. As you can see in Figure 10-15, Access deleted all the records related to the orders we just deleted, because the relationship forces cascading deletes.
Figure 10-15. Records are missing from this table.
Now let's look at the delete query's SQL statement, shown here:
DELETE Orders.OrderID, Orders.OrderDate FROM Orders WHERE (((Orders.OrderDate)<DateAdd("yyyy",-4,Now())));
Notice that the statement identifies only the two fields that we specified in the design grid: OrderID and OrderDate. However, the query deleted the entire record. It makes no difference whether you specify a single field or all the fields in a delete query; the query will delete the entire record, not just the data in the specified fields. This makes the DELETE statement less readable than some of the other SQL statements, but the logic behind the behavior is sound. If you want to delete data from a field rather than deleting an entire record, you should run an update query to update the field to a zero-length string ("") or Null. (See "Changing Data with an Update Query.")