MS Access - Working With Queries
MS Access - Working With Queries
Prerequisites
Queries are the stars of Microsoft Access. Queries make sense out of all the
thousands of jumbled records and display exactly what you need to know.
Queries discover things like what the average price of tea in China is or which
customers bought the most parakeet food from your company. Queries can
even make widespread changes to the records in your database without
wearing out your mouse and keyboard! For example, a delete query can
automatically delete a whole bunch of records that meet your criteria.
3971408.doc - 191 -
In this tutorial you will learn how to harness the power of queries. First you will
learn about all the different types of queries: simple select queries, parameter
queries that prompt you for more information, crosstab queries that summarize
records in an easy-to-understand format, and action queries that actually
modify the records in your database.
All this power comes with a price tag: Many people find that queries are one of
the more difficult database objects, and learning how to fully utilize queries isn't
something you can learn in an afternoon. By the time you finish this tutorial,
however, you will have a good start towards understanding and mastering
queries.
A Quick Review
Figure 6-1. The in Design view.
Before we start tackling the functions and types of queries, let's take a step
back and review. This lesson is more of a "cheat sheet" than an exercise.
Hopefully, it will help you remember what you already know about queries.
Figure 6-1 shows the in Design view, Figure 6-2 shows a close-up of the design
grid, and Table 6-1 outlines the Common Criteria Operators.
3971408.doc - 192 -
Operator Example Description
BETWEEN 1/1/99
BETWEEN Finds records between 1/1/99 AND 12/31/99.
AND 12/31/99
IS NOT
IS NOT NULL Finds records whose fields contain values.
NULL
3971408.doc - 193 -
Reference
OR...
DRAG THE FIELD FROM THE FIELD LIST ONTO THE DESIGN GRID.
3971408.doc - 194 -
Up until now, when you thought of a query, you were actually probably thinking
of a select query a particular type of query. Select queries are by far the most
common and useful type of query in Access; however, there are other types of
queries that are also important.
We will cover most of these query types in this tutorial, so here's a quick
overview of the different types of queries you'll find in Microsoft Access. Each
type of query has its own icon, as shown in Figure 6-3. Table 6-2 describes the
different types of queries.
Reference
3971408.doc - 195 -
Query Type Description
The most basic and common type of query, select queries find and
display the data you want from one or more tables or queries.
Prompts the user for specific information every time the query is
run.
While select queries display information that matches your criteria, the following
action queries do something to the data that matches your criteriasuch as
change or delete it.
Creates a new table from all or part of the data in one or more
tables. Useful for backing up and exporting information.
Append Appends or adds selected records from one table to another table.
Query Useful for importing information into a table.
Delete
Deletes selected records from one or more tables.
Query
Union Combines fields from two or more tables or queries into one field
Query and is written directly in SQL.
3971408.doc - 196 -
In Access you will often need to look at and analyze information that comes
from not one but several different tables. Since Access is a relational database,
it's easy to establish a relationship between two or more tables and look at the
information that goes together.
Just like it sounds, a multiple-table query blends together information from two
or more related tables. Working with a multiple-table query usually isn't much
different from working with a single-table query. You tell Access which tables
you want to use in your query and specify the fields and criteria you want to
see. The main difference between a multiple-table query and a single-table
query is that with , Access creates a link between related tables. When the
query is displayed in Design view, this link (called a join) appears as a line that
connects two or more tables.
When you create a multiple-table query, Access will usually link or join the
tables automatically. Sometimes, however, you will have to manually join two
tables in the query design window. You can manually join two tables by
dragging a field from one table's field list to the matching field in the other
table's field list, as shown in Figure 6-4. If the tables don't have any fields in
common, you must add another table to act as a bridge between them. This
lesson will give you some experience creating a multiple-table query.
2. Click the Queries icon in the Objects bar and then double-click Create
query in Design view.
3971408.doc - 197 -
The query design window and Show Table dialog box both appear. You
have to select the tables and/or queries you want to use.
A field list for the tblEmployees table appears in the top half of the query
design window. You also want to add the tblCustomerTours table and the
tblTours table to the query.
When you have finished adding the tables and/or queries to your query,
you can close the Show Table dialog box.
5. Click Close.
If two tables are related, Access will automatically connect their common
fields with a join line. For example, Access automatically joined the
tblTours table and the tblCustomerTours table because they are already
related. If the tables aren't related you will have to manually join the
tables by dragging a field from one table's field list to the matching field
in the other table's field list.
6. Click EmployeeID in the tblEmployees field list and drag and drop it onto
Employee in the tblCustomerTours field list.
Click EmployeeID in the tblEmployees field list and drag and drop it onto
Employee in the tblCustomerTours field list.
Note: You can remove a join from a query by clicking the join line
(carefulthere's not much there to click!) and pressing Delete.
Next you need to specify the fields you want to appear in the query
results. You can add fields to the query design grid in two ways:
3971408.doc - 198 -
o By clicking and dragging the field down to the design grid yourself.
Because field lists don't have much room to display their contents, you
may have to scroll up or down the list in order to find the field you want.
Access adds the LastName and FirstName fields from the tblEmployees
table to the design grid. Next add the fields for the tblTours and
tblCustomerTours tables.
8. Double-click the TourName field in the tblTours field list and the Date and
Cost fields in the tblCustomerTours field list.
Next you need to specify any criteria for the query. For this exercise, you
want to see tours from the first quarter of the year.
9. Click the Date column's Criteria row and type Between 1/1/00 and 3/31/00.
10.Click the Date column's Sort box list arrow and select Ascending.
Tip: Other ways to run a query are to open the query from the Database
window, or click the View button on the toolbar in Design view, or select
Query Run from the menu.
Access displays the results of the query. The results show the names of
the employees who sold tours and the names, dates, and costs of each
tour.
3971408.doc - 199 -
Reference
OR...
DRAG THE FIELD FROM THE FIELD LIST ONTO THE DESIGN GRID.
3971408.doc - 200 -
Figure 6-7. To enter fields in an expression, type the field name in
brackets ([Order Total]).
Figure 6-8. If a field name exists in more than one table, you will
need to enter the name of the table that contains the field in
brackets ([Customer Tours]) followed by an exclamation mark
(!). Then type the field name in brackets ([Order Total]).
Normally, when you create a database, you should only have to enter the
information you need and not worry about data or values that Access calculates
based on information already in the database. A calculated field performs some
type of arithmetic on one or more fields in a database to come up with a
completely new field. For example, if your database has an Order Total field and
a Tax Rate field, Access can calculate these two fields to find out the Sales Tax
for each order: [Order Total] x [Tax Rate] = [Sales Tax].
3971408.doc - 201 -
You must create an expression (or formula) to perform a calculation. To enter
fields in an expression, type the field name in brackets ([Order Total]), as
described in Figure 6-7. If a field name exists in more than one table, you will
need to enter the name of the table that contains the field in brackets
([Customer Tours]) followed by an exclamation mark (!). Then type the field
name in brackets, such as [Order Total], as described in Figure 6-8. For
example if an Orders table and a Shipping table both contain a Date field, you
would tell Access which of the two Date fields you want to use by typing the
table name ([Orders]), an exclamation mark (!), and then the field name
([Date]) or, in other words, [Orders]![Date]. Yes, can be a little confusing at
first...
This lesson will show you how to add a calculated field to a query.
2. Click the Queries icon in the Objects bar if necessary, click the
qryEmployeeSales query, and then click the Design button.
3. Click the blank Field cell of the fourth column and type
Bonus:[Cost]*[Commission], as shown in Figure 6-6.
Tip: You can also use the Expression Builder to help you create your
calculated fields. Click the Builder button on the toolbar, double-click the
field you want to use in the calculation, click the button that corresponds
to the calculation you want, and then click or type any other fields or
values you want to use.
The expression you entered will create a new calculated field named
"Bonus" that will display the results of the Cost field in the
tblCustomerTours table multiplied by the Commission field in the
tblEmployees table.
3971408.doc - 202 -
Let's see the results of our calculated field.
Tip: Other ways to run a query are to open the query from the Database
window, or click the View button on the toolbar in Design view, or select
Query Run from the menu.
Access displays the results of the query. The "Bonus" calculated field
multiplies the Cost field by the Commission field in each record and
displays the results.
Save your changes in a new query with a different name. Here's how:
You're already familiar with some of the used in expressions; including math
symbols such as the plus sign (+) to perform addition between values, and the
minus sign (-) to perform subtraction between values. Check out Table 6-3
below for a refresher on the various arithmetic operators.
* Multiplication
+ Addition
- Subtraction
/ Division
^ Exponentiation
3971408.doc - 203 -
Reference
OR...
3971408.doc - 204 -
You can add calculations to queries, forms, and reports by typing an expression,
or a formula that tells Access exactly what to calculate. An expression can be
any combination of values, identifiers (such as the value in a field), and
operators that result in a value. Here's an example of an expression that
calculates profit from two fields called Income and Expenses:
Number fields aren't the only types of fields that you can use in you can also
perform calculations with dates, times, and text data.
The problem with creating expressions is you have to enter a formula so that
Access understands it (and believe me, Access isn't very bright). For example,
when you create an expression, some types of information must be enclosed
between special characters so that Access knows what type of information it
istable names and field names must be enclosed in [brackets], text strings in
"quotation marks," and so on. Table 6-4 has more information about how to use
various elements in an expression.
If you know what you want an expression to do but not how to write it, you can
try using the Expression Builder. The Expression Builder lets you pick the fields,
mathematical symbols, and functions you can use to create an expression.
This lesson will give you some more experience writing expressionsboth on your
own and using the Expression Builder.
3971408.doc - 205 -
1. Click the qrySales query and then click the Design button.
First you need to insert a blank column at the beginning of the design
grid. Here's how:
2. Position the mouse over the top of the Normal Price field (until changes
to ) and click to select the field. Press Insert to add a new column.
A column is inserted before the Normal Price column. In the next step,
you will learn how to create one of the most common database functions:
how to combine the tblEmployees table's FirstName and LastName fields
to display the full name.
The is used to combine or concatenate two or more text fields. The " "
adds a space between the [FirstName] and [LastName] fields.
Next you need to enter an expression that calculates the cost of the tour
by multiplying the Number of Tickets field by the Normal Price field. You
will use the Expression Builder to help you write this expression.
4. Click a new blank field and click the Build button on the toolbar.
Tip: Another way to use the Expression Builder is to right-click in any field
and select Build from the shortcut menu.
6. Click OK.
3971408.doc - 206 -
The Expression Builder closes. Add a meaningful label to the new
calculated field.
7. In the new calculated field, replace the Expr1: label with Total:
The query combines the FirstName and LastName fields in the new Agent
field and displays the total sales price in the new Total field.
9. Click the Save button on the menu to save your changes and then close
the query.
Microsoft Access is very strict about how you write your expressions. If your
expressions aren't written in the correct syntax, they won't work. Use the
following table as a guideline for adding fields, text, and constants to your
expressions.
Text "Minneapolis"
3971408.doc - 207 -
Reference
Figure 6-11. Here the IIf function evaluates the value in the First
Class field and returns 50 if the First Class field is True and 25 if
the First Class field is False.
3971408.doc - 208 -
Functions are used to create more complicated calculations or expressions than
operators can. For example, the adds several values together, and the IPmt
function calculates the loan payments based on an interest rate, the length of
the loan, and the principal amount of the loan.
There are several hundred in Access, but all of them are used in a similar way:
the name of the function, followed by the arguments in parenthesis. An
argument in Access is the value a function uses to perform its calculationnot the
heated disagreement you have over political views. For example, the argument
in the formula p r2 would be r, or the radius, used to find the area of a circle.
This lesson introduces a very useful database function: the IIf function. The IIf
function is a or because it evaluates a condition and returns one value if the
condition is true and another value if the condition is false. For example, you
could use the IIf function in an invoice to create a formula that would subtract a
5-percent discount from the invoice if the total were more than 500
dollarsotherwise, the IIf Function wouldn't subtract anything.
The IIf function contains three arguments, as shown in Figure 6-10. Since you
can use the to help you create IIf function formulas, you really don't need to
memorize the syntax of the function.
In this lesson you will use the IIf function to create a field that gives passengers
a 50-dollar rebate if they fly first class and a 25-dollar rebate if they fly coach,
as shown in Figure 6-11.
1. Click the qryRebate query and then click the Design button.
You need to create a calculated field that will determine how much of a
rebate passengers should receive. Create this field in the first blank Field
row.
2. Click the blank Field row in the fifth column and click the Build button on
the toolbar.
3971408.doc - 209 -
The Expression Builder appears.
To use one of the built-in functions, double-click the Functions folder and
select the in the bottom-left window.
The Functions folder expands and displays its contents. The Built-In
Functions folder contains several hundred functions that are included in
Access.
When you select the Built-In Functions folder in the left window, the
middle window displays the function categories you can use, and the right
window displays the functions in the selected category. If you know the
category of the function you want to use, you can select it in the middle
window to narrow down your choices in the right window.
5. Scroll down the middle window and find and click the Program Flow
function category.
3971408.doc - 210 -
You need to specify the logical testif the passenger flew first class or not.
8. Double-click the Tables folder in the left window, click the tblCustomers
folder, and then double-click the First Class field in the middle window.
The Expression Builder adds the First Class field to the expression. Finish
the rest of the logical test.
9. Type =true.
10. Double-click the ?truepart? argument and type 50, then double-click the ?
falsepart? argument and type 25.
11.Click OK.
The Expression Builder closes. We need to give the new calculated control
a more meaningful name...
12. In the new calculated field, replace the Expr1: label with Rebate:
The IIf expression in the new Rebate field evaluates the First Class field
and returns a 50-dollar rebate if the customer flew first class, and a 25-
dollar rebate if not.
3971408.doc - 211 -
Reference
OR...
3971408.doc - 212 -
When you work with queries, you will often be less interested in the individual
records and more interested in summarized information about groups of
records. A query can calculate information about a group of records in one or
more tables. For example, you could create a query that finds the total amount
of tea your company sold to China in 1998 or how much all that tea cost. The
Total row lets you group and summarize information in a query. The Total row
normally is tucked away from view in the query design windowyou can make
the Total appear by clicking the Totals button on the toolbar or by selecting View
Totals from the menu. Once the Total row is displayed, you can tell Access
how you want to summarize the fields.
1. Click the qryTourSales query and then click the Design button.
First you need to add the field that you want to group data by onto the
design grid. You want to calculate the total sales and number of tickets
sold for each tour package, so you will group the query by the TourName
field.
The TourName field appears as the first field in the design grid. Next you
need to add the fields you want to summarize.
To summarize your query, you must summon the Total row. To summon
the Total row, click the Totals button on the toolbar or select View
Totals from the menu.
3971408.doc - 213 -
4. Click the Totals button on the toolbar.
Tip: Another way to display the Total row is to select View Totals from
the menu.
The Total row appears in the design grid. "Group By" must remain in the
TourName Total row to group the records by the TourName field. Next you
need to select the fields you want to summarize and the calculation you
want to perform on them.
5. Click the Total row in the Number of Tickets column and click the list
arrow that appears.
7. Click the Total row in the Cost column, click the list arrow, and select Sum
from the list.
You want to calculate only those records from the second quarter of the
year.
3971408.doc - 214 -
9. Click the Total row in the Date column, click the list arrow, and select
Where from the list.
10. Click the Date column's Criteria row and type Between 4/1/00 and 6/30/00.
Access displays the results of the query, which calculates the total sales
and number of tickets sold for each tour package.
12. Save the query as qryTourTotals and then close the query.
Groups the values in the field so that you can perform calculations
Group By
on the groups.
3971408.doc - 215 -
Option Description
calculation.
Reference
3971408.doc - 216 -
Figure 6-14. Access displays the top five values it finds in the
query.
Figure 6-15. Access displays the five tours with the lowest total
sales.
If all you care about is the highest or lowest values produced by a query, you
can use the Top Values list in the to display only these records. For example,
you could use the Top Values list to display the ten largest or smallest orders in
the Invoices table.
This lesson explains how you can use the Top Values list to display the top or in
a query.
1. Click the qryTourSales query and then click the Design button.
Move to the next step and add the fields you want to see in your query.
3971408.doc - 217 -
2. Double-click the TourName field in the tblTours field list, and the Cost and
Smoker fields in the tblCustomerTours field list.
You want to create a query that retrieves the five most expensive
nonsmoking tours. First you need to add the nonsmoking criteria to the
query.
3. Click the Criteria row in the Smoker column and type False.
Now you need to sort the field that you want to display the top or bottom
values for. The Sort row works a little differently when you're using top or
bottom values:
You want the query to display the top values in the Cost field, so...
4. In the Cost column, click the Sort box list arrow and select Descending.
Next you have to use the Top Values list to specify the number of top
values you want to be displayed in your query results.
5. Click the Top Values list arrow on the toolbar and select 5, as shown in
Figure 6-13.
This will display the five most expensive tickets. You're ready to run the
query.
7. Click the View button on the toolbar to display the query in Design view.
You can also use the Top Values feature to display the top or bottom
values from a calculation. Let's modify the query so that it calculates the
total sales of nonsmoking tour sales.
8. If the Total row is not already displayed, click the Totals button on the
toolbar.
3971408.doc - 218 -
The Total row appears. You need to specify which field you want to use to
group the query, which field(s) you want to be calculated, and which fields
are used to limit the number of records displayed in the query.
You want to group records using the TourName field, and since its Total
row already displays Group By, you can leave it as it is. You will need to
tweak the Total row for both the Cost and Smoker fields, however.
9. Click the Total row in the Cost column, click the list arrow, and select Sum
from the list.
This will total the Cost field. The Smoker field is used as criteria to limit
the records displayed to only nonsmokersit shouldn't be included in the
query results. Move on to the next step to tell Access this.
10.Click the Total row in the Smokers column, click the list arrow, and select
Where from the list.
One more change before we run the querythis time instead of displaying
the top values for the Cost field we want to display its bottom values.
11.In the Cost column, click the Sort box list arrow and select Ascending.
This will summarize the five tours with the lowest sales (for nonsmokers).
Let's see the results...
13. Save the query as qryBottomTours and then close the query.
Table 6-6 explains what each of the options in the Top Values list does.
Type a number, such as 15 in the Top The top 15 (or specified number of)
Values box records
3971408.doc - 219 -
Do This... ...to Display This
Click 5% or 25% from the Top Values List The top 5 or 25 percent of records
Type a percentage, such as 20%, in the The top 20 percent (or specified
Top Values box percent) of records
Click All from the Top Values list All of the records
Reference
Parameter Queries
Figure 6-16. Enter a by entering a message or prompt
enclosed in [brackets] in the field's criteria row.
Figure 6-17. The parameter query prompts the user to enter the
state.
3971408.doc - 220 -
Figure 6-18. The results of the parameter query.
Getting tired of modifying a query every time you want to use a new criterion?
A parameter query is your answer. A parameter query prompts the user for the
query's criteria. For example, you could create a Regional Sales query that
would ask for the name of the state that you want to filter by.
Creating a parameter query is easy. All you have to do is click the Criteria row
for the field that you want to use as a parameter and type a message, enclosed
in [brackets], that you want Access to display when you run the query, as
shown in Figure 6-16.
1. Click the qryTourSales query and then click the Design button.
As always, you need to add the field that you want to group data by onto
the design grid. This time we want to create a query that summarizes
total employee sales. Here are the fields that we will use in the query:
Next you need to tell the query that you want to group and summarize
the query.
3971408.doc - 221 -
The Total row appears. You need to specify which field(s) you want to use
to group the query, which field(s) you want to be calculated, and which
field(s) you want to use to limit the number of records displayed in the
query.
You want to group records using the FirstName, LastName, and State
fields and find the total of the Cost field.
4. Click the Cost column's Total row, click the list arrow, and select Sum
from the list.
This will total the Cost field. We will use the Date field as criteria to limit
the records to those that fall between two dates. Instead of entering a
criteria expression with two fixed date values, such as "Between 1/1/00
and 3/31/00," we will create two parameters that will prompt the user to
enter the two date values each time they run the query.
5. Click the Date column's Criteria row and type Between [Enter start date]
and [Enter end date].
You've just created two parametersthe [Enter start date] parameter and
the [Enter end date] parameter.
Since the Date field is only being used as a criteria field, you need to
select the "Where" option from its Total row.
6. Click the Date column's Total row, click the list arrow, and select Where
from the list.
The "Show" check box automatically unchecks itself, indicating that the
Date field will not appear in the query results.
Let's add one more parameterone that prompts the user to enter the
state where the tour was sold.
7. Click the State column's Criteria row and type [Enter the state].
This will prompt the user to enter the name of the state.
Since the State field is only being used as a criteria field, you need to
select the "Where" option from its Total row.
3971408.doc - 222 -
8. Click the State column's Total row, click the list arrow, and select Where
from the list.
Access prompts you to enter the first parameter, as shown in Figure 6-17.
You want to summarize records from Washington.
13. Save the query as qryParameter and then close the query.
3971408.doc - 223 -
Reference
3971408.doc - 224 -
Figure 6-20. Step Two: Select the field or fields that contain the
duplicate values.
Figure 6-21. The query displays those records that have duplicate
values in both the LastName and FirstName fields.
The helps you find records that have the same value in one or more fields. So
when would you need to use a Find Duplicates Query? Here are a few scenarios:
"Arrr-rrgh!" you shout as you realize that you and another co-worker have just
entered the same customers into a database. Fortunately, you can find the
duplicated records by using the Find Duplicates Query Wizard.
3971408.doc - 225 -
2. In the Database window, click the Queries icon in the Objects bar and
click the New button.
The first step of the Find Duplicates Query Wizard appears, as shown in
Figure 6-19. Choose the table or query that you want to sift through for .
The second step of the Find Duplicates Query Wizard appears, as shown
in Figure 6-20. Her you will tell Access which field or fields might contain
the duplicate information.
Since you are trying to find duplicate customers, you decide to search the
FirstName and LastName fields for duplicate values.
6. Click Next.
The next step of the appears. You can select any field (other than the
ones you specified in Step 4) that you want to be displayed in the query.
You decide to display the City and State fields so you can verify that the
records are duplicates.
7. Double-click the City and State fields. Click Next when you're finished.
You're finished! Well, almost. You have to give your query a name, or you
can accept the default name Access gives the query.
8. Click Finish.
Access saves the query with the name "Find duplicates for tblCustomers"
and displays the results of the query, as shown in Figure 6-21.
3971408.doc - 226 -
9. Close the query.
Reference
3971408.doc - 227 -
Figure 6-23. Specify the field that will join the records in the first
table to the records in the second table.
3971408.doc - 228 -
The helps you find the records in one table that do not have matching records in
another table. Some scenarios when you might need to create such a query
include:
In this lesson you will use the Find Unmatched Query Wizard to create a query
to find customers who have never booked a tour.
1. In the Database window, click the Queries icon in the Objects bar and
click the New button.
The first step of the Find Unmatched Query Wizard appears, as shown in
Figure 6-22. You need to choose the table or query whose values you
want to display in the query. Since you want to find customers without
any tour packages, you would select the tblCustomers table.
3971408.doc - 229 -
The second step of the Find Unmatched Query Wizard appears. Here you
have to tell Access which table contains the related records. Let's select
the tblCustomerTours table.
The third step of the Find Unmatched Query Wizard appears, as shown in
Figure 6-23. Here you have to specify the related field to join the records
in the first table to the records in the second table. Once you have
selected the matching record in both tables, click the button to join
the two tables.
5. Verify that the CustomerID field is selected in both tables and click the
button.
The Matching fields area displays the fields used to join the tables
(CustomerID = CustomerID).
6. Click Next.
Almost there! Now you have to specify which fields you want to see in the
query.
The LastName, FirstName, City, and State fields should all appear in the
"Selected fields" list.
8. Click Next.
Here you can give your query a nameor you can accept the default name
that Access gives the query.
9. Click Finish.
Access saves the query with the name "tblCustomers Without Matching
tblCustomerTours" and displays the results of the query, as shown in
Figure 6-24.
3971408.doc - 230 -
Reference
Crosstab Queries
Figure 6-25. It's difficult to see the bottom line in a long
list of records like this.
3971408.doc - 231 -
Figure 6-26. A query displays a summary view of Figure 6-24's
information.
There are many ways that queries can help you summarize and analyze all that
information in your database. A crosstab query displays summarized
information in a table format that makes it easy to analyze and compare data.
Look at the information displayed in Figure 6-25difficult to see the bottom line,
isn't it? Now look what happens when the same information is placed in a
crosstab query, as shown in Figure 6-26. Which do you think is easier to
understand?
You can create a crosstab query in Design View or by using the Crosstab Query
Wizard. The Crosstab Query Wizard is usually much easier, but it does have
some limitations:
3971408.doc - 232 -
• If you need to use more than one table or query in the crosstab query,
you will first need to create a separate query that has the tables you want
to use.
• You can't specify any limiting criteria when using the Crosstab Query
Wizard. (But you can always modify the crosstab query in Design View
and add the criteria yourself.)
In this lesson you will use the Crosstab Query Wizard to create a query that
summarizes monthly ticket sales by tours.
1. In the Database window, click the Queries icon in the Objects bar and
click the New button.
The first step of the Crosstab Query Wizard appears. Here you need to
select the table or query that contains the values you want. For this
exercise you will use the ToursByName query as the source for the
crosstab query.
3. Click the Queries option in the View section to display the queries in the
database, select the qryToursByName query, and click Next.
The second step of the Crosstab Query Wizard is which field you want to
use as the row headings for the crosstab. Let's use the TourName field for
your row headings.
The next step is determining which field you want to use for your column
headings. Let's use the Date field as the column heading.
Because you selected a date field, the asks by which interval you want to
group the dates: date, month, quarter, year, or date/time. For this
exercise you want the date column to group dates by months.
3971408.doc - 233 -
Probably the most important step in the Crosstab Query Wizard is
determining which field you want to calculate where columns and rows
intersect and the type of calculation you want to use to summarize the
fields.
7. Select the Number of Tickets field from the Fields list and the Sum option
from the Functions list, as shown in Figure 6-27.
This will calculate the total number of tickets sold for each tour, grouped
by month.
8. Click Next.
Access saves the query with the name "qryTicketsByDate" and displays
the results of the query, as shown in Figure 6-26. Let's modify the
crosstab query and add some limiting criteria.
10.Click the View button to display the crosstab query in Design view.
You only want to see tours for passengers without first class tickets.
12. Click the First Class column's Total row, click the list arrow and select
Where from the list. Click the First Class column's Criteria row and type
False.
13.Click the Run button on the toolbar.
Access displays the crosstab query, which only includes non-first class
tickets.
3971408.doc - 234 -
Reference
Delete Queries
Figure 6-29. A delete query
3971408.doc - 235 -
Figure 6-30. Access asks you to confirm the query.
Definitely the most dangerous of all queries is a delete query, a query that
deletes a whole bunch of records at a time. Once you have deleted records
using a delete query, you cannot undo the resultsthe records are gone forever!
Creating a delete query is no different than creating a select querywith one very
important difference: While a select query displays the records that match your
criteria, a delete query deletes those records. For this reason, you should
always preview the results of a delete query in Datasheet View to see which
records will be deleted.
If you want to delete records from multiple tablesfor example, a customer and
all of that customer's ordersyou need to do a few things first:
LeAnne Chang, one of North Shore Travel's managers, decides to open her own
competing travel agency across the street, and being the vindictive person she
is, takes all her customers with her. In this lesson you will create a delete query
to delete all the tours sold by LeAnne Chang.
1. From the Database window, click the Queries icon in the Objects bar and
click the New button.
The query design window and Show Table dialog box both appear. You
have to select the tables and/or queries you want to use in the delete
query.
3971408.doc - 236 -
A field list for the tblEmployees table appears in the top half of the query
design window.
When you have finished adding the tables and/or queries, you can close
the Show Table dialog box.
5. Click Close.
6. Click the EmployeeID field in the tblEmployees field list and drag and drop
it onto the Employee field in the tblCustomerTours field list.
7. Click the Query Type button list arrow on the toolbar and select
Delete Query from the list.
Tip: Another way to change the type of query is to select Query from the
menu and select the type of query from the list.
Access converts the select query to a delete query and displays the Delete
row in the query design grid. Now you have to tell Access what you want
to delete.
8. Drag the asterisk (*) from the top of the tblCustomerTours field list into
the design grid.
Notice that From appears in the Delete cell for the asterisk field,
indicating that the records will be deleted from the tblCustomerTours
table. Unless you want the query to delete each and every record in the
3971408.doc - 237 -
tblCustomerTours table, you will need to add some limiting criteria. You
decide to use the last name Chang as the limiting criteria.
9. Drag the LastName field from the tblEmployees field list into the design
grid.
This time Where appears in the Delete cell for the LastName field,
indicating that the LastName field will be used as the criteria to select
which records will be deleted from the tblCustomerTours table.
10. Click the LastName column's Criteria row and type Chang.
Access will add the "quotation marks" around the text string Chang for
you, as shown in Figure 6-29. That's all there is to creating a delete
query.
Note: Before you run a delete query, you should always preview the
results in Datasheet view first. Click the View button on the toolbar to
display the delete query in Datasheet view.
11.Click the View button on the toolbar to preview the results of the delete
query in Datasheet view.
The delete query displays the results of the delete query. Let's switch
back to Design view.
Let's run the delete query and delete the selected records.
Ever-cautious Access asks if you really want the delete query to delete the
records, as shown in Figure 6-30.
14.Click Yes.
3971408.doc - 238 -
15.Close the query without saving your changes and open the
qryToursByName query.
Notice that all the tours for LeAnne Chang are gone.
Reference
OR...
Append Queries
3971408.doc - 239 -
Figure 6-31. The Append dialog box asks where you want
to add the query's records.
An append query takes a group of records from one or more tables or queries in
your database and adds them to another existing table. Append queries are
especially useful for importing information into a table. For example, you could
use an append query to import several dozen customer records from an Excel
spreadsheet into an existing table. Of course, you would have to know how to
import the Excel spreadsheet firstand that's another lesson in and of itself.
There are several rules that you must follow when using an append query:
• The appended data must meet the data validation and referential integrity
rules of the table it is being added to.
• The appended data must have its own unique primary-key values. If the
primary-key field in the table to which the data is being added is an
AutoNumber field, do not append that fieldAccess will generate new
numbers for the new records.
• The type of data in the records you're adding must match the type of data
in the table to which you're adding them.
In this lesson you will create an append query to add a new group of tours to
the tblCustomerTours table.
3971408.doc - 240 -
1. If necessary, open the Lesson 6 database.
2. In the Database window, click the Queries icon in the Objects bar and
click the New button.
The query design window and Show Table dialog box both appear. Let's
select the tables and/or queries you want to use in the append query.
4. Click the tblCaribbeanTours table, click Add, and then click Close.
Now you need to convert the select query to an append query. Here's
how:
The Append dialog box appears, as shown in Figure 6-31. You have to tell
the append query where you want the results of the query to be added.
6. Select tblCustomerTours from the Table Name list and click OK.
The append query will add the results of its query to the tblCustomerTours
table. Notice that an Append To row appears in the design grid, as shown
in Figure 6-32. Now you have to specify the fields you want to append.
Since the field names are the same in both tables, Access automatically
fills in the Append To row with the names of the fields you're appending
records to. If some of the fields you're appending have a different field
name, you will have to specify to which field they should be added from
the Append To row.
3971408.doc - 241 -
Since there isn't a field named No Tickets in the tblCustomerTours table,
Access doesn't automatically fill in the Append To row. You will have to
select the name of the field you want to to.
9. Click the Append To row in the No Tickets field, click the list arrow, and
select Number of Tickets.
This will append the fields from the No Tickets field in the
tblCaribbeanTours table to the Number of Tickets field in the
tblCustomerTours table. Move on to the next step and finish adding the
remaining fields that you want to append.
10.Double-click the Date, First Class, Smoker, Ship Via, and Cost fields in the
tblCaribbeanTours field list.
Note: As with any action query, you should always preview the results in
Datasheet view first. Click the View button on the toolbar to display the
results of the Append query in Datasheet view.
11.Click the View button on the toolbar to preview the results of the append
query in Datasheet view.
The append query displays the records it will add or append to the
tblCustomerTours table.
12.Click the View button on the toolbar to return to Design view and click the
Run button on the toolbar.
13.Click Yes.
14.Close the query without saving your changes and open the
qryToursByName query.
3971408.doc - 242 -
Notice the new tblCaribbeanTours records that have been added by the
append query.
3971408.doc - 243 -
Reference
OR...
5. CLICK OK.
6. ADD THE FIELDS YOU WANT TO APPEND AND IDENTIFY A
MATCHING FIELD IF ACCESS DOESN'T SUPPLY ONE.
7. CLICK THE VIEW BUTTON ON THE TOOLBAR TO VIEW THE
RESULTS OF THE QUERY OR THE RUN BUTTON ON THE TOOLBAR
AND CLICK YES TO CONFIRM THE ADDITION.
Make-Table Queries
3971408.doc - 244 -
Figure 6-33. Type the name of the table you're creating in
the Make Table dialog box
Figure 6-35. The query uses its results to create a new table.
Like all queries, a make-table query asks a question of the information in one or
more tables and then retrieves results. Instead of displaying the results,
however, a make-table query creates a new table with the results of the query.
Make-table queries are useful for:
In this lesson you will create a make-table query to create a table with
information about all China tour records.
1. Click the qryTourSales query and then click the Design button.
3971408.doc - 245 -
The query opens in Design view. First you need to add the fields that you
want to include in your new table.
2. Double-click the TourName field in the tblTours field list, the Number of
Tickets, Date, and Cost fields in the tblCustomerTours field list, and the
LastName and FirstName fields in the tblEmployees field list.
The make-table query will create a table with these fields, as shown in
Figure 6-34. Next you need to specify any limiting criteria.
Access will add the "quotation marks" around the text string "China" for
you. The make-table query will only include China tours when it creates
the new table.
4. Click the Query Type button list arrow and select Make-Table Query from
the list.
Access displays the Make Table dialog box, as shown in Figure 6-33. Here
you need to tell Access the name of the new table.
You're ready to have the make-table query create the new table. Preview
the results of the query first.
Note: As with any action query you should always preview the results in
Datasheet view first. Click the View button on the toolbar to display the
results of the make-table query in Datasheet view.
6. Click the View button on the toolbar to preview the results of the make-
table query in Datasheet view.
The make-table query displays the records it will use to create the new
tblChinaTours table.
3971408.doc - 246 -
7. Click the View button on the toolbar to return to Design view and click the
Run button on the toolbar.
8. Click Yes.
Access creates the new tblChinaTours table based on the results of the
make-table query, as shown in Figure 6-35. Now let's open the new table.
9. Close the query without saving your changes, click the Tables icon in the
Objects bar, and double-click the tblChinaTours table.
3971408.doc - 247 -
Reference
OR...
5. CLICK OK.
6. CLICK THE VIEW BUTTON ON THE TOOLBAR TO VIEW THE
RESULTS OF THE QUERY OR THE RUN BUTTON ON THE TOOLBAR
AND CLICK YES TO CONFIRM THE CREATION.
Update Queries
Figure 6-36. An query.
3971408.doc - 248 -
Figure 6-37. Access asks you to confirm the record update.
You can use an update query to change a pile of records at the same time. For
example, you could create an update query to lower prices by eight percent or
to change the sales representative for all your clients in Oregon from "Mr.
Potter" to "George Bailey." Just like other action queries, you create an update
query by first creating a select query and then converting the select query to an
update query.
In this lesson you will create an update query to raise the prices of all trips to
Europe by 10 percent.
1. From the Database window, click the Queries icon in the Objects bar and
click the New button.
3971408.doc - 249 -
The New Query dialog box appears.
The query design window and Show Table dialog box both appear. Here
you have to select the tables and/or queries you want to use in the
update query.
Now you need to convert the select query to an update query. Here's
how:
4. Click the Query Type button list arrow and select Update Query from the
list.
5. Double-click the TourID, Normal Price, and First Class Price fields in the
tblTours field list.
The next step is a little bit trickyyou have to tell Access which fields to
update and how to update them. You want to raise the price of both the
Normal Price and First Class Price fields by 10 percentyou will have to
write an expression (or formula) in the Update To rows of both fields to
make this little bit of magic happen.
6. Click the Normal Price column's Update To row and type [Normal
Price]+([Normal Price]*.1).
So what does this confusing expression actually mean? Let's assume the
Normal Price for a record is $100. The expression would then look
something like this: [$100] + ([$100] * .1).
3971408.doc - 250 -
7. Click the First Class Price column's Update To row and type:
Next you need to specify any limiting criteria. You want to raise prices for
only those tours that are in Europe. Sadly, the only way to determine this
is by looking at the values in the tblTours table. Here are all the European
TourIDs: 1, 2, 3, and 9. You will have to create an OR statement in your
query to make sure you get them all.
This will select the record whose TourID is "1," but what about the rest?
9. Press the (down arrow key) to select the TourID field's second Criteria
row (the or row) and type 2.
This will select the records whose TourID is "2." Go to the next step and
finish adding the rest of the OR criteria.
10. Press the (down arrow key) to select the TourID field's third Criteria row,
type 3, press the (down arrow key) to select the TourID field's fourth
Criteria row and type 9.
Compare your query to the one in Figure 6-36. Look the same? Let's run
the query.
Access asks about the updating the selected records, as shown in Figure
6-37.
12.Click Yes.
Access updates the selected records by raising both their Normal Price
and First Class Price fields by 10 percent. Let's open the new table.
13.Close the query without saving your changes, click the Tables icon in the
Objects bar, and double-click the tblTours table.
3971408.doc - 251 -
Compare your table with Figure 6-38. Notice that the prices of four
European tours have been increased by ten percent.
Reference
OR...
Review
3971408.doc - 252 -
Lesson Summary
A Quick Review
To Create a Query in Design View: Click the Queries icon in the Objects bar,
then double-click Create query in Design view. Select the table or query you
want to use and click Add. Repeat as necessary for additional tables or queries
that you want to add to the query and click Close when you're finished. Double-
click the fields that you want to appear in the query or click and drag the fields
onto the design grid. In the design grid, enter any desired search criteria for the
field in the Criteria row and/or click the Sort box list arrow for the field and a
sort order. Click the Save button on the toolbar, click Yes to save the query,
enter a query name, and click OK.
• Select queries
• Parameter queries
• Crosstab queries
• Make-table queries
• Append queries
• Delete queries
• Update queries
• Union queries
To Create a Multiple-Table Query in Design View: Click the Queries icon in the
Objects bar, then double-click Create query in Design view. Select the table or
query you want to use and click Add. Repeat as necessary for additional tables
or queries that you want to add to the query and click Close when you're
finished. If Access doesn't automatically join the tables, click the related field in
the first table and drag it to the related field in the second table. Repeat as
necessary to connect all the tables. Double-click the fields that you want to
appear in the query or click and drag the fields onto the design grid. In the
design grid, enter any desired search criteria for the field in the Criteria row
and/or click the Sort box list arrow for the field and select a sort order. Click the
3971408.doc - 253 -
Save button on the toolbar, click Yes to save the query, enter a query name,
and click OK.
To Create an IIF (IF...THEN) Function: Display the query in Design view. Click
the Field row of a blank column in the design grid, enter the field name followed
by a : (colon) and type the expression using the syntax IIf(?expr?, ?
truepart?, ?falsepart?) (or you can use the Expression Builder to help you
create the IIf expression).
3971408.doc - 254 -
To View Top or Bottom Values: Display the query in Design view, click the
appropriate Sort field, and select either Ascending (displays bottom values) or
Descending (displays top values). Select an option from the Top Values list on
the toolbar.
Parameter Queries
To Create a Parameter Query: Display the query in Design view, click the
Criteria row for the field you want to use for your parameter criteria and enter
the text of the prompt, surrounded by square brackets [ ].
To Use the Find Duplicates Query Wizard: In the Database window, click the
Queries icon in the Objects bar and click the New button. Select Find Duplicates
Query Wizard and click OK, then select the table or query you want to search
and click Next. Double-click the field(s) that may contain the duplicate values
and click Next. Double-click any additional fields that you want to appear in the
query results, click Next, and then click Finish.
To Use the Find Unmatched Query Wizard: From the Database window, click the
Queries icon in the Objects bar and click the New button. Select Find
Unmatched Query Wizard and click OK, select the table whose values you want
to display and click Next. Select the table that contains the related records, click
Next, specify the related fields that join the two tables, then click the
button to join the two tables and click Next. Double-click any additional fields
that you want to appear in the query results, click Next, and then click Finish.
Crosstab Queries
To Create a Crosstab Query: In the Database window, click the Queries icon in
the Objects bar and click the New button, then select Crosstab Query Wizard
and click OK. Select the table or query you want to use in the crosstab query
and click Next. Select the field you want to use as the row heading, click Next,
select the field you want to use as the column heading, and click Next. Select
the field you want to summarize, the type of calculation you want to use to
summarize the field, click Next, type a name for the crosstab query, and click
Finish.
3971408.doc - 255 -
Delete Queries
To Create a Delete Query: In the Database window, click the Queries icon in the
Objects bar and click the New button. Select Design view and click OK. Add the
appropriate tables and/or queries and click Close, then connect any unrelated
tables. Click the Query Type button list arrow on the toolbar and select Delete
Query or select Query Delete Query from the menu. Click the View button to
view the results of the delete query. If you're satisfied that the appropriate
records will be deleted, click the Run button on the toolbar and click Yes to
confirm the deletion.
Append Queries
To Create an Append Query: Create a new query, select Design view, and click
OK. Click the tables and/or queries you want to use in the append query, click
Add, and then click Close when you're finished. Click the Query Type button list
arrow on the toolbar and select Append Query or select Query Append Query
from the menu. Select the table to which you want to add the results of the
query. If you select an existing table, click one of the following options: Current
Database (if the table is in the currently open database) or Another Database
(and type the name of the other database, including the path, if necessary).
Click OK, then add the fields you want to append and identify a matching field if
Access doesn't supply one. Click OK and click the View button on the toolbar to
view the results of the query or the Run button on the toolbar to append the
records.
Make-Table Queries
Update Queries
3971408.doc - 256 -
To Create an Update Query: Create a new query in Design view, then select the
tables and/or queries you want to use in the update query. Click the Query Type
button list arrow on the toolbar and select Update Query or select Query
Update Query from the menu. Double-click the fields that you want to appear in
the query or click and drag the fields onto the design grid. Enter an expression
to update the selected field and enter any criteria, if needed, to select which
records should be updated. Click the View button to view the results of the
update query. If you're satisfied that the appropriate records will be updated,
click the Run button on the toolbar to update the records.
Quiz
1. Which of the following criterion is NOT written using the proper syntax?
A. "Harris"
B. Between 1/1/2000 and 12/31/2000
C. NO VALUE
D. 500
2. Which of the following types of queries are action queries? (Select all that
apply.)
A. Parameter queries.
B. Append queries.
C. Update queries.
D. Crosstab queries.
3. Which of the following expressions is NOT written in the correct syntax?
A. [Order Total]*[Tax Rate]
B. "Order Total"*0.1
C. [tblCustomerTours]![Cost]*[tblEmployees]![Commission]
D. 100+10
4. If you are having trouble remembering how to write expressions using the
correct syntax, you can use the Expression Builder to help you create the
expression. (True or False?)
5. Rebate: IIF([Age]65,"Senior","Adult") This expression is an example of:
A. Something I learned back in high school algebra and thought I
would never see again.
B. A financial expression.
C. Something that belongs in a Microsoft Excel book.
D. A conditional expression.
6. A query prompts a user for a date and then displays only records that
contain the specified date. Which type of query is this?
3971408.doc - 257 -
A. A parameter query.
B. A crosstab query.
C. An action query.
D. An update query.
7. You must create a report if you want to calculate totals for a group of
records, as queries can't perform this task. (True or False?)
8. A query summarizes information in a grid, organized by regions and
months. Which type of query is this?
A. A parameter query.
B. A crosstab query.
C. An action query.
D. An update query.
9. Your company finally agreed to buy you a nifty 3COM Palm palmtop. Now
you want to extract your clients from the company's database and put
them into a separate table that you can export to your Palm. Which type
of query could help you accomplish this task?
A. A parameter query.
B. A crosstab query.
C. An update query.
D. A make-table query.
10.If you are creating a crosstab query, what must the table you are
querying contain?
A. At least one text field.
B. At least one number field.
C. More than 100 records.
D. Lots of confusing information.
11.How can you add a table to the query design window?
A. Select Edit Add Table from the menu.
B. Click the Show Table button on the toolbar.
C. Select the table from the Table list on the toolbar.
D. Select Tools Add Table from the menu.
12.You want a query to calculate the total sales for your employees. How can
you do this from the query design window?
A. Click the Totals button on the toolbar. In the Total row select "Group
By" under the Employee field and "Sum" under the Sales field.
B. Click in the Sales field and click the AutoSum button on the toolbar.
C. You need to export this information to Microsoft Excel and calculate
it there.
3971408.doc - 258 -
D. Click in the Sales field and select Tools AutoSum from the menu.
Homework
3971408.doc - 259 -