Introduction To Microsoft Access II: Relationships and Queries
Introduction To Microsoft Access II: Relationships and Queries
Where to Find Help When You Need It
Relationships ............................................................................................................................................... 1
Define Relationships between tables........................................................................................................... 1
Referential Integrity .................................................................................................................................... 2
Queries ........................................................................................................................................................ 3
Design View................................................................................................................................................ 3
Create a Query............................................................................................................................................. 4
Entering Criteria.......................................................................................................................................... 4
Using Compound Criteria ........................................................................................................................... 5
Sorting Data in a Query............................................................................................................................... 5
Using Computed Fields in a Query............................................................................................................. 5
Calculating Statistics ................................................................................................................................... 6
Grouping...................................................................................................................................................... 6
Saving a Query............................................................................................................................................ 6
Appendix A ................................................................................................................................................. 7
Appendix B ................................................................................................................................................. 9
Microsoft Access II: Relationships and Queries
Relationships
After you've set up different tables for each subject in your database, you need a way of telling
Microsoft Access how to bring that information back together again. The first step in this process is to
define relationships between your tables. After you've done that, you can create queries, forms, and
reports to display information from several tables at once.
The kind of relationship that Microsoft Access creates depends on how the related fields are defined:
• A one-to-many relationship is created if only one of the related fields is a primary key or has a
unique index.
• A one-to-one relationship is created if both of the related fields are primary keys or have unique
indexes.
• A many-to-many relationship is really two one-to-many relationships with a third table whose
primary key consists of two fields - the foreign keys from the two other tables.
ÎIn most cases, you drag the primary key field (which is displayed in bold text) from one table to a
similar field (often with the same name) called the foreign key in the other table. The related fields don't
have to have the same names, but they must have the same data type (with two exceptions) and contain
the same kind of information. In addition, when the matching fields are Number fields, they must have
the same Field Size property setting.
7. The Relationships dialog box is displayed. Check the field names displayed in the two columns to
ensure they are correct. You can change them if necessary.
8. Click the Create button to create the relationship.
9. When you close the Relationships window, Microsoft Access asks if you want to save the layout.
Whether you save the layout or not, the relationships you create are saved in the database.
Page 1
Microsoft Access II: Relationships and Queries
Referential Integrity
Referential integrity is a system of rules that Access uses to ensure that relationships between records in
related tables are valid, and that you don't accidentally delete or change related data. You can set
referential integrity when all of the following conditions are met:
• The matching field from the primary table is a primary key or has a unique index. A unique index is
an index defined by setting a field's Indexed property to Yes (No Duplicates). A unique index will
not allow duplicate entries in the indexed field. Setting a field as the primary key automatically
designates the field as a unique index.
• The related fields have the same data type. There are two exceptions. An AutoNumber field can be
related to a Number field with a FieldSize property setting of Long Integer, and an AutoNumber
field with a FieldSize property setting of Replication ID can be related to a Number field with a
FieldSize property setting of Replication ID.
• Both tables belong to the same Microsoft Access database. If the tables are linked tables, they must
be tables in Microsoft Access format, and you must open the database in which they are stored to set
referential integrity. Referential integrity can't be enforced for linked tables from databases in other
formats.
When referential integrity is enforced, you must observe the following rules:
• You can't enter a value in the foreign key field of the related table that doesn't exist in the primary
key of the primary table. However, you can enter a Null value in the foreign key, specifying that the
records are unrelated.
− For example, you can't have an order that is assigned to a customer that doesn't exist, but you
can have an order that is assigned to no one by entering a Null value in the CustomerID field.
• You can't delete a record from a primary table if matching records exist in a related table.
− For example, you can't delete an employee record from the Employees table if there are orders
assigned to the employee in the Orders table.
• You can't change a primary key value in the primary table, if that record has related records.
− For example, you can't change an employee's ID in the Employees table if there are orders
assigned to that employee in the Orders table.
If you want to enforce these rules for a relationship, select the Enforce Referential Integrity check box
when you create the relationship. If referential integrity is enforced and you break one of the rules with
related tables, Access displays a message and doesn't allow the change.
You can override the restrictions against deleting or changing related records and still preserve
referential integrity by setting the Cascade Update Related Fields and Cascade Delete Related Records
check boxes.
• When the Cascade Update Related Fields check box is set, changing a primary key value in the
primary table automatically updates the matching value in all related records.
• When the Cascade Delete Related Records check box is set, deleting a record in the primary table
deletes any related records in the related table.
Page 2
Microsoft Access II: Relationships and Queries
Queries
Access offers the ability to answer questions. The answer to these questions, and many more are found
in the database, and Access can find the answers quickly. When you pose a question to Access, the
question is called a query. A query is simply a question represented in a way that Access can understand.
You use queries to view, change, and analyze data in different ways. You can also use them as the
source of records for forms and reports. The most common type of query is a select query. A select
query retrieves data from one or more tables using criteria you specify, and then displays it in the order
you want.
ÎCAREFUL: Making changes to a query record or deleting a record in a query will affect the same
record in the related table.
Design View
The design grid is used to setup a query in Design view.
Run button Add Tables Totals command
Field List
Sort row
Design Grid
Show
check box
Criteria Box
Page 3
Microsoft Access II: Relationships and Queries
• In the bottom section, each row will consist of a row heading to describe its purpose. You will find
the following:
− Field for the field name. Calculations can also be made in this cell to display the result based on
an expression. (See the Calculated Fields section for examples.)
− Table for the table or query name.
− Sort for sorting the query by ascending or descending.
− Show to select whether the data in that field is displayed or not.
− Criteria to enter the criteria for the query.
− By going into the View menu and clicking Totals, the Totals row heading will be added to the
design grid. Click the drop-down arrow to display the results of a calculation in a field, based on
a predefined calculation such as, sum, average, count, minimum, maximum, standard deviation,
or variance. You choose one totals calculation for each field you want to calculate.
Create a Query
1. In the Objects Bar, click the Queries button, and then click New.
2. In the New Query dialog box, click Design View, and then click OK.
3. In the Show Table dialog box, click the tab that lists the objects whose data you want to work with.
4. Double-click the name of each object you want to add to the query, and then click Close.
5. If you have multiple tables or queries in the query, make sure they are connected to each other with a
join line so that Microsoft Access knows how the information is related. If they aren't connected,
create the join line yourself.
6. Add fields to the query by double-clicking the field names from the field list.
7. Refine your query by entering criteria, adding a sort order, creating calculated fields, computing the
sum, average, count, or another type of total on the data it retrieves, or otherwise modifying the
query's design.
8. To save the query, click Save on the toolbar. Enter a name and then click OK.
9. To see the results of the query, i.e. run the query, click the Run button on the toolbar.
Entering Criteria
To enter criteria, enter them on the Criteria row in the design gird below the field name to which the
criterion applies.
Text
To use text data in criteria, simply type the text in the Criteria row below the corresponding field name.
For example, to indicate that the student’s Last Name is ‘Jones’, you would type Jones in the Criteria
row below the Last Name field.
Wildcards
Two special wildcards are available. The first of the two wildcards, the asterisk (*), represents any
collection of characters. For example in the Last Name field criteria, typing Sm*, means any last name
Page 4
Microsoft Access II: Relationships and Queries
that starts with Sm followed by any collection of characters. The other wildcard symbol is the question
mark (?) which represent any single character. For example, T?m, could be Tim or Tom.
Numeric Data
To enter a number in a criterion, type the number without any dollar signs or commas.
Comparison Operators
If you want a result other than an exact match, you must enter the appropriate comparison operator. The
comparison operator are > (greater than), < (less than), >= (greater than or equal to), <= (less than or
equal to), and NOT (not equal to).
In an AND criterion, each individual criteria must be true in order for the compound criteria to be true.
For example you would use an AND criterion to find students that are Freshman AND who are
Economics majors. To combine criteria with AND, place the criteria on the same line.
In an OR criterion, is true if either individual criteria is true. For example you would use an OR criterion
to find students that are Freshman OR who are Economics majors. To combine criteria with OR, the
criteria must go on separate lines in the Criteria area.
The computations you can do are addition (+), subtraction (-), multiplication (*), or division (/). You can
use parentheses in you computation to indicate which computation should be done first.
Page 5
Microsoft Access II: Relationships and Queries
Calculating Statistics
There are nine built in aggregate functions for Access. For a list of the built in aggregate functions and
how they are used see Appendix B. To use any of these in a query, you include it in the Total row in the
design grid. By default the Total row does not appear in the grid. To include it, click Totals on the
toolbar.
Grouping
Often statistics are used in combination with grouping. For example you may want the average GPA for
all students in each major of study. Grouping means creating groups of records that share some common
characteristic. In this example, when grouped by major, one group would by Business Administration
students, one group would be Finance students, and another group would be Economic students. The
calculation of average GPA would be made for each group. To indicate groping in the query, select the
Group By as the entry in the Total row for the field to be used for grouping. Then perform the aggregate
function, such as average, on the field to computer, GPA.
Saving a Query
In many cases, you will construct a query you will want to use again. By saving the query you will
eliminate the need to repeat the design of that query.
Once you have saved a query, you can use it any time in the future by opening it. To open a saved query,
click the Queries tab in the Database window, select the query, and then click Open.
The query is run against the current database, thus if changes have been made to the data since the last
time you ran it, the results of the query may be different.
Page 6
Microsoft Access II: Relationships and Queries
Appendix A
Examples of Criteria Expressions in Queries
Page 7
Microsoft Access II: Relationships and Queries
Page 8
Microsoft Access II: Relationships and Queries
Appendix B
About aggregate functions and other options in the query design grid's Total row
Select To
Group By Define the groups you want to perform the
calculations for. For example, to show total sales by
category, select Group By for the CategoryName
field.
Expression Create a calculated field that includes an aggregate
function in its expression. Usually, you create a
calculated field when you want to use multiple
functions in an expression.
Where Specify criteria for a field you aren't using to define
groupings. If you select this option for a field,
Microsoft Access will hide the field in the query
results by clearing the Show check box.
First The First and Last functions simply return the value
of a specified field in the first or last record,
Last respectively, of the result set returned by a query.
Because records are usually returned in no particular
order (unless the query includes an ORDER BY
clause), the records returned by these functions will
be arbitrary.
Page 9