4.1 Introduction: Using Queries To Get The Information You Need
4.1 Introduction: Using Queries To Get The Information You Need
4.1 Introduction: Using Queries To Get The Information You Need
4.1 Introduction: Using queries to Once a query is defined, it can be used in exactly the
get the information you need same way as a table. Because of this, it is useful to
think of queries as “virtual tables”. Similarly, in some
At first glance, it appears that splitting information DBMSes, queries are called “views” because they
into multiple tables and relationships creates more of allow different users and different applications to
a headache than it is worth. Many people like to have different views of the same data.
have all the information they need on one screen
(like a spreadsheet, for instance); they do not want to
4.2 Learning objectives
have to know about foreign keys and relationships
and so on. Do queries contain any data?
Queries address this problem. They allow the user to How do I create a query?
join data from one or more tables, order the data in What can I do with a query?
different ways, calculate new fields, and specify cri-
How do I create a calculated field?
teria to filter out certain records.
Why does Access add square brackets
The important thing is that the query itself contains
around field names?
no data—it merely reorganizes the data from the
table (or tables) on which it is built without changing What names should I give the queries I
the “underlying tables” in any way. create?
What does the ampersand operator (&) do?
the
Select the Queries tab in
database window.
create
Press the New button to
a new query.
FIGURE 4.2: Add tables to your query using the “show table” window.
byAddselecting
the Courses table to the query
it and pressing Add
(alternatively, you can simply double-
click on the table you want to add).
table”
Press Close when done (the “show
window is “modal”—you can
The “show table” window is always
available from the Query > Show Table
not do anything else in Access until a menu. Alternatively, you can press the
modal window is closed). “show table” button on the tool bar.
FIGURE 4.4: Project a subset of the available fields into the query definition.
drag
Select the field you wish to project and
it into the query definition grid.
Alternatively, double-click the field.
and
Select “ascending” for the DeptCode field
“descending” for the CrsNum field.
FIGURE 4.6: Select a subset of records from the Courses table matching a specific criterion.
matching
View the results. Only records
the criteria are shown.
• Perform the steps shown in Figure 4.8 to create a • Project Title from the Courses table and
query giving the following result: DeptCode, CrsNum, Section and Catalog-
“Show the department, course number, and title Num from the Sections table (see Figure 4.9).
of all courses from the Commerce department • Follow the instructions in Figure 4.10 to move
and also show those from the Creative Writing CatalogNum to the far left of the query definition
department for which the number of credits is grid.
greater than three.” Access performs an automatic lookup of information
4.3.2.5 Joining from the “one” side of the relationship whenever the
a valid value is entered into the foreign key of the
In Tutorial 3, you were advised to break you informa-
“many” side of the relationship. To see how this
tion down into multiple tables with relationships
works, create a new section of “MUSC 105”:
between them. In order to put this information back
• Scroll to the bottom of the query in datasheet
together in a usable form, you use a join query.
mode and click on the department field.
• Close qryCourses.
• Enter “MUSC”.
• Open the relationships window and ensure you
• Enter “105” in the course number field.
have a relationship defined between Courses
and Sections. If you do not, create one now (do Once Access knows the DeptCode and CrsNum of
not forget to enforce referential integrity). a section, it can uniquely identify the course that the
• Create a new query called qryCatalogNum section belongs to (which means it also knows the
based on the Courses and Sections tables. values of Title, Credits, Activity, etc.)
criterion
Enter the Credits
in the
DeptCode
Enter the second row.
criteria in
different rows.
Note
Bring Courses and Sections into the query.
that the relationship between the tables is
inherited from the relationship window.
the
Project fields from both tables into
query definition.
“column
Click once on the grey
selector”
above the field you
want to move (if
properly selected, the
column turns black).
itsDragnewthelocation.
selected column to
4.3.3 Creating calculated fields the expression involves two fields from the Courses
A calculated field is a “virtual field” in a query for table (DeptCode and CrsNum) and the ampersand
which the value is a function of one or more fields in operator (see Section 4.4.2 for more information on
the underlying table. To illustrate this, we will create using the ampersand operator).
two calculated fields: • Create a new query called qryCourseLengths
based on the Courses table.
1. one to combine DeptCode and CrsNum into one
• Follow the instructions in Figure 4.11 to create
field,
the calculated field Course
2. one to translate the Credits field into a dichoto-
• Run the query to verify the results, as shown in
mous string variable (full year or half
Figure 4.12.
year).
The syntax of a calculated field is always the same: When you use field names in expressions,
<calc field name>: <definition> Access normally adds square brackets. This
For example, the syntax for the calculated field is not cause for concern because in Access,
called Course is: square brackets simply indicate the name of a
Course: DeptCode & CrsNum field (or some other object in the Access envi-
ronment). However, if your field name con-
The calculated field name can be just about any-
tains blank spaces (e.g., Dept Code), the
thing, as long as it is unique. The definition is any
square brackets are NOT optional—you must
expression that Access can evaluate. In this case,
The zoom window provides more room to type than the tiny
space in the query definition grid. Invoke the zoom window
by moving to the area of the grid in which you wish to type
and either right-click or press the Shift-F2 keys.
the
Put the cursor in
Field row of
the first column
and invoke the
zoom window.
and
Type in the name
the definition Press OK when you
of the calculated have finished typing
field. The name the expression.
cannot be the same
as that of an
existing field.
type them every time you use the field name three credits is a full-year course). To do this, we will
in an expression. use the “immediate if” (iif) function.
• Search on-line help for information about the
4.3.3.1 Refining the calculated field iif() function.
Instead of having DeptCode and CrsNum run Basically, the function uses the following syntax:
together in the new Course field, you may prefer to iif(<expression>, <true part>,
have a space separating the two parts. <false part>)
• Edit the Courses field by clicking on the field row to implement the following logic:
and invoking the zoom box.
IF <expression> = TRUE THEN
• Add a space (in quotation marks) between the
RETURN <true part>
two constituent fields:
ELSE
Course: DeptCode & ” ” & CrsNum
RETURN <false part>
• Switch to datasheet mode to see the result.
END IF
4.3.3.2 A more complex calculated field • Create a new calculated field called Length:
To create a calculated field that maps Credits to a Length: iif(Credits > 3, “full
dichotomous string variable, we need a means of year”, “half year”)
testing whether the value of Credits exceeds a • Verify the results, as shown in Figure 4.13.
certain threshold (e.g., any course with more than
FIGURE 4.13: Create a calculated field using the “immediate if” function
Length:
Create a calculated field called Length with the following expression:
iif(Credits>3, “full year”, “half year”)
• Use capitalization rather than spaces to separate • Stick to standard alphanumeric characters — You
words — Unlike many database systems, Access should limit yourself to the characters [A...Z],
allows spaces in object names. However, if you [a...z], [0...9], and perhaps underscore (_) and
choose to use spaces, you will have to enclose dash (-). Although Access allows you to use virtu-
your field names in square brackets whenever ally any character, undocumented problems have
you use them in expressions (e.g., [Back been encountered in the past with non-alphanu-
Orders]). As such, it is slightly more efficient to meric characters such as the pound sign (#).
use a name such as BackOrders than Back Table 4.1 shows a suggested naming convention for
Orders. Access database objects (you will discover what
• Give each type of object a distinctive prefix (or these objects are in the course of doing the tutorials).
suffix) — This is especially important in the con-
text of queries since tables and queries cannot 4.4.2 The ampersand (&) operator
have the same name. For example, you cannot
The ampersand operator is like any other operator
(e.g., +, -, ×, ÷) except that it is intended for use on
have a table named BackOrders and a query
named BackOrders. However, if all your query
strings of characters. What the ampersand does is
names are of the form qryBackOrders, then
simply add one string on to the end of another string
distinguishing between tables and queries is
(hence its other name: the “concatenation” operator).
straightforward.
For example, the expression
“First string” & “Second string”
DeptCode
Change the source table for
and CrsNum
from Sections to
Courses.
FIGURE 4.16: The result of attempting to save a record in which the foreign key is missing
new
Attempt to save the
section by
clicking its record
selector.
view
Project fields from both tables and
the query in datasheet mode
(i.e., view the “recordset”).
Attempt to
change a value in
the recordset.
CrsNum
To create a nonsensical query, delete the
relationship by clicking on it Note the absence of the asterisk and the “new record”
and pressing the Delete key. Leave the row. This is a sure sign that the recordset is non-updatable.
DeptCode relationship intact.
the values in this recordset would create anomalies, should appear automatically. If they do not, see
Access designates the recordset as non-updatable. Section 4.4.3.
• Create a calculated field in your qryOrderDe-
A common mistake is to build data entry tails query that calculates the extended price
forms on nonsensical queries and to assume (quantity shipped × price) of each order detail.
that there is a mistake in the form when the • Enter the first order into your system by entering
forms do not work. Clearly, if a query is non- the information directly into tables or queries.
updatable, a form based on the query is also This involves creating a single Orders record
going to be non-updatable. A quick check for and several OrderDetails records. You must
a “new record” row in the query can save time also consult the Products and BackOrders
and frustration. tables to determine the quantity of each item to
ship.
4.5 Application to the assignment
• Create a query to sort the Products table by Entering orders into your system will be much
ProductID. less work once the input forms and triggers
• Create a query that joins the OrderDetails are in place. The goal at this point is to get
and Products tables. When you enter a valid you thinking about the order entry process
ProductID, the information about the product and ways in which it can be automated.
(such as name, quantity on hand, and so on)