Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

4.1 Introduction: Using Queries To Get The Information You Need

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Access Tutorial 4: Basic Queries Using QBE

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?

© Michael Brydon (brydon@unixg.ubc.ca)


Last update: 25-Aug-1997 Home Previous 1 o f 27 Next
4. Basic Queries Using QBE Tutorial exercises

 What is a non-updatable recordset? How do I 4.3.2 Five basic query operations


tell whether a query results in a non-
4.3.2.1 Projection
updatable recordset?
Projecting a field into a query simply means includ-
4.3 Tutorial exercises ing it in the query definition. The ability to base a
query on a subset of the fields in an underlying table
4.3.1 Creating a query (or tables) is particularly useful when dealing with
tables that contain some information that is confiden-
• Use the New button in the Queries pane of the
tial and some that is not confidential. For instance,
database window to create a new query as
the Employees table you created in Tutorial 2 con-
shown in Figure 4.1.
tains a field called Salary. However, most of the
• Add the Courses table to the query as shown in
queries seen by end-users would not include this
Figure 4.2.
information, thereby keeping it private.
• Examine the basic elements of the query design
• Perform the steps shown in Figure 4.4 to project
screen as shown in Figure 4.3.
the DeptCode, CrsNum, and Title fields into
• Save your query (Control-S) using the name
the query definition.
qryCourses.
• Select View > Datasheet from the menu to see
the results of the query. Alternatively, press the
datasheet icon ( ) on the tool bar.

Home Previous 2 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

FIGURE 4.1: Create a new query.

 the
Select the Queries tab in
database window.

 create
Press the New button to
a new query.

Avoid the use of the query wizard


at this point. Queries are very
important and it is best to learn to
create them from scratch.

Home Previous 3 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

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.

Home Previous 4 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

FIGURE 4.3: The basic elements of the query design screen.

The upper If you “lose” tables in the top


pane contains pane, you have to use the
field lists for horizontal and vertical scroll
the tables on bars to return to the upper-left
which the corner of the pane.
query is based.
Field row— shows the name of the
fields included in the query.

The lower Table row— shows the name of the


pane contains table that the field comes from. To get
the actual table names in version 2.0, select View
query > Table Names from the menu.
definition.
Sort row— allows you to specify the
order in which the records are
Criteria row — allows you Show boxes— determine displayed
to specify criteria for whether fields included
including or excluding in the query are actually
records from the results set. displayed.

Home Previous 5 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

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.

To project all the fields in the


Courses table (including
any that might be added to the
table after this query is
created) drag the asterisk (*)
into the query definition grid.

To save time when


projecting fields, select more
than one field at once (by
holding down the Control
key) and dragging all the
fields as a group.

Home Previous 6 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

• Select View > Query Design to return to design 4.3.2.3 Selection


mode. Alternatively, press the design icon ( ) You select records by specifying conditions that each
on the tool bar. record must satisfy in order to be included in the
4.3.2.2 Sorting results set. In “query-by-example” you enter exam-
ples of the results you desire into the criteria row.
When you use a query to sort, you do not change the
• Perform the steps shown in Figure 4.6 to select
physical order of the records in the underlying table
only those courses with a DeptCode = “COMM”.
(that is, you do not sort the table). As a result, differ-
ent queries based on the same table can display the 4.3.2.4 Complex selection criteria
records in different orders. It is also possible to create complex selection criteria
• Perform the steps shown in Figure 4.5 to sort the using Boolean constructs such as AND, OR, and
results of qryCourses by DeptCode and NOT.
CrsNum. • Project the Credits field into the query.
• Perform the steps shown in Figure 4.7 to create a
Since a query is never used to display data to
query giving the following result:
a user, you can move the fields around within
“Show the department, course number, and title
the query definition to get the desired sorting
of all courses in the Commerce department for
precedence. You then reorder the fields in the
which the number of credits is greater than
form or report for presentation to the user.
three.”

Home Previous 7 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

FIGURE 4.5: Sorting the results set on one or more fields.

 and
Select “ascending” for the DeptCode field
“descending” for the CrsNum field.

When multiple sort fields are specified,


the sorting precedence is from left to
right (e.g., DeptCode is sorted first
 the
View the results and notice
order of the records.
and then CrsNum is sorted within each
set of matching DeptCodes).

Home Previous 8 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

FIGURE 4.6: Select a subset of records from the Courses table matching a specific criterion.

 ofType the expression “COMM” in the criteria row


the DeptCode field. You could also type
= “COMM” but the equal sign is always implied
unless another relational operator is used.

 matching
View the results. Only records
the criteria are shown.

Home Previous 9 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

FIGURE 4.7: Select records using an AND condition.

When multiple criteria are placed in the


same row, they are AND-ed. In other
words, the records in the results set
 Show the result. must satisfy DeptCode = “COMM”
AND Credits > 3.

Note that the number


3 is not in quotation
marks whereas the
string of characters
“COMM” is.

 Uncheck the “show”


box (Credits is
used as a criterion but
 “COMM”
Enter the first criteria:
 >In the
3
same row, enter the second it is not displayed in
the results set)

Home Previous 10 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

• 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.)

Home Previous 11 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

FIGURE 4.8: Select records using an AND and an OR condition.

When multiple criteria are placed in


different rows, then they are OR-ed. In
other words, the records in the results set
must satisfy DeptCode = “COMM”
OR (DeptCode = “CRWR” AND
Credits > 3).

 criterion
Enter the Credits
in the
 DeptCode
Enter the second row.
criteria in
different rows.

Home Previous 12 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

FIGURE 4.9: Create a query that joins Courses and Sections.

 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.

Home Previous 13 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

FIGURE 4.10: Move a field within the query definition grid.

 “column
Click once on the grey
selector”
above the field you
want to move (if
properly selected, the
column turns black).

To delete a field from


the query definition,
select it and press the
Delete key.

 itsDragnewthelocation.
selected column to

Home Previous 14 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

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,

Home Previous 15 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

FIGURE 4.11: Create a calculated field based on two other fields.

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.

Home Previous 16 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

FIGURE 4.12: The resulting calculated field.

The name of the


calculated field shows in
the field selector.

When the zoom window is


closed, Access adds square
brackets to the field names.
Since the field names in this
example do not contain
spaces, the brackets are
optional.

The ampersand operator (&) simply tacks


CrsNum onto the end of DeptCode.

Home Previous 17 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

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

Home Previous 18 o f 27 Next


4. Basic Queries Using QBE Tutorial exercises

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”)

Home Previous 19 o f 27 Next


4. Basic Queries Using QBE Discussion

4.3.4 Errors in queries 4.4 Discussion


It may be that after defining a calculated field, you
get the “enter parameter” dialog box shown in 4.4.1 Naming conventions for database
Figure 4.14 when you run the query. This occurs objects
when you spell a field name incorrectly. Access can- There are relatively few naming restrictions for data-
not resolve the name of the misspelled field and thus base objects in Access. However, a clear, consistent
asks the user for the value. To eliminate the problem, method for choosing names can save time and avoid
simply correct the spelling mistake. confusion later on. Although there is no hard and fast
FIGURE 4.14: A spelling error in a calculated naming convention required for the assignment, the
field. following points should be kept in mind:
• Use meaningful names — An object named
Table1 does not tell you much about the con-
Access cannot find the tents of the table. Furthermore, since there is no
field named Creditz practical limit to the length of the names, you
should not use short, cryptic names such as
s96w_b. As the number of objects in your data-
base grows, the time spent carefully naming your
objects will pay itself back many times.

Home Previous 20 o f 27 Next


4. Basic Queries Using QBE Discussion

• 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”

Home Previous 21 o f 27 Next


4. Basic Queries Using QBE Discussion

Table 4.1: A suggested naming convention for yields the result


Access database objects. First stringSecond string
However, if a space is include within the quotation
Object type Prefix Example marks of the second string (“ Second string”),
table (none) OrderDetails the result is:
query qry qryNonZeroBackOrders First string Second string
parameter pqry pqryItemsInOrder
query 4.4.3 Using queries to populate tables
form frm frmOrders on the “many” side of a
relationship
sub form sfrm sfrmOrderDetails
In Section 4.3.2.5, you added a record to the Sec-
switchboard swb swbMainSwitchboard
form tions table to demonstrate the automatic lookup
feature of Access. However, a common mistake
report rpt rptInvoice
when creating queries for entering data into tables
sub report srpt srptInvoiceDetails on the “many” side of a relationship is to forget to
macro mcr mcrOrders project the table’s foreign key. That is, faced with two
Visual Basic bas basUtilities tables containing the fields DeptCode and CrsNum,
module you project the fields from the wrong table (the “one”
side) into your query definition.

Home Previous 22 o f 27 Next


4. Basic Queries Using QBE Discussion

To illustrate the problem, do the following: 4.4.4 Non-updatable recordsets


• Open the qryCatalogNum query and make the Another problem that sometimes occurs when creat-
changes shown in Figure 4.15. ing join queries is that the query is not quite right in
• Attempt to save the new section of “MUSC 105” some way. In such cases, Access will allow you to
as shown in Figure 4.16. view the results of the query, but it will not allow you
There are two ways to avoid this error when deciding to edit the data.
which fields to project into your join queries: In this section, will look at a nonsensical query that
1. Always show the table names when creating a results from an incompletely specified relationship.
query based on more than one table. That way, As you will probably discover, however, there are
you can quickly determine whether the query many different way to generate nonsensical queries.
makes sense. • Create a new query called qryNonUpdate
2. Always ask yourself: “What is the purpose of this based on the Courses and Sections tables.
query?” If the answer is: “To add new records to • Delete the CrsNum relationship but leave the
the Sections table,” you automatically have to DeptCode relationship intact, as shown in
include all the fields from the Sections table. Figure 4.17.
Fields from the Courses table are only shown The result of this query is that every section in a
for validation purposes. Commerce course will be associated with every
Commerce course. Since allowing the user to update

Home Previous 23 o f 27 Next


4. Basic Queries Using QBE Discussion

FIGURE 4.15: Create a data-entry query without a foreign key.

In version 2.0 you have to


 Reorder the fields (by
dragging and dropping) so
select View > Table
Names to display the
that DeptCode and table row.
CrsNum are on the far left.

 DeptCode
Change the source table for
and CrsNum
from Sections to
Courses.

 Switch to datasheet mode


and attempt to add a new
section of “MUSC 105”.

Home Previous 24 o f 27 Next


4. Basic Queries Using QBE Discussion

FIGURE 4.16: The result of attempting to save a record in which the foreign key is missing

Since the fields are bound to the


Courses table, you are
attempting to replace the
current record in the Courses
table with “MUSC 105”. But
since a “MUSC 105” already
exists, you get an error.

 new
Attempt to save the
section by
clicking its record
selector.

Home Previous 25 o f 27 Next


4. Basic Queries Using QBE Discussion

FIGURE 4.17: Create a non-updatable recordset.

 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.

Home Previous 26 o f 27 Next


4. Basic Queries Using QBE Application to the assignment

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)

Home Previous 27 o f 27 Next

You might also like