You are on page 1of 150

Data Management I & II

Practical Tutorial

Adapted from www.holowczak.com


Part 1
Introduction to MS Access
2007/2010/2013

1
Introduction to the MS Access 2007/2010/2013 Tutorial
Welcome to the MS Access tutorial. This tutorial is designed to get the user up and running with MS
Access (henceforth simply “Access”) in a rapid fashion. The four basic modules of Access are
demonstrated: Tables, Forms, Reports and Queries. A business example is discussed first which
provides a background for developing a simple database.

Brief overview of Relational Databases and Database Applications


The first databases implemented during the 1960s and 1970s were based upon either flat data files or
the hierarchical or networked data models. These methods of storing data were relatively inflexible
due to their rigid structure and heavy reliance on applications programs to perform even the most
routine processing. In the late 1970s, the relational database model which originated in the academic
research community became available in commercial implementations such as IBM DB2 and Oracle.
The relational data model specifies data stored in relations that have some relationships among them
(hence the name relational). In relational databases such as Sybase, mySQL, Oracle, IBM DB2, MS
SQL Server and MS Access, data is stored in tables made up of one or more columns (Access calls a
column a field). The data stored in each column must be of a single data type such as Character
(sometimes called a “string”), Number or Date. A collection of values from each column of a table is
called a record or a row in the table. Different tables can have the same column in common. This
feature is used to explicitly specify a relationship between two tables. Values appearing in column A
in one table are shared with another table.

Below are two examples of tables in a relational database for a local bank:

Customer Table

CustomerID First Name Last Name Street Address City State Zip
Number Character Character Character Character Character Character
1001 Joseph Smith 123 Lexington Smithville KY 91232
1002 Alberta Jones 12 Davis Ave. Smithville KY 91232
1003 Nathanial Axe 443 Grinder Ln. Broadville GA 81992
1004 Paulina Builder 661 Parker Rd. Streetville GA 81990

Accounts Table

CustomerID AccountNumber AccountType DateOpened Balance


Number Number Character Date Number
1001 9987 Checking 10/12/1989 4000.00
1001 9980 Savings 10/12/1989 2000.00
1002 8811 Savings 01/05/1992 1000.00
1003 4422 Checking 12/01/1994 6000.00
1003 4433 Savings 12/01/1994 9000.00
1004 3322 Savings 08/22/1994 500.00
1004 1122 Checking 11/13/1988 800.00

The Customer table has 7 columns (CustomerID, First Name, Last Name, Street Address, City, State
and Zip) and 4 rows (or records) of data. The Accounts table has 5 columns (CustomerID,
AccountNumber, AccountType, DateOpened and Balance) with 7 rows of data.

2
Each of the columns conforms to one of three basic data types: Character, Number or Date. The data
type for a column indicates the type of data values that may be stored in that column.

• Number – may only store numbers, possibly with a decimal point. Can be positive or
negative.
• Character – may store numbers, letters and punctuation. Access calls this data type Text.
• Date – may only store date and time data.

In some database implementations other data types exist such as Images (for pictures or other data).
However, the above three data types are most commonly used.

Notice that the two tables share the column CustomerID and that the values of the CustomerID
column in the Customer table are the same the values in the CustomerID column in the Accounts
table. This relationship allows us to specify that the Customer Nathanial Axe has both a Checking
and a Savings account that were both opened on the same day: December 1, 1994.

Another name given to such a relationship is Master/Detail. In a master / detail relationship, a single
master record (such as Customer 1003, Nathanial Axe) can have many detail records (the two
accounts) associated with it.

In a Master / Detail relationship, it is possible for a Master record to exist without any Details.
However, it is impossible to have a Detail record without a matching Master record. For example, a
Customer may not necessarily have any account information at all. However, any account
information must be associated with a single Customer.

Each table also must have a special column called the Key that is used to uniquely identify rows or
records in the table. Values in a key column (or columns) may never be duplicated. In the above
tables, the CustomerID is the key for the Customer table while the AccountNumber is the key for the
Accounts table.

3
A Business Example
In this section, we will outline a business example that will be used as a basis for the examples
throughout the tutorial. In organizations, the job of analyzing the business and determining the
appropriate database structure (tables and columns) is typically carried out by Systems Analysts. A
Systems Analyst will gather information about how the business operates and will form a model of
the data storage requirements. From this model, a database programmer will create the database
tables and then work with the application developers to develop the rest of the database application.

For this tutorial, we will consider a simple banking business. The bank has many customers who
open and maintain one or more accounts. For each Customer, we keep a record of their name and
address. We also assign them a unique CustomerID. We assign this unique identifier both for
convenience and for accuracy. It is much easier to identify a single customer using their CustomerID
rather than by looking up their full name and address. In addition, it is possible for the bank to have
two customers with the same name (e.g., Bill Smith). In such cases, the unique CustomerID can
always be used to tell them apart.

In a similar fashion, all accounts are assigned a unique account number. An account can be either a
checking account or a savings account. Savings accounts earn interest but the only transactions
allowed are deposits and withdrawals. Checking accounts do not earn interest. We maintain the date
that the account was opened. This helps us track our customers and can be useful for marketing
purposes. Finally, we maintain the current balance of an account.

In the previous section, we gave the structure and some sample data for the Customer table and the
Accounts table. These will be used to support the data storage part of our Banking application.

Database Applications
In any database application, each of the tables requires a means to get data into them and to retrieve
and modify the data at a later time. The primary way to get data into tables is to use data entry forms.
The primary ways to get data back out of tables or to display data in tables are to use queries or
reports. In a complete database application, all of the forms and reports are linked together in a
Navigation Form – a single page that will have links to each of the parts of the application. A large
database application may have dozens of data entry forms and reports.

For this tutorial, we will create a data entry form for each table, a query for each table and a report
for each table.

Creating and Viewing Tables


Tables are the main units of data storage in Access. Recall that a table is made up of one or more
columns (or fields) and that a given column may appear in more than one table in order to indicate a
relationship between the tables.

From the business example discussed earlier, we concluded that two tables would be sufficient to
store the data about Customers and their bank Accounts. We now give the step-by-step instructions
for creating these two tables in Access.

There are a number of ways to create a table in Access. Access provides wizards that guide the user
through creating a table by suggesting names for tables and columns. The other main way to create a
table is by using the Design View to manually define the columns (fields) and their data types.

4
While using the wizards is a fast way to create tables, the user has less control over the column
names (fields) and data types. In this tutorial, we will describe the steps to create a table using the
Design View. Students are encouraged to experiment on their own with using the Create Table
wizard.

Creating a Table Using the Design View

To create a table in Access using the Design View, perform the following steps:

1. In Access 2007, 2010 and 2013, the Create New Table tab should already be highlighted and
a new table named table1 created. If this is not the case, click on the Create tab and click on
the Table icon. Then pull down the View menu and choose Design View.

The Table Design View will appear. Fill in the Field Name, Data Type and Description for
each column/field in the table. The CustomerID field is filled in below:

5
Note that the default name given for the table is Table1. In a later step, we will assign an
appropriate name for this table.

2. Fill in the information for the fields as follows:

Field Name Data Type Description


CustomerID Number The Unique Identifier for a Customer
FirstName Text The First Name of the Customer
LastName Text The Last Name of the Customer
StreetAddress Text The Street Address of the Customer
City Text The City of the Customer
State Text The home State of the Customer
Zip Text The Zip Code of the Customer

A figure showing the design view with the new table definition filled in is given below:

3. The next step is to define the Key for the table and to save the table.

6
Now that all of the fields have been defined for the table, a Primary Key should be defined.
Recall that the Primary Key will be used to uniquely identify a record in the table (in this case
a Customer). Highlight the CustomerID field and click on the Primary Key button on the
button bar

Notice that a small key appears next to the field name on the left side.Note: To remove a primary
key, simply repeat this procedure to toggle the primary key off.

4. As a final step, the table must be saved. Pull down the Office menu and choose the Save As
menu item. A dialog box will appear where the name of the new table should be specified.
Note that Access gives a default name such as Table1 or Table2. Simply type over this
default name with the name of the table.For this example, name the table: Customer Then

click on the OK button.

At this point, the new Customer table has been created and saved.

A Note about naming fields (Columns) in MS Access


7
When defining the fields (columns) for a table, it is important to use field names that give a clear
understanding of the data contents of the column. For example, does the field CNO indicate a
Customer Number or a Container Number ?

Field names in Access can be up to 64 characters long and may contain spaces. However, the use of
spaces in field names and table names is strongly discouraged. If you wish to make field names
easier to read, consider using an underscore character to separate words. However be certain no
spaces appear before or after the underscore.

The following table summarizes some different ways to give field names:

Description Bad Good

CustomerID or
Unique identifier for a customer CID
Customer_ID

Description for a product PDESC ProductDescription

Employee’s home telephone


Employee_home_telephone_number HomePhone
number

Bank account number BA# AccountNumber

Creating a Table

Create the Accounts table by following the same steps used to create the Customer table.

A figure showing the design view with the new table definition filled in is given below:

1. Define a Primary Key for the Accounts table. Click on the AccountNumber field with the
Right mouse button and choose Primary Key from the pop-up menu.
2. Save the new Accounts table by pulling down the File menu and choosing the Save menu
item. Fill in the name of the table: Accounts Then click on the OK button.

Viewing and Adding Data to a Table

Data can be added, deleted or modified in tables using a simple spreadsheet-like display. You can
now create the two tables described earlier below:

1. Customer Table

2. Accounts Table

8
To navigate to other records in the table, use the navigation bar at the bottom of the screen:

To modify existing data, simply navigate to the record of interest and tab to the appropriate field.
Use the arrow keys and the delete or backspace keys to change the existing data.

To delete a record, first navigate to the record of interest. Then pull down the Edit menu and choose
the Delete menu item.

At this point in the tutorial, we have created two tables, Customers and Accounts, and added data to
each one. In the subsequent sections, we will cover how to query and report on the data in the tables
and how to create a user-friendly data entry form using the Access wizards.

Creating Relationships Between tables

Recall that one of the main characteristics of relational databases is the fact that all tables are related
to one another. In the Bank database thus far, the Customers table is related to the Accounts table by
virtue of the CustomerID field appearing in both tables. Access has a means to make this relationship
explicit using the Relationships screen. Access uses this information when designing reports, forms
and queries that require more than one table to be displayed.

To get started, make sure the Accounts table and the Customer table are both closed. Access will halt
creation of any relationships if the table are currently opened. To close a table, either right-click on
the table name in the tab above the table and choose the close menu item, or click the small X to
right above the table.

9
Next, display the Relationships screen by clicking on the Database Tools tab and then click on the
Relationships button as shown below.

The blank Relationships screen will appear as follows:

10
The Show Table dialog box will appear by default. Highlight both the Customers table and the
Accounts table as shown below and then click on the Add button.

Then click on the Close button to close this dialog box. The Relationships screen will now reappear
with the two tables displayed as below:

11
To connect the Customers table with the Accounts table to form a relationship, click on the
CustomerID field in the Customers table and drag it over on top of the CustomerID field on the
Accounts table. Upon releasing the mouse button, the Edit Relationships dialog box will appear as
below:

Access will do its best to determine the Relationship Type (almost always it will select One-to-
Many). For this example, Access knows that CustomerID is a key of the Customer table so it chooses
this field as the “One” side. This makes the Accounts table the “Many” side as One customer may
have Many accounts.

One additional step to be taken is the check off the box labeled “Enforce Referential Integrity”. This
option puts constraints into effect such that an Accounts record can not be created without a valid
Customer record, and Access will also prevent a user from deleting a Customer record if a related
Accounts record exists. At this point, click on the Create button to create the relationship. The
Relationships screen should reappear with the new relationship in place as follows:

12
Note the symbols “1” (indicating the “One” side) and the infinity symbol (indicating the “Many”
side) on the relationship. Close the relationships screen and select Yes to save the changes to the
Relationships layout.

If the relationship does not appear in the above fashion, highlight it and press the delete key to delete
it. Then go back to the table design view and make certain that the CustomerID field is designated as
the key of the Customers table. Then go back to the Relationships screen and try to recreate the
relationship.

13
Review of Creating and Viewing Tables

Creating a new table requires the following steps:

1. Click on the Tables tab on the Access main screen


2. Click on the New button.
3. Choose the Design View and click the OK button.
4. Fill in the name, data type and description of each of the fields in the table.
5. Designate a primary key by clicking on one of the fields with the right mouse button and then
choose Primary Key from the pop-up menu.
6. Save the table by pulling down the File menu and choosing Save.
7. Close the new table by pulling down the File menu and choosing Close.

To change the design of an existing table (e.g., to add, change or delete a field):

1. Click on the Tables tab on the Access main screen


2. Highlight the name of the table to be modified and click on the Design button.
3. Make the necessary changes.
4. Save the table by pulling down the File menu and choosing Save.
5. Close the table by pulling down the File menu and choosing Close.

To add, delete or change data in an existing table:

1. Click on the Tables tab on the Access main screen


2. Highlight the name of the table to be modified and click on the Open button.
3. Make the necessary changes to the data.
4. Save the table data by pulling down the File menu and choosing Save.
5. Close the table by pulling down the File menu and choosing Close.

To create or edit relationships between tables:

1. Pull down the Tools menu and select the Relationships menu item.
2. To display tables, right click and choose Add Tables
3. To create new relationships, drag a key field from one table and drop it on the associated field
in another table
4. To edit an existing relationship, double click on the relationship line.
5. To delete an existing relationship, click on the relationship line and press the delete key.

14
Creating and Running Queries
Queries are a fundamental means of accessing and displaying data from tables. Queries can access a
single table or multiple tables. Examples of queries for our bank database might include:

• Which Customers live in Georgia ?


• Which Accounts have less than a $500 balance ?
• What is the total amount of money deposited by each Cusomter?
• Which Checking account has the largest balance?

Queries can be used to carry out other tasks such as for creating formatted reports and data entry
forms, and for exporting subsets of data to Excel or another software program.

In this section, we show how to use the Access Wizards to create queries for a single table and for
multiple tables.

Single Table Queries

In this section, we demonstrate how to query a single table. Single table queries are useful to gain a
view of the data in a table that:

• only displays certain fields (columns) in the output


• sorts the records in a particular order
• performs some statistics on the records such as calculating the sum of data values in a column
or counting the number of records, or
• filters the records by showing only those records that match some criteria. For example, show
only those bank customers living in GA.

Creating a query can be accomplished by using either the query design view or the Query wizard. In
the following example, we will use the query wizard to create a query.

To create a new query, click on the Create tab. Then click on the Query wizard button.

15
When the Query wizard appears, highlight the Simple Query Wizard selection and click on the OK
button.

The first step in the Simple Query wizard is to specify the table for the query and which fields
(columns) should be displayed in the query output. Three main sections of this step are:

1. Tables/Queries – A pick list of tables or queries you have created.


2. Available Fields – Those fields from the table that can be displayed.
3. Selected Fields – Those fields from the table that will be displayed.

For this example, pull down the Tables/Queries list and choose the Customer table. Notice that the
available fields change to list only those fields in the Customer table. This step is shown below:

16
From the list of Available fields on the left, move the FirstName, LastName, StreetAddress, City and
State fields over to the Selected Fields area on the right. Highlight one of the fields and then click on
the right arrow button in the center between the two areas. Repeat this for each of the four
fields to be displayed. When done with this step, the wizard should appear as below:

Click on the Next button to move to the next and final step in the Simple Query wizard.

In the final step, give your new query a name. For this example, name the query: Customer Address

At this point, the wizard will create the new query with the option to either:

• Open the query to view information – that is, the wizard will execute the query and show the
data.
• Modify the query design – the wizard will switch to the Design View to allow further
modification of the query.

17
For this example, choose Open the query to view information and click on the Finish button. When
this query executes, only the customer’s name, address, city and state fields appear, however, all of
the rows appear as shown in the figure below:

Close this query by clicking on the X in the upper right corner of the query results as shown in the
figure below:

18
The Access main screen showing the Queries tab should appear. Note the new query Customer
Address appears under the Customers table.

Single Table Queries (Continued)

In the following example, we will modify the Customer Address query to only display customers in a
certain state. To accomplish this, we will make use of the Query Design View.

Open up the Customer Address query in the design view by right-clicking on the name of the query.
Then select the Design View menu item as shown below.

The design view will appear as in the figure below:

19
The Query Design view has two major sections. In the top section, the table(s) used for the query are
displayed along with the available fields. In the bottom section, those fields that have been selected
for use in the query are displayed.

Each field has several options associated with it:

• Field – The name of the field from the table


• Table – The table the field comes from
• Sort – The order in which to sort on this field (Ascending, Descending or Not Sorted)
• Show – Whether or not to display this field in the query output
• Criteria – Indicates how to filter the records in the query output.

For this example, we will filter the records to only display those customers living in the State of
Georgia (GA). We will also sort the records on the City field.

To sort the records on the City field, click in the Sort area beneath the City field. Choose Ascending
from the list as shown in the figure below:

20
To filter the output to only display Customers in Georgia, click in the Criteria area beneath the State
field and type the following statement: = 'GA'

The = 'GA' statement tells Access to only show those records where the value of the State field is
equal to ‘GA’. Note the use of single quotes to surround the characters.

Run the query by clicking on the Run button (with the large red exclamation point). The output is
shown in the figure below:

21
Finally, save and close this query to return to the Access main screen.

Exercise: Single Table Queries

For this exercise, use the Simple Query wizard to create a query on the Accounts table showing just
the AccountNumber, AccountType and Balance fields.

1. From the Access main screen, click on the Create tab. Then click on the Query Wizard
button.
2. Choose the Simple Query wizard option and click on the OK button.
3. Under Table/Queries: choose the Accounts table. Then move the AccountNumber,
AccountType and Balance fields over to the Selected fields area. Then click the Next button.
4. In the next panel, you will be asked to choose between a detail or summary query. Choose
detailed query and click on the Next button.
5. Name the new Query : AccountsQuery and click on the Finish button.

The output is shown below:

22
Close this query by pulling down the Office menu and choosing Close.

In the next part of the exercise, we will modify the query to sort the output on the account number
and only display the Savings accounts.

1. From the Queries tab on the Access main screen, highlight the AccountsQuery and click on
the Design button.
2. Change the Sort order for the AccountNumber field to Ascending.Add the following
statement to the Criteria: are under the AccountType field:=
‘Savings’

3. Run the query by double-clicking on the AccountsQuery name. The output is shown below:

23
4. Finally, save and close the query to return to the Access main screen.

Multiple Table Queries

Up to this point, queries involving only one table have been demonstrated. It is almost a given that
queries will need to involve more than one table. For this example, assume that a manager would like
to see a list of all of the customers and the type of account(s) that each one maintains at the bank.
Such a query requires data from both the Customers table as well as the Accounts table. In such
queries, Access will rely on the Relationships established between tables to guide how the data will
be assembled to satisfy the query.

Before proceeding with these next instructions, make certain the One-to-Many relationship between
the Customers and Accounts table has been created (see section Creating Relationships for a review
of this process).

To start the process of creating a multiple table query, highlight the Create tab and click on the
Query Wizard button to create a new query. Select the “Simple Query Wizard” option as was done
previously.

When the simple query wizard appears, select the CustomerID and LastName fields from the
Customers table, then switch the Tables/Queries selection to the Accounts table and select the

24
CustomerID, AccountType and Balance fields from the Accounts table. The result from this step is
down below:

Click the Next button to continue. In the next step of the wizard, an option will appear to provide
some level of Summary. For this example, leave the default at “Detail …” as shown below and then
click on the Next button.

In the final step of the wizard, name the query “Customer Accounts Query” and click on the Finish
button. The multiple table query results should appear as follows:

25
MS Access knows how to line up (or “join”) the accounts table to the Customer table for this query
due to the relationship that was created when the tables were first defined.

As with single table queries demonstrated previously, one can change the query definition in design
view by adding filters (e.g., show account information for all customers in ‘GA’).

Exercise: Multiple Table Queries

For this exercise, create a new query called “Accounts Summary Query” that joins the Customers
table (include the CustomerID and LastName fields) with the Accounts table (include the Balance
field only). In the second step of the wizard, click on the Summary choice (instead of Details) and
then click on the Summary Options… button. Check off all of the Summary option boxes such as
Sum, AVG, Min and Max as shown in the figure below:

26
The resulting query should appear as follows:

Be sure to save the query as “Accounts Summary Query”.

27
Review of Creating and Running Queries

In this section, the basic steps for creating and running queries were introduced. The query wizard
can be used to create simple queries that access a single table. It is also possible to then modify the
query to sort or filter the records.

Creating a query using the query wizard:

1. From the Access main screen, click on the Queries tab. Then click on the New button.
2. From the Queries tab on the main Access screen, click on the New button and choose the
Simple Query wizard option.
3. Under Table/Queries: choose the appropriate table for the query and then indicate which
fields in the table will appear in the query output.If querying more than one table, change the
Table/Queries: selection to display additional tables and select the necessary fields.
4. If the table contains numeric fields, either detailed or summary information may be specified
for the query.
5. Finally, name the new query and click on the Finish button.

As a final note, Forms and Reports can be created based on existing queries.

28
Creating and Running a Data Entry Form
Data entry forms are the primary means of entering data into tables in the database. In a previous
section, we described how to add data to a table using a spreadsheet-like view of the data. Data entry
forms offer a more user-friendly interface by adding labels for each field and other helpful
information.

Access provides several different ways of creating data entry forms. These include:

• Creating the forms by hand using a Design View


• Creating a default form based on all of the fields available in a table or a query
• Creating a form based on a number of different wizards that walk the user through the forms
creation process.

As with queries, a data entry form can be based on a single table or it can work on multiple tables at
the same time.

In this section, we cover the basic steps for using a wizard to create a data entry form based on a
single table. After this exercise, a multiple-table form is demonstrated.

Creating a Single Table Form using the Wizard

In this example, we will create a simple data entry form for the Customer table. To begin the process,
click on the Create tab on the Access main screen. As with the other components in Access, there are
buttons for creating a New form, Open an existing form and Design an existing form. For this
example, click on the New button to create a new form.

Several buttons for creating a new form will appear. For this tutorial, choose the Form wizard.

In the first step of the Form wizard, we need to specify the fields from the Customer table that will
appear on the form. In this case, we want all of the fields to appear. Move each of the fields from the
Available Fields side over to the Selected Fields side as in the following figure. Then click on the
Next button.

29
Forms can have several different layouts or arrangement of the labels and fields on the screen.

• Columnar – Places the labels to the left of each field. This is similar to a paper form. This
layout is suitable for viewing data one record at a time.
• Tabular – Places the field labels at the top of the screen and the records are displayed below.
This is similar to how a spreadsheet would display the data and is suitable for displaying
multiple records of data at a time.
• Datasheet – The data appears in the same fashion as when viewing or adding data to a table.
• Justified – Places the labels above each field with the fields spread out on the form. This is
suitable for viewing a single record at a time as with the columnar layout.

For this example, choose the columnar layout as shown in the figure below and click on the Next
button.

30
At this point, MS Access 2007 and 2010/2013 versions are a bit different. Access 2007 will show
several sample display styles that determine how the form will appear, including elements such as
fonts, colors and the background used in the form. Access 2010 and 2013 skips this step in this
wizard and provides styles that can be applied to the form in Design mode. For this example, for MS
Access 2007, select the Office style as shown below and click on the Next button.

As a final step, give this new form the name: CustomerDataEntry and then click on the Finish button
as shown below:

31
The new form will be created by the wizard and then opened. It should appear as in the figure below:

32
Use the tab key to navigate between fields in the form. To move to the next or previous record, use
the record navigation bar at the bottom of the form:

The buttons on the navigation bar perform the following functions:

Go to the first record.


Go to the previous record.
Go to the next record.
Go to the last record. Go past the last record to add a new record.

To close the form and return to the Access main screen, pull down the File menu and choose Close.
To open the form at any time, highlight the form name under the Forms tab on the Access main
screen and click on the Open button.

One quick final note on forms. When the form is created, MS Access looks at how the table is
designed and creates the form based on the properties of the table. If you make any changes to the
table, you will need to re-create the form again in order to see those table changes reflected in the
form. One example where this might happen is is if you change a column in your table from a text
box to a combo box, or if you add or remove any columns from your table.

Exercise: Creating a Single Table Form

For this exercise, we will create a data entry form for the Accounts table created in a previous
exercise.

1. Click on the Create tab on the Access main screen and then click on the More Forms…
button and the “Forms Wizard” to create a new form.
2. Select the Accounts table and all of the available fields and click on the Next button.
3. Choose a Tabular layout and click on the Next button.
4. For Access 2007 choose the Office style and click on the Next button.
5. Name the form: AccountsDataEntry Then click on the Finish button to create, save and
view the new form.

The new form is shown in the figure below:

33
Close the form and return to the Access main screen, by pulling down the File (or Office) menu and
choosing Close.

Review of Creating and Running a Data Entry Form

The basic steps for creating a simple data entry form are:

1. Choose a table and a form wizard


2. Specify the fields (columns) that will appear in the form
3. Specify the layout for the form
4. Specify the style (fonts/colors, etc.) for the form
5. Save, create and run the new form

34
Creating and Running a Report
Reports are similar to queries in that they retrieve data from one or more tables and display the
records. Unlike queries, however, reports add formatting to the output including fonts, colors,
backgrounds and other features. Reports are often printed out on paper rather than just viewed on the
screen. They can also be attached to e-mail and exported and posted as web pages.

As with data entry forms, there are a number of ways to create reports in MS Access:

• A report can be created “by hand” in Design view


• A default report can be created automatically based on all of the firleds for a given table.
• A report can be created using the Create Report wizard.

In this section, we cover how to create simple reports using the Report wizard.

Creating a Single Table Report using the Wizard

In this example, we will create a simple report for a single table using the Report wizard. As with the
Queries and Forms, we begin by selecting the Create tab from the Access main screen.

To create a new report, click on the Report Wizard button.

In the next step of the Report wizard, is used to specify the fields from the Customer table that will
appear on the report. In this case, we want all of the fields to appear. Move each of the fields from
the Available Fields side over to the Selected Fields side as in the following figure. Then click on the
Next button.

35
In the next step, we have the opportunity to add Grouping Levels to the report. A grouping level is
where several records have the same value for a given field and we only display the value for the
first records. In this case, we will not use any grouping levels so simply click on the Next button as
shown below.

In the next step, the sorting order of the report can be specified. For this example, we will sort the
records on the CustomerID field. To achieve this, pull down the list box next to the number 1: and
choose the CustomerID field as shown in the figure below. Then click on the Next button.

36
Creating a Single Table Report using the Wizard (Continued)

The next step is to specify the layout of the report. The three options are:

• Columnar – Places the labels to the left of each field. This is similar to a paper form.
• Tabular – Places the field labels at the top of the report page and the records are displayed
below. This is similar to how a spreadsheet would display the data.
• Justified – Places the labels above each field with the fields spread out on the report page.

Generally, reports use the tabular layout. For this example, choose Tabular layout and set the page
Orientation to Landscape so that all of the fields will fit across one page. This is shown in the figure
below. Click on the Next button to continue.

37
In the next step, the style of the report can be selected. For this example, choose the Office style and
click on the Next button to continue.

Finally, give a name for the new report: CustomerReport and then click on the Finish button to
create, save and display the new report.

38
The output from the report is shown in the figure below. Note that on some screens, the last field,
Zip, may not display without scrolling over to the right.

Once the report is displayed, it can be viewed, printed or transferred into Microsoft Word or
Microsoft Excel. The button bar across the top of the screen has the following functions:

Print the report


Zoom into a region of the report
Display the report as one, two or multiple pages

Zoom into or out of the report


39
Transfer the report into MS Word
Close the report

To close the report and return to the Access main screen, click on the Close button.

Exercise: Creating a Single Table Report

For this exercise, we will create a report showing all of the Accounts information.

1. From the Access main screen, click on the Create tab and Click on the Report wizard.
2. Select all of the fields in the Accounts table by moving them all over to the Selected Fields
side and then click Next
3. Group the report by CustomerID by clicking on the CustomerID field and then clicking on
the right arrow button. This is shown in the following figure:

Click on the Next button to continue.

4. Choose to sort the report on the AccountNumber field. Note that a new button will appear
called Summary Options.

40
Click on the Summary Options button. Choose the Balance field and select the Sum option.
Choose the option to show both Detail and Summary data. Then click on the OK button.

Click on the Next button.

5. Choose a Block layout and click on the Next button.


6. Choose the Corporate style and the click on the Next button.
7. Finally, name the report: AccountsReport and click on the Finish button to create, save and
run the report.

The output from the AccountsReport is shown below:

41
Note the Grouping at the level of the CustomerID and the Sum for each customer’s balances.

To close the report and return to the Access main screen, pull down the File menu and choose Close.

Review of Creating and Running a Report

As can be seen in the report exercise, there are many ways to create reports to show summation,
sorting and layout of the data. Further study of Reports will show how to modify the layout using the
Design View. Students are encouraged to work with the Report wizards to create different styles and
types of reports.

42
Creating and Running a Master/Detail Form
Master/Detail forms are used to display data from two tables at the same time. MS Access calls the
“details” a “subform”. The forms are linked according to the relationship between the tables. Recall
that in the example database, the CustomerID is used to link the Customer table (Master) to the
Accounts table (Detail). In this section a master / detail form for the Customer and Accounts tables
will be created.

1. From the Access main screen, click on the Create tab and Click on the “More Forms…”
section and finally the “Forms Wizard”.Select the Customer table first and move the
CustomerID, FirstName and LastName fields to the Selected Fields list.Next, select the
Accounts table and move the AccountNumber, AccountType, DateOpened and Balance fields
to the Selected Fields list as shown below.

Click the Next… button to move to the next step.


2. At this point MS Access detects that this form will involve data from two different tables.
The first prompt asks how the form should be organized at the top or “Master” level. The “by
Customer” selection should be highlighted.The second prompt asks how the forms should be
created. For this example, select “Form with Subform(s)” as shown below and click the
Next… button to move to the next step.

43
3. The Subform is the form that will display the detailed data from the Accounts table. Selecting
the “Datasheet” layout will make it easy for the user to view the multiple accounts a
Customer may have. Select “Datasheet” and click the Next… button to move to the next step.

4. For Access 2007, select the Office style and click the Next… button to move to the next step.
(This step will not appear in MS Access 2010 or 2013).

44
5. Finally, give the main form the name “CustomerMasterForm” and the Subform the name
“Accounts Subform”.

6. After clicking on the Finish button the new Master/Detail form will appear as shown below.

45
Note that the navigation bar at the bottom of the form is used to navigate through the records in the
Master (or top) part of the form.

46
Creating and Running a Switchboard
A Switchboard is a type of form that displays a menu of items that a user can click on to launch data
entry forms, reports, queries and other actions in the database. A switchboard is typically created
after all of the forms and reports for a database application have been completed. It can be used to
guide the user to an appropriate set of forms and reports.

Note that starting with Access 2010, Switchboards are not available by default (you will need to add
this to the ribbon bar manually using the Options). Access 2010 and 2013 make use of the
Navigation Forms.

In this section, a default switchboard will be created.

1. From the Access main screen, click on the Database Tools tab and Click on the Switchboard
Manager as shown in the figure below.

If this is the first switchboard made for this database, you will be prompted to create a new one as
shown below. Click the Yes button.

2. The Switchboard manager will appear as shown below:

47
3. Click on the Edit menu to edit the “Main Switchboard”. The Edit Switchboard Page will
appear as shown below:

4. Add a new switchboard item by clicking on the New… button. The Edit Switchboard Item
form will appear as shown below. Fill in the fields as follows:

Text: Customer Data Entry Form


Command: Select Open Form in Edit Mode from the drop down list.
Form: Select the “CustomerDataEntry” form from the drop down list.

5. Click on the OK button to save this new Switchboard item.

48
6. Repeat the above step two more times to add Switchboard items for the Accounts DataEntry
form and the Customer Report.

Once completed, click the Close button. Then click the Close button once more to close the
Switchboard manager.

7. From the main MS Access screen look for a new section labeled Switchboard items. To view
the switchboard, double-click on name “Switchboard”.

49
The next section covers creating a Navigation Form which is the recommended navigation screen for
MS Access 2007, 2010 and newer versions.

Creating and Running a Navigation Form


MS Access 2010 introduced a new form called a Navigation Form. Navigation forms take the place
of Switchboards but provide much the same functionality. Namely, they are designed to give the user
the ability to run forms and reports without having to hunt through all of the different menus and lists
objects. Typically a database application will have one main Navigation form that will appear when
the database is opened.

In this section, the basic steps for creating and running a Navigation Form in MS Access 2010 will
be demonstrated.

A Navigation Form is another type of form in MS Access 2010 and 2013

50
1. To get started, click on the Create tab on the Access 2010 or 2013 ribbon bar. Under the
section for Forms look for the item labeled Navigation Form. Note that this may be located
on the button labeled Other Forms.

2. Note that there are 6 different default styles of Navigation Forms. Each one places the buttons
in a different configuration on the screem. Buttons can be aligned across the top, either side
or some combination.For this tutorial select the Horizontal Tabs configuration which appears
as the first item on the list.
3. At this point a new Navigation Form will be created with a row of tabs across the top. The
first tab will be labeled [Add New]

4. To add items to the Navigation form, drag the items from the list on the left over to the spot
on the Navigation Form labeled [Add New]. This is shown by the arrow in the above figure.

51
For example, drag over the CustomerDataEntry form to the Navigation Form. The result is
shown below.

5. Next drag and drop the CustomerMasterForm as shown below.

52
6. Next drag and drop the CustomerReport as shown below.

53
7. At this point we have created a new navigation Form and added three items along the top of
the page. Save the Navigation Form by right-clicking on the name of the form and choosing

Save as shown below:


8. Name the Navigation Form: Bank Navigation Form and click the OK

button.
9. Close up the Navigation Form by right-clicking again on the name of the form and choosing
Close menu item.At this point the new Navigation Form has been created and saved. The
next step will be to view the Navigation Form and navigate the different forms and reports
linked to it.
10. To view the Navigation Form, look for the Unrelated Objects group on the left side of the
screen. Double click on the Bank Navigation Form item as shown below:

54
The Navigation Form will appear:

55
Note that each form or report can be displayed simply by clicking on the different tabs across the top
of the Navigation Form.

Exercise: Modifying a Navigation Form


For this exercise, edit the Bank Navigation Form in Layout View and add the following new items to
the Navigation Form:

• AccountsDataEntry
• AccountsReport

The resulting Navigation Form should appear as below with the AccountsReport opened:

56
Setting the Navigation Form as the Default
MS Access 2007 and 2010 (as well as earlier versions) have the ability to set a default form that will
open up automatically once the MS Access data file is opened. This is especially useful for end users
so that they always see the same form when they open up the database.

To set the Default Form, pull down the File menu and select the Options menu item.

57
The Database Options form will appear. Click on the Current Database item on the left hand side.

Under the Application Options heading, look for the Display Form: prompt and set this to the Bank
Navigation Form as shown below:

58
Click on the OK button to close up the Database Options screen.

The next time this database (bankdb.accdb) is opened, the Bank Navigation Form will open up.

59
Part 2
Advanced Database Table Design in
MS Access 2010 and 2013

60
Advanced Database Table Design inMS Access 2010 and 2013
For example, the Accounts table was created as shown below:

Keeping Bad Data out of your database

The general idea we are working on here is to try and keep “bad data” out of the database while
doing what we can to assist the user. So as much as possible we want to try and suggest good data to
be put into the tables and to reject any obviously bad data. Once bad data makes its way into the
database it is often difficult to correct. Records that are missing data are also a problem. So again it
will always help the user any time we can provide a default value or provide good suggestions of
what data to put in.

Below are some additional properties that can be customized to provide better data input quality. In
general these techniques should be used at the time tables are created. MS Access will use these
properties when creating data entry forms and reports.

Specifying a Default Value for Columns (Fields) in MS Access

Some table columns (fields) may have a common default value. When adding a new data record it is
helpful to supply as many default values as is reasonable so the user does not have to type in as much
data. For example, in the Accounts table for the bank database, any new account that is created
should have a balance of $0.00. So a common-sense default value for the “Balance” column would

61
be 0. To set a default value, highlight the name of a column (field) in the table Design View and then
set the Default Valueproperty accordingly. In the example below the Default value for Balance has
been set to 0:

Also consider putting the Required property into play to ensure the user will put something in the
field. In the above example the Required property is set to No. Setting this to Yes will force the user
to enter data.

Column Validation Rules for tables in MS Access


In addition to setting default values, another helpful property to set up is the Validation Rule.
Validation Rules put limits around the values that are allowed to be stored in a column (field). Rules
can be set up compare the data a user enters and then either accept or reject that value. In case the
data is rejected by the rule, a message from the Validation Text property will be displayed. In this
example, the Balance column (field) will be validated to make sure it can never be a negative
number. The Validation Rule is set to > 0 and the Validation Text is set to Error: The balance
must always be more than $0.00

62
Converting a Textbox to a Combo Box with a list of values
Often columns (fields) in a table have a specific set of allowable values. For example the Gender of a
student or customer should be either “F” or “M”. An Account type should be either “Checking”,
“Savings” or “Money Market”. Rather than have the user type in these values, we can change the
default text box display of a field to a Combo Box. A Combo Box looks like a text box but it has a
small arrow on the right hand side. Clicking on the arrow presents a list of possible values.

For this example we will modify the Customer table and provide a Combo Box with a list of
suggested values for the State column (field).

1. Right-click on the Customer table and select “Design View”


2. Highlight the State column (field) and click on the “Lookup” tab in the Field Properties list.
The default Display Control property will be Text Box as shown below:

63
3. Change the Display Control property from Text Box to Combo Box. A new set of properties
will appear:

64
4. Change the Row Source property to: Value List. This setting allows us to type in a list of
suggested values separated by semicolons.
5. Type in the value list in the Row Source property. Surround any text string in double quotes
and separate values by semicolons like so: "GA";"KY";"NC";"SC";"TN";"VA"
6. Leave the rest of the properties as the default values. Make sure the Limit to list property
is set to No. This way if a Customer comes in from another state not on the list, the user can
type it in. At this point the properties look like:

7. Save the current table design and then close up the Design View.
8. Open up the table in datasheet view and click in the State field to see the Combo Box and list
of values drop down:

65
Converting a Textbox to a Combo Box with a Query
In the prior example, a combo box was created using a static value list typed in at the tie the table is
designed. In some cases the values that can be supplied for a field can come from another table or
some external data source. So rather than typing in a static list of possible values, the Row Source
property can be set to a Query.

A common situation occurs when we need to supply the value for a foreign key. Recall that a foreign
key is a column (field) that is copied from another table where the column acts like a Primary key (or
simply “the key”). The CustomerID column is the key of the Customer table. When it appears in the
Accounts table, the CustomerID column is a foreign key. When supplying a value for the
CustomerID column in the Accounts table, we are restricted to using only existing CustomerID
values that exist already in the Customer table.

For this example the Display Control for the CustomerID in the Accounts table will be changed to
a Combo Box using a Query.

1. Close any open tables or forms and open the Accounts table in Design View.
2. Highlight the CustomerID field and click on the Lookup table in the Field Properties
3. Change the Display Control from Text Box to Combo Box
4. Change the Row Source Type property to Table/Query
5. For the Row Source property pull down the list and select the Customer table.
6. Change the Bound Column property to 1
7. Change the Column Count property to 3The above three property changes tell Access to do
the following:
When the user clicks on the Combo Box, query the Customers table. Show the first three
columns of the Customer table (CustomerID, FirstName and LastName). when the user
selects a customer from the list, return the value from the first column (CustomerID) to the
CustomerID field in the Accounts table (Bound Column: 1)
8. Change the Column Heads property to Yes to show column headers at the top of the Combo
Box.
9. Change the Column Widths property to 0.5";1";1"
This will tell Access to display the first column (CustomerID) in a half an inch wide column
while the FirstName and LastName columns will be shown in columns 1 inch wide each.

66
10. Change the Limit to List property to Yes. We many only use CustomerIDs that exist in
the Customer table.
At this point the properties for the CustomerID column in the Accounts table will look like
the following:

11. Save the design of the Accounts table and close it.
12. Open the Accounts table and pull down the Combo Box for CustomerID to see the list of
values produced by the query:

67
The main advantage of using a query for a Combo Box in this way is that the list of available values
will automatically update any time new Customers are added. Note that the Row Source property
can be set to any existing table, query or even a SQL statement (discussed later on).

AutoNumber columns (fields) in MS Access


In my MS Access 2007/2010 Tutorial I introduced three main data types for columns (fields) in a
table: Character (or Text), Numbers and Date/Time. Columns designated as Keys are a special case.
Because of their function as a unique identifier, each value of key needs to be unique. For small
databases we may be able to count on the user typing in a new unique number or text string for the
key column each time a new record is created. However for larger databases and especially in cases
where the database is shared among many users, we need a way to guarantee unique key values are
generated for each new record.

MS Access provides a facility to deliver unique values by using the AutoNumber data type.
Specifying a column (field) data type as AutoNumber will accomplish the following things:

1. The data type will be an integer number.


2. The first data record entered will be given number 1 and each new record afterwards will
automatically be given the next number in sequence.
3. The user will not be able to click inside the AutoNumber field or change its values.

Unfortunately once a table has been created and data added, a field can not easily be changed from a
Number or Text to AutoNumber. So for this next exercise, we will create a new table for the Bank
database and will make use of the AutoNumber data type.

The Bank would now like to keep track of each transaction that occurs in an account. For example,
money can be deposited or withdrawn from the account. The bank will need to track the
AccountNumber, the TransactionType, the TransactionAmount and the date and time of the
transaction.

1. Start by closing up all of the existing tables.


2. Click on the Create tab on the ribbon bar and then click on the Table icon.
68
3. Right-click on the new table that has been created and select Design View.
4. When prompted name the new table “Transactions”
5. Add 5 columns (fields) to the Transactions table:

Field Name Data Type Description


TransactionID AutoNumber The Unique Identifier for the Transaction
TransactionDateTime Date/Time The Date and time of the transaction
TransactionType Short Text (Size 15) The transaction type
TransactionAmount Number (single) The transaction amount
AccountNumber Number (Long Integer) The Unique Identifier for a Bank Account

6. Save the new Transactions table and close the table Design View.
7. Open up the Relationship Tools screen from the Database Tools tab on the ribbon bar.
8. Add the Transactions table to the Relationships design. Create a relationship from the
AccountNumber column in the Accounts table to the AccountNumber column in the
Transactions table. The relationship should be One to Many and enforce referential integrity:

9. Save and close up the Relationship tools.


10. Open up the Transactions table and add some transactions as follows:

TransactionI TransactionDateTi TransactionTy TransactionAmou AccountNumb


D me pe nt er

69
5/14/2013 9:34:12
1 Deposit 3000 3322
AM
5/15/2013 4:12:31
2 Withdraw 2500 3322
PM
5/16/2013 10:11:01
3 Deposit 1500 8811
AM
5/17/2013 11:45:41
4 Withdraw 500 8811
PM
5/17/2013 12:14:21
5 Deposit 4000 9987
PM
5/17/2013 2:51:05
6 Deposit 2000 9980
PM
5/17/2013 2:52:15
7 Deposit 6000 4433
PM
5/17/2013 2:52:16
8 Deposit 3000 4433
PM
5/17/2013 3:11:32
9 Deposit 6000 4422
PM
5/18/2013 11:44:05
10 Deposit 800 1122
AM

Notice that when adding new records the TransactionID is automatically filled in with the next
integer.

We will make use of this data in the next part of the advanced Access tutorial.

Exercises: Table Properties in MS Access


Make the following additional changes to the tables in the Bank database:

1. Make the default value for DateOpened column in Accounts table equal to the current date.
Use the function =Date()
The Date() function will automatically populate the DateOpened field with the current date
when a new Accounts record is created.
2. For the AccountType column in the Accounts table, change the Display Control to a
Combo Box and make a value list of: "Checking";"Savings";"Money Market"
3. In the TransactionType column in the Transactions table, change the Display Control to a
Combo Box and make a value list of: "Deposit";"Withdraw";"Adjustment"
4. In the AccountNumber column in the Transactions table, change the Display Control to a
Combo Box and specify the Table/Query Row Source as a SQL query:
SELECT AccountNumber, customerid FROM Accounts ORDER BY AccountNumber
5. In the TransactionDateTime column in the Transactions table, specify a Default Value
property of: =Now()
The “Now()” function returns the current system date and time.
70
Part 3
Advanced Forms Design in
MS Access 2010 and 2013

71
Advanced Forms Design in MS Access 2010 and 2013

For example, in the section on Creating and Running a Data Entry Form the Customer Data entry
form was created:

The general idea we are working here is to make entering and updating data as easy as possible for
the users. So as much as possible we want to try and suggest good data to be put into the form fields,
provide default values wherever possible, and apply some common-sense checks to make sure bad
data is not entered.

Before we get into these details, we will start with a more complete overview of data entry forms.

72
Four basic types of data entry forms in MS Access
A typical database schema can contain dozens of tables, each with several columns of various data
types. We develop applications (forms, reports, menus, etc.) to make the job of manipulating data in
those tables easier for users. In Microsoft Access, a form (or data entry form) acts like a “window”
into the database schema. An individual form focuses the attention of the user to one or a few of the
tables at a time. In addition, a form can give prompts so the user knows what kind of input is
expected and how data is to be entered and manipulated. By default, every form in Access has the
capability to query existing data in a table, modify existing data and add new data (records) to the
table. A form is built up using a main form and possibly one or more “subforms” that correspond to
tables in the database. Fields within a form correspond to columns in the database tables.

There are four main types of forms that can be designed.

Single Table Form. This form design contains a single Single Table Form with lookup field. This form design
form corresponding to a single database table. This is contains a single form corresponding to a single
the most basic type of form. database table with the addition of one or more
fields that display data from some other tables or
hold the results of summary or calculated values.
This extra data is “looked up” when the form runs.

Master/Detail Form. This form design contains a Master/Detail Form with lookup fields. This form
“master” form and a “Subform” that are arranged in design is similar to the Master/Detail but has the
a master/detail (one to many) relationship. additional lookup fields in the master and/or detail
blocks.

My MS Access 2007/2010 Tutorial covered how to create single-table forms and master/detail
forms. In this tutorial we will cover how to add “lookup” fields (called “unbound” fields” to these
form designs. First we will dig a bit deeper into the forms designer and the properties of forms.

73
Forms Design Properties in MS Access
The Forms Design view provides a way to alter all of the properties of form canvas and fields. While
it is possible to create a form from scratch just by using the Design View, usually we can get a good
start on a form by running through the Form Wizard. Then we can customize the form by playing
around with the form properties in Design View. To get started, we will create a data entry for the
Accounts table as discussed in the MS Access 2007/2010 Tutorial.

For this exercise, we will create a data entry form for the Accounts table.

1. Click on the Create tab on the Access main screen and then click on the More Forms…
button and the “Forms Wizard” to create a new form.
2. Select the Accounts table and all of the available fields and click on the Next button.
3. Choose a Tabular layout and click on the Next button.
4. For Access 2007 only choose the Office style and click on the Next button.
5. Name the form: AccountsDataEntry Then click on the Finish button to create, save and view
the new form.

Note that if you had already created this form during the prior tutorial, you will be asked to
over-write the form with this new one.

The new form is shown in the figure below:

Table Design and Forms Design

One quick item to call to your attention is the CustomerID and Account Type fields. In the Advanced
Database Table Design in MS Access 2010 and 2013 tutorial we modified the Accounts table to
make the CustomerID column display as a Combo Box. The Account Type field was then modified
in the exercises to show a list of account types. The data entry form “inherits” these features and
74
should have created the CustomerID fields as a Combo Box as shown in the above figure. If your
form does not have combo box for CustomerID, you may wish to first go back to the Advanced
Database Table Design in MS Access 2010 and 2013 tutorial and complete those steps.

Other table features that are also inherited from table design include the size of the text boxes
(related to the size of the columns), default values and column validation rules.

Form Themes in Microsoft Access 2010 and 2013

Forms and reports can be customized with a wide range of themes. A Theme consists of a set of
background and foreground colors and fonts that are applied to the forms. MS Access 2007 and
earlier versions had a small selection of themes that could be selected during the Form Wizard.
Access 2010 and later versions create the form first and then apply themes later on.

To change the theme of the current form, click on the Home tab on the ribbon bar, then click on
the View menu and finally Design View. This will change the display of the current form to the
Design View as shown below:

With the Forms Design View activated, the ribbon bar adds three new entries at the top under the
heading Forms Design Tools:

• Design – Change colors and themes. Add buttons, fields, labels and other objects to the form.

75
• Arrange – Change layout and align objects on the form.
• Format – Change format of text, background images and drawing shapes.

The Design tab is shown below:

To change the theme of the form, click on the Design tab on the ribbon bar and pull down
the Theme menu. select a theme from the list that drops down. In a similar fashion the color scheme
of the form can be changed using the Colors menu and the font used for the labels and text boxes
can be set using the fonts menu.

Microsoft Access Form Properties

Every element or object on a form or report in MS Access has a set of properties associated with it.
On a form, there are “form level” properties that apply to the entire form. Each label, text box,
combo box and other object on a form also have their own set of properties. To view the Form level
properties, right-click on the form in Design View and select Properties from the pop-up menu. If
the Selection Type does not say Form then pull down the list below and select Form from the list.
Finally click on the Data tab as shown below:

76
The Data tab displays properties of the form related to the data that is used to populate the form and
how the data is to be displayed and manipulated. Access has already set all of these properties when
the form was created by the Forms Wizard. So by default there may not be a reason at this point to
change any of the properties. However in later steps we may come back to this property page to
make some changes. For now, a few of the more important and useful properties to be aware of are:

Property Description

Record Source The source of data for the form. Forms may only have one source of data “bound” to the
fields on the form. This source can be a query but most of the time it will be a table.

Recordset The type of Recordset object created from the record source. In virtually all cases this
Type should be set to Dynaset since a Dynaset maintains consistency with the underlying table. A
snapshot just shows the data at the time the form is opened so no data changes are
reflected until the form is re-opened or refreshed.

Fetch Defaults Yes indicates default values set in the underlying table will be populated in the fields when
a new record is created.

Filter Sets any filtering criteria for when the form is opened. For example, one might set a filter to
only show “Money Market” account types for a particular form. By default no filters are
applied but can be added by the user once the form is displayed.

Filter on load If a filter is set, Yes indicates the filter will be applied as the form is loading.

Order By Specifies the order of the records as they are displayed in the form. For example, putting
“CustomerID” for this property will cause the form to display the Accounts records ordered
by CustomerID.

Data Entry Yes indicates the form can only be used to add new data records. No is the default.

Allow Yes indicates this form can be used to add new records.
Additions

Allow Yes indicates this form can be used to delete existing records.
Deletions

Allow Edits Yes indicates this form can be used to edit existing records.

Allow Filters Yes indicates users can add filters to diplsay a subset of the records in the form.

Record Locks Indicates how data should be locked when multiple users are working on the same data.
Locks are used to prevent two users from overwriting the same data.

77
No Locks indicates no locking is done. This is the default but may not be reasonable if you
plan to share this data with multiple users.
All Records indicates all records in the table are locked when a user edits one record.
Edited Record indicates only the current record being edited will be locked.

The Format properties tab for a form controls the appearance of the form including scrollbars,
headings, default layout of fields, etc. Some handy properties include:

Property Description

Caption Form Caption – this is the name that appears on the top tab when the form is open.

Default View Default view when form is opened. Can be:


Single Form
Continuous Form
Data Sheet
split Form

Allow Form Yes indicates the regular form view is allowed.


View

Allow Yes indicates the form can be shown as a data sheet.


Datasheet
View

Allow Layout Yes indicates the form can be switched to Layout view.
View

Scroll Bars Can be Neither, Horizontal, Vertical or Both

Close Button Yes indicates a Close button will appear in the upper right corner of the form.

The other property tabs on the Form Properties sheet include:

• Events – Properties to control macros and Visual Basic for Applications (VBA) code in response to
certain events on the form. We will revisit Events in a later tutorial.
• Other – Properties to control other appearance aspects such as the inclusion of custom menu bars,
ribbon bars, help files and printing defaults.

In later tutorials we will revisit these form-level properties to customize how the form behaves.

78
Field Properties

While form-level properties apply to entire forms, the field-level properties apply to specific fields. if
the Property Sheet is no longer open, right-click on the CustomerID field and
select Properties from the pop-up menu. If the Property Sheet is already displayed then simply
click once on the CustomerID field. The Data tab for CustomerID properties is shown below:

As with the form-level properties, Access sets the default properties for each field during the Forms
Wizard process to create a new form. Most of these properties can (and probably should) be left with
their default values. However a few properties will be modified to change the behavior of the fields.

Property Description

Control Source The source of data for the field. The choices here are limited to the columns available in
the table (or query) specified in the form-level Record Source property. In this example,
the CustomerID is sourced (orbound to the CustomerID column in the Accounts table.

Row Source Properties that control the source of values for the Combo Box. In this case the first
Row Source column of the Customer table is used to populate the CustomerID field on the Accounts
Type table. Note that this set of properties were set by the table design properties introduced
Bound Column in the Advanced Database Table Design tutorial

Input Mask Set a template for data to be input. A “0” is used to indicate a mandatory numeric digit.
“9” indicates an optional digit. “L” indicates a mandatory letter. “?” indicates an optional
letter.
For example, a mask for a U.S. telephone number might be (999) 000-0000;0;-:.
Setting the Input Mask on the AccountNumber field to 0000 forces the user to enter a
4-digit number:

79
This Microsoft article discusses input masks in detail.

Default Value Specifies a default value for new records. This can also be set in the table level
properties.

Validation Sets a validation rule for data entered by the user. For example, this can be used to limit
Rule and the range of values for a particular field. Note that these are similar to the properties that
Validation are set by the table design properties introduced in the Advanced Database Table Design
Text tutorial

Enabled Yes indicates the field is available in form view.

Locked Yes indicates the data in the field is locked and can not be change.

Auto Expand Yes indicates a value will be pre-filled if the first few letters are typed in. For example,
when enabled, typing “C” in the AccountType field produces:

You may wish to bookmark this page so that you can easily refer back to the various forms
properties.

80
Lookup (unbound) Fields in MS Access
As discussed previously, the fields on a form are “bound” to an underlying table in the database. In
some cases, we may also wish to display some data from a different table – one that is not the main
table the form is based on. In this case, we can add “unbound” fields to the form and then populate
those fields using data pulled from other tables. Such fields are sometimes called “Lookup” fields.
Often you will see lookup fields representing the reverse of the “One-to-Many” or “Master/Detail”.

In our bank database example, One Customer can have Many accounts. So Customer is on the
“One” side and Accounts is on the “Many” side. When Accounts is the table used for the form, and
we want to show some Customer data that matches the account, we follow the CustomerID
relationship from the Accounts table back to the Customer table and use this relationship to bring in
the additional data to the form.

To help make this connect we will use a function to look up the CustomerID in the Customer table.
Access supports a large number of functions that can carry out different operations including various
math, accounting and finance calculations, date and time data manipulation, text formatting, data
type conversion and database manipulation. For this example we will specifically use
the DLookUp function that is designed to find a specific record in a data table based on a search
criteria.

To get started on this process, begin with the AccountsDataEntry form in Design View.

1. Pull down the Design ribbon bar and click on the Text Box icon:
2. Use the Textbox tool to “draw” a text box to the right of the CustomerID field on the form.
You may need to increase the width of the form to get this to fit (just drag the edge of the
form to make it wider on the screen).
3. Bring up the Properties for this new Text box. Click on the Other tab in the Property Sheet
and name this text box: CFirstName. Here we are making up a new name for this text box
that is different than the names of the columns in the Customer table for clarity.
4. Repeat the above two steps to create a second Text box named ClastName
At this point the new text boxes should look like the following:

Note that the contents of each text box is “Unbound” since there is nothing set for the Control
Source property.

5. The next step is to create a source for each text box. Starting with the CFirstName text box,
right click and bring up Property Sheet.
6. Click on the Control Source property and then click on the small button with three dots on
it to bring up the Expression Builder. The Expression Builder is a special form that provides a
way to write different expressions and functions. Note that all of the elements of the database
(tables, forms, queries, fields, etc.) are available for use in making expressions.
81
7. Type in the following expression for the CFirstName field:
=DLookUp("FirstName","Customer","CustomerID=" &
[Forms]![AccountsDataEntry]![CustomerID])
The DLookUp function finds a value for FirstName found in the Customer table where the
CustomerID from the Customer table is equal to the CustomerID field on
the AccountsDataEntry form.

8. Click on the OK button to close up the Expression Builder.


9. Repeat the above 4 steps for the CLastName field. use the following expression in
the Expression Builder:
=DLookUp("LastName","Customer","CustomerID=" &
[Forms]![AccountsDataEntry]![CustomerID])
At this point the CFistName and CLastName fields will now have a Control
source specified:

10. As a final step, consider changing the Enabled property on the CFirstName and CLastName
fields to No so that users can not click in those fields or try to change their values.
11. Save the form and then switch form Design View to Form View. Note that for each Accounts
record on the form, the appropriate Customer first name and last name will appear in the
fields next to CustomerID.

82
83
Working with Check Boxes on Access Forms
Check boxes are a user interface control typically used to provide quick, intuitive way to select a
simple logical data value. For example, if a column (field) has two potential values, say “Yes” and
“No”, or “On” and “Off”, the check box makes it easy for the user to select one value or the other.
There are two main ways to set up a check box control with an Access form:

1. Bind the check box directly to a column (field) in the underlying table.
2. Set up the check box as an unboud control on the form and then use macros or VBA code to
set the appropriate values in the underlying table.

Adding a Check Box Bound to a table column (field)

In this section we will demonstrate how to set up a simple “Yes/No” check box to the Accounts table
and form.

1. When bound to a table, check boxes must bind to a field with a special data type. So the first step is
to add such a column (field) to the Accounts table. Make sure all other forms and tables are closed,
then open up the Accounts table in Design View.
2. Add a new column (field) called AccountClosed and select Yes/No as the data type. All of the
other properties can be left at the default values as shown below:

3. Save and close the Accounts table and open up the AccountsDataEntry form we used previously in
Design View. Becuase this form was created before we added the new AccountClosed field, we will
need to add it to the form. If, after adding the new column to the table, you create a new form
based on the Accounts table, Access will add it automatically. The rest of these instructions assume
we will be adding this new field to the existing AccountsDataEntry form.
4. With the AccountsDataEntry form opened in Design View, click on the Design item in the ribbon bar
and then click on the Add Existing Fields button.
5. When the list of fields from the Accounts table appears, drag the AccountClosed field from the list
to the form as shown below:

84
6. Save the AccountsDataEntry form and open it up in Form View. Note the check box is set up and
ready to use.

85
Working with Option Buttons (Radio Buttons) on Access
Forms
Option buttons, someitmes called radio buttons, are a user interface controls typically used to provide
quick, intuitive way to select from two or more mutually exclusive data values. For example, if a
column (field) has two potential values, say “Yes” and “No”, or “On” and “Off”, the option button
makes it easy for the user to select one or the other. Option buttons are collected in a “Group” such
that selecting one button automatically de-selects the other button (or other buttons) in the same
group. There are two main ways to set up an option button with an Access form:

1. Bind the option buttons directly to a column (field) in the underlying table.
2. Set up the option buttons as unbound controls on the form and then use macros or VBA code to set
the appropriate values in the underlying table.

Adding Option Buttons (Radio Buttons) Bound to a table column (field)

1. When bound to a table, option buttons must bind to a field with either a number data type or a
“Yes/No” data type. For this example, the first step is to add such a column (field) to the Accounts
table. If you already did this while working with the Check Box example, you can skip this next step.
Make sure all other forms and tables are closed, then open up the Accounts table in Design View.
2. Add a new column (field) called AccountClosed and select Yes/No as the data type. All of the
other properties can be left at the default values as shown below:

3. Save and close the Accounts table and open up the AccountsDataEntry form we used previously in
Design View. Because this form was created before we added the new AccountClosed field, we will
need to add it to the form. If, after adding the new column to the table, you create a new form
based on the Accounts table, Access will add it automatically. The rest of these instructions assume
we will be adding this new field to the existing AccountsDataEntry form.

86
4. With the AccountsDataEntry form opened in Design View, click on the Design item in the ribbon bar
and scroll thorugh the controls list until you find the Option Group control.

5. Click on the Option Group control and then draw the option group on the form.

6. As soon as the Option Group is drawn on the form, the Option Group Wizard will launch. The Option
Group Wizard takes care of setting up the Option Group and binding it to a column (field) in a table.
7. The first step in the Option Group Wizard is to assign labels to each option. For this example assign
the following to the labels: Account Open and Account Closed
as shown below. Click on the Next> button to continue:

87
8. The next step in the Option Group Wizard is to set the default choice for the Option Group. For this
example we are binding the option group to an underlying table column and so the default choice
should come from that field. For new records, the default choice should be put in place. For this
example select the Account Open as the default value and click on the Next> button to continue:

9. The next step in the Option Group Wizard is to assign a value to each of the option group’s options.
These values must be an integer. When binding to a table column (field) with the “Yes/No” data
type, the values assigned need to be 0 and -1
Assign the values as shown in the figure below and click on the Next> button to continue:

10. Once the user select an option and the value from the prior step is assigned, Access can either hold
on to the value or pass it along to a specific column (field) in the table. In this case bind the Option
Group to the AccountClosed field by selecting the second option and selecting

88
the AccountClosed field from the list. Click on the Next> button to continue:

11. The next step is to customize the content and appearance of the Option Group. For this example, we
are sticking with the defaults of Option Buttons with the Etched style. Click on
the Next> button to continue:

12. The final step of the Options Group Wizard is to give a Caption for Option Group. This Caption will
appear above the option group. For this example type in: Account Status and click on

89
the Finish button to complete the wizard:

13. Once the Option Group Wizard is completed, the new object will appear on the form. Once in place
it can be re-sized and moved. The properties (such as Option Value) can also be changed.
14. Save the form and switch to Form View to test the Option Group functionality.

1. Bind the option buttons directly to a column (field) in the underlying table.
2. Set up the option buttons as unbound controls on the form and then use macros or VBA code to set
the appropriate values in the underlying table.

Adding Option Buttons (Radio Buttons) Bound to a table column (field)

1. When bound to a table, option buttons must bind to a field with either a number data type or a
“Yes/No” data type. For this example, the first step is to add such a column (field) to the Accounts
table. If you already did this while working with the Check Box example, you can skip this next step.
Make sure all other forms and tables are closed, then open up the Accounts table in Design View.
90
2. Add a new column (field) called AccountClosed and select Yes/No as the data type. All of the
other properties can be left at the default values as shown below:

3. Save and close the Accounts table and open up the AccountsDataEntry form we used previously in
Design View. Because this form was created before we added the new AccountClosed field, we will
need to add it to the form. If, after adding the new column to the table, you create a new form
based on the Accounts table, Access will add it automatically. The rest of these instructions assume
we will be adding this new field to the existing AccountsDataEntry form.
4. With the AccountsDataEntry form opened in Design View, click on the Design item in the ribbon bar
and scroll thorugh the controls list until you find the Option Group control.

91
5. Click on the Option Group control and then draw the option group on the form.

6. As soon as the Option Group is drawn on the form, the Option Group Wizard will launch. The Option
Group Wizard takes care of setting up the Option Group and binding it to a column (field) in a table.
7. The first step in the Option Group Wizard is to assign labels to each option. For this example assign
the following to the labels: Account Open and Account Closed
as shown below. Click on the Next> button to continue:

8. The next step in the Option Group Wizard is to set the default choice for the Option Group. For this
example we are binding the option group to an underlying table column and so the default choice
should come from that field. For new records, the default choice should be put in place. For this

92
example select the Account Open as the default value and click on the Next> button to continue:

9. The next step in the Option Group Wizard is to assign a value to each of the option group’s options.
These values must be an integer. When binding to a table column (field) with the “Yes/No” data
type, the values assigned need to be 0 and -1
Assign the values as shown in the figure below and click on the Next> button to continue:

10. Once the user select an option and the value from the prior step is assigned, Access can either hold
on to the value or pass it along to a specific column (field) in the table. In this case bind the Option
Group to the AccountClosed field by selecting the second option and selecting

93
the AccountClosed field from the list. Click on the Next> button to continue:

11. The next step is to customize the content and appearance of the Option Group. For this example, we
are sticking with the defaults of Option Buttons with the Etched style. Click on
the Next> button to continue:

12. The final step of the Options Group Wizard is to give a Caption for Option Group. This Caption will
appear above the option group. For this example type in: Account Status and click on

94
the Finish button to complete the wizard:

13. Once the Option Group Wizard is completed, the new object will appear on the form. Once in place
it can be re-sized and moved. The properties (such as Option Value) can also be changed.
14. Save the form and switch to Form View to test the Option Group functionality.

Adding Option Buttons as Unbound Controls

In many cases a table column (field) will take one of two or three values and we may want to use
Option Buttons as the user interface control to set those values. If the values are integers, then we can
bind the Option Group directly to the table column. However if the values are not integers, then we
will need to use an unbound option group with some macro code or VBA code to actually set the
right values in the fields that are bound to the data tables.

For this example we will add an Option Group that will control the AccountType field on the
AccountsDataEntry Form.
95
1. With the AccountsDataEntry form opened in Design View, click on the Design item in the ribbon bar
and scroll thorugh the controls list until you find the Option Group control.

2. Click on the Option Group control and then draw the option group on the form.

3. As soon as the Option Group is drawn on the form, the Option Group Wizard will launch. The Option
Group Wizard takes care of setting up the Option Group and assigning internal values to the various
options within the group.
4. The first step in the Option Group Wizard is to assign labels to each option. For this example assign
the following to the labels:
Checking
Savings
Money Market

96
Click on the Next> button to continue:

5. The next step in the Option Group Wizard is to set the default choice for the Option Group. For this
example, the default values will be set from the underlying table so there is no need to set a default.
Select the option for No, I don't want a default and click on the Next> button to continue:

6. The next step in the Option Group Wizard is to assign a value to each of the option group’s optoins.
These values must be integers. For this example we will make Checking have a value of
1, Savings will have a vaue of 2 and Money marketwill have a value of 3.

97
Assign the values as shown in the figure below and click on the Next> button to continue:

7. Once the user selects an option in the Option Group and the value from the prior step is assigned,
Access can either hold on to the value or pass it along to a specific column (field) in the table. In this
case we will not be binding these values directly to the table. Instead we will use some VBA code
(shown below) to do this work. Select the option Save the value for later use. and click on
the Next> button to continue:

8. The next step is to customize the content and appearance of the Option Group. For this example, we
are sticking with the defaults of Option Buttons with the Etched style. Click on

98
the Next> button to continue:

9. The final step of the Options Group Wizard is to give a Caption for Option Group. This Caption will
appear above the option group. For this example type in: Account Type and click on
the Finish button to complete the wizard:

10. Once the Option Group Wizard is completed, the new object will appear on the form. Once in place
it can be resized and moved. The properties (such as Option Value) can also be changed.
11. While still in Form Design view, right-click on the newly created Options Group and show Properties.
Under the Other tab of the property sheet, locate the Name property and set it

99
to AccountTypeFrame. We will refer to this control name in the steps below.

At this point the new Option Group has been created and given the name AccountTypeFrame. The
options group will not do anything useful however since there is no programming or logic to connect
the options group to the Accounts table. To do this some Visual Basic for Applications (VBA) code
will need to be added in two places in order to synchronize the data in the Accounts table and the
Options Group.

The first step is to make the value of the AccountType field change when a different option is
selected on the AccountTypeFrame. Since the AccountType field is bound to the table, and changes
made will be saved in the database. The following steps will put this into action but first we need to
spend a few minutes talking about “Events”.

Events in MS Access Forms

in Access, “Events” are triggered for a variety of reasons. For example, the following actions all
result in an “Event”:

• Opening or closing a form


• Clicking into a field on a form
• Changing the value of a field on a form
• Navigating to a new record on a form
• Clicking on any control on a form

and so on.

The two important parts of an event are the event type and what control on the form triggered the
event. For example, there are events the relate to the entire form and other events that relate only to
specific controls on the form.

For this part of the tutorial there are two events we are concerned about: Navigating to a new record
causes the form-level event called On Current to be triggered. We will use this event to change the
Options Group selection to match the data in the table. Selecting a different option in the Option
Group causes an After Update event to be triggered. We will use this event to change the value of
the AccountType field.

100
1. To set the After Update event on the AccountTypeFrame, right-click on
the AccountTypeFrame and select Properties.
2. Click on the Events tab and find the After Update event.
3. Click on the small button with three dots on it:

4. The Choose Builder dialog box will appear next. Select Code Builder and click the OK button:

5. The Visual Basic for Applications development environment will appear in a separate window. The
“stub” of the new event handler will already be written as follows:

Private Sub AccountTypeFrame_AfterUpdate()

End Sub

The code already supplied indicates this is a Private Subroutine (only accessible to the current
form) and it operates on the AccountTypeFrame responding to the AfterUpdate event.

101
6. Add the following lines of code to the AccountTypeFrame_AfterUpdate sub routine. When
completed the full code will appear as shown below:

Private Sub AccountTypeFrame_AfterUpdate()


' Check the value selected on the AccountTypeFrame
' and assign the appropriate text string to the AccountType field
Select Case AccountTypeFrame.Value
Case 1
AccountType = "Checking"
Case 2
AccountType = "Savings"
Case 3
AccountType = "Money Market"
End Select
End Sub

The first and last lines of code are already provided so just add the lines in between them.

In VBA, any line starting with a single quote is a comment. These are used to help
programmers document what a sub routine does. The Select Case statement looks at the
value of AccountTypeFrame and assigns the appropriate text string to the AccountType field
on the form. For example, if the value of AccountTypeFrame is 2, then the second Case is
activated and the string “Savings” will be assigned to the AccountType field.

7. Save the VBA code by pulling down the File menu and selecting the Save menu item. Then return
to the Access form by pulling down the File menu again and selecting Close and return to
Microsoft Access.
8. Test the form by switching to Form View. Try clicking on different account type option buttons to see
how the value in the AccountsType field is updated.

102
Coordinating the Options Group with the Data

At this point the VBA code is in place so that any time the user selects a different account type
option in the Options Group, the value in the AccountType field will change (and hence will be
saved into the database table). The next step is to coordinate the Options Group and AccountType
field in the other direction. That is, when navigating to a new Accounts record, the value in the
AccountType field should be reflected in the AccountTypeFrame options group.

1. Begin by bringing up the Properties of the AccountDataEntry form. If the Property Sheet is still
visible, change the Selection Type to Form and click on the Events tab.
If the Property Sheet is not visible, right-click on the form area and select Form Properties from
the pop-up menu. Then click on the Events tab.

2. The On Current event is triggered each time the user navigates to a new record on the form. Click
on the small button with three dots on it.
3. The Choose Builder dialog box will appear next. Select Code Builder and click the OK button.
4. The Visual Basic for Applications development environment will appear in a separate window. The
“stub” of the new event handler will already be written as follows:

Private Sub Form_Current()

End Sub

5. Add the following code to the Sub Form_Current:

Private Sub Form_Current()


' Check the value selected on the AccountType field and assign
' the appropriate value to the AccountTypeFrame options group
Select Case AccountType.Value
Case "Checking"
AccountTypeFrame.Value = 1
Case "Savings"
AccountTypeFrame.Value = 2
Case "Money Market"
AccountTypeFrame.Value = 3
Case Else
AccountTypeFrame.Value = Null
End Select

103
End Sub

When completed the code will look like the following:

6. Save the VBA code by pulling down the File menu and selecting the Save menu item. Then return
to the Access form by pulling down the File menu again and selecting Close and return to
Microsoft Access.
7. Test the form by switching to Form View. Note that when navigating to a new record, the
AccountTypeFrame options group will be updated to reflect the value in the AccountType field.

Review of Option Buttons

In this section we covered adding Option Buttons to a form. When bound to a table column with an
integer data type, Options Buttons automatically reflect the value of the data in the underlying table.
When used as an unbound control to set values in a bound field, we need to add two sets of VBA
code to coordinate the unbound control’s behavior.

Once an Option Group has been set up and is tested, we can take one further step to hide the bound
field (AccountType in the last example). In this way there will be only one control on the form
visible to the user. To hide a control just change its Visibleproperty to No. At that point you can
move the text field or other control anywhere on the main form and rearrange other fields as needed.

104
In the next section we will introduce how to customize a form with command buttons.

105
Customizing Access Forms with Command Buttons
Command Buttons are a great way to provide easy access to common functions such as saving data,
opening a related form or printing data. In this section we will cover adding a few simple buttons to
the Accounts data entry form.

1. Start with the Accounts data entry form as shown in the figure below:

2. Right-click on the form and select Design Mode.


3. Click on the Design tab on the Ribbon bar and then click on the Button icon.

4. The cursor will turn into a plus sign with the picture of a button attached to it.
Use this cursor to “draw” a button on the form as shown below:

5. Once the new button is drawn on the form, the Command Button wizard will appear. In
general, a command button can either invoke a preset function on the form, or it can launch a
macro (custom VBA code). For this example, we will select a present function to print the
current record on the form.
Select Form operations in the Categories window and then select Print current form in

106
the actions window as shown below. Then click the Next> button.

6. The next step in the command button wizard provides a chance to either use a text title or a
picture/icon for the button. In this example, select the option for Picture and highlight the
Printer option as shown below. Then click the Next> button.

7. In the last step of the command button wizard, you can give a name to the button. It is always
a good idea to use a meaningful name, especially if many buttons will be added to the form.
For this example, name the button: btnCmd_PrintForm as shown below and then click the

107
Finish button.

8. Save the form and view it. Notice the Print button with the printer icon will appear. Clicking
on this button should bring up the default printer dialog box that will allow you to print the
current form’s data:

108
As with any other object on a form, buttons have a large number of properties that can be set to
change how the button appears while on the form, while the user hovers their cursor over the button,
and finally when the user clicks on the button.

Embedding Charts on Access Forms


Charts are a useful way to summarize information and can lend insight to data analysis. For this
exercise we will create a pie chart representing the account balances for each bank Customer shown
by account type. This chart/graph will be embedded or added to the form so that the chart’s data
automatically updates to match the current database record being viewed.

1. Begin by opening the CustomerDataEntry form in Design mode. If you have not created a
Customer Data Entry form, run through the Forms Wizard and create a simple data entry
form based on all of the columns of the Customer table. (Visit my MS Access tutorial for the
steps to create a simple data entry form)
2. Increase the size of the form by stretching down the bottom of the main form area:

3. Click on the Design tab on the ribbon bar and scroll through the list of controls until
the Chart icon appears. This icon will show up like a small bar chart.

109
4. With the Chart Control tool selected (cursor will change to a plus sign with a small chart icon
attached to it), click on the form and drag a square box opening where you would like the
chart to be placed.

5. As soon as the chart is “drawn” on the form, the Chart Wizard will launch. The Access Forms
Chart Wizard will walk through the steps required to set up the chart.
6. The first step of the Chart Wizard is to select the source of the data. The data source for the
chart can be a table or a query. In this example even though we are working on the Customer
data entry form, we will select the Accounts table for the Chart. Highlight the Accounts table
and click the Next> button.

7. The next step for the Chart Wizard is to select the column (fields) to be used in the chart. For
this example highlight the CustomerID, AccountType and Balance fields and move them to

110
the Fields for Chart side. Then click the Next> button.

8. As with other Microsoft Office programs, Access has a large number of different chart styles.
For this example, select the Pie Chart style and click the Next> button.

9. The next step is to set up the fields Access will use for the chart series. In this case we would
like to use the Balance field according to each AccountType. Drag the AccountType field
button to the upper box to summarize the chart by AccountType and drag the Balance field
button to the lower box below the graph to use this field as the data. Keep in mind the data

111
for this chart is coming from the Accounts table (not from the form).

10. Click onthe Preview Chart button to see what the chart will look like and when done click
the Next> button.
11. At this point we can now link the data that will appear on the chart to the current Customer
record we have selected on the form. To do this select the CustomerID as the Form
Field and select the CustomerID as the Chart Field. Click theNext> button to continue.

112
12. Finally, give the chart a name and click on the Finish button to complete the wizard.

13. Save the form and switch to Form View to see the chart in action. Note that when you
navigate to a different Customer record, the chart will update with that customer’s account
data.

The charts and graphs used in Microsoft Access have the same properties, styles and options available in all of
the Microsoft Office programs. This means that there are a vast number of ways to format charts and graphs
within Access. To access all of these formatting options, return to Design mode and double-click on the chart.
The menus at the top will change to focus on the chart. Right-click on the different parts of the chart (the pie
itself, the legend, the title, etc.) to bring up the properties, chart types and other chart options.

113
Part 4
Working with Structured Query Language
(SQL) using Microsoft Access 2010 and
2013

114
Working with Structured Query Language (SQL)
using Microsoft Access 2010 and 2013

The purpose of this tutorial is to demonstrate how you can write your own SQL statements and run
them from within Microsoft Access 2007, 2010 or 2013. As with all relational databases, Microsoft
Access can be programmed directly using the Structured Query Language (SQL). While most often
SQL is hidden from users, for database students, MS Access provides a quick and easy way to
explore SQL and write some pretty complex queries. This is especially handy if you do not have time
or patience to install SQL Server, Oracle, mySQL or other larger relational database management
system.

The Structured Query Language (SQL)


Structured Query Language (SQL pronounced “Sequel”) is a declarative programming language
used to manipulate relational database management systems (RDBMS). It was first introduced in
IBM’s System R in the late 1970’s. Today SQL is used in all major relational DBMS such as Oracle,
IBM DB2, Informix, Sybase, Microsoft SQL Server, MySQL, Postgres, SQLLite, Microsoft Access
and many others. While each database vendor provides some proprietary features added on, the core
of SQL can be used on just about any relational database.

The structured query language is divided into two major portions:

1. Data Definition Language (DDL) – Used to create (define) data structures such as schemas,
tables, indexes, clusters, sequences as we ll as secure the database
2. Data Manipulation Language (DML) – Used to insert, retrieve, update and delete data from
tables.

Microsoft Access supports both DDL and DML parts of SQL. Most of the time we focus on SQL
Queries which as SQL SELECT statements used to retrieve data from an existing database. The basic
syntax for a SQL SELECT statement is:

SELECT column1, column2, ... columnN


FROM tableA, tableB, ... tableZ
WHERE condition1, condition2, ...conditionM
ORDER BY column1, column2, ... columnN

So, for example assuming we have a table named Customer with columns such as FirstName,
LastName, StreetAddress, City, state and Zip, we can write a SQL SELECT statement like this:

SELECT FirstName, LastName, City, State


FROM customer

In the above query we are asking for data in just the columns FirstName, LastName, City and State,
and the table we are getting this data from is called customer. Note that SQL language does not
worry about upper or lower case letters. So writing select firstName... is the same as writing
SELECT FIRSTNAME....

A slightly more sophisticated query would be if we only want to see customers who live in Georgia
and we would like the results sorted by the customer’s last name:

SELECT FirstName, LastName, City, State


FROM customer
115
WHERE state = 'GA'
ORDER BY LastName

As you can see, the list of columns we want to show follow the SELECT keyword. The name of the
table we are querying follows the FROM keyword, a condition state = 'GA' follows the WHERE
keyword and finally the results are sorted on the LastName column as described by the ORDER BY
keyword.

There are many more features of SQL SELECT statement that involve querying multiple tables by
“joining” them together, grouping up collections of records to find totals, largest, smallest or average
values, and performing other manipulations to the output that users will eventually see.

SQL in Microsoft Access


In this section we will provide the steps to write your own SQL in MS Access. This exercise assumes
you have MS Access 2007, 2010 or 2013 running with the “Bank” database (Customer and Accounts
tables) open.

To get started:

1. create a new query by clicking on the Create tab and then clicking on the Query Design
icon as shown below.

2. The “Show table” dialog box will appear as shown below. Click the Close button to close it
up.

116
3. Click on the Design tab and then click on the SQL icon on the left side (or pull down the
view button and select SQL

4. At this point the SQL View of the Query1 query will appear. By default the SELECT
keyword is shown in the window.

5. Edit the query to write out a complete SQL Statement:

SELECT firstname, lastname


FROM customer
ORDER BY lastname

The SQL view query window will now appear as below:

6. At this point, with the SQL statement typed in, we can execute the query against the database
by clicking on the exclamation point “Run” button.

117
7. The results of the query will display in a Datasheet view (like a spreadsheet):

8. To return to edit the SQL query, pull down the View menu and select SQL again.

118
9. You may also wish to save your query. To do this, right click on the tab with the current
query name: Query1 and choose Save.

A dialog box will appear prompting for the new name of the query. Type in a new name such as:
Customer_Names and then click OK to save it.

10. Finally, MS Access does not provide a way to save a query under a new name (“Save As”).
Instead what you can do is highlight the name of the query, right-click and select Copy then
right-click again and select Paste. You will then be prompted for the new name of the query.

119
Writing and Debugging SQL Queries in MS Access
Now that you have the basic mechanics of writing and running SQL queries, here are a few tips and
tricks for debugging your SQL.

Editors for MS Access SQL

The SQL editor window in MS Access is not all that intelligent or easy to work with. One way to
work with SQL is to write the code in another editor, then copy and paste the code into Access to run
it. There are many different text editors available. For example within Windows you will have
Notepad available under the Accessories group. The only warning I can give here is to NOT use MS
word or other word processing software to write your SQL. The reason for this is that MS Word and
other word processors will turn your single and double quotes into “fancy quotes” that SQL does not
understand.
For example, if you have a WHERE clause such as WHERE state = 'GA'
SQL expects the text to be enclosed in simple quotes. MS word will turn those into a fancy opening
and closing quote character that SQL will not understand.
If you receive an error such as Enter Parameter Value for `GA’ then you will definitely want to
make sure you have your text enclosed in plain single quote characters.

Dealing with Syntax Errors

Syntax errors can be very frustrating in SQL because often the database cannot pinpoint exactly
where the problem is in your code. Some of the main errors that Access will display include:

Error text Solution Example

Enter Most often this happens when the


Parameter name of a column (field) is not
Value for
typed correctly (such as this case
________
“lstname” is misspelled) or an
expression can not be recognized
such as WHERE state = `GA'

The Microsoft Most often this happens when the


Access name of a table is not typed
Database
correctly in the FROM clause of the
engine can not
find the input query. For example, in this case the
query or query specified FROM customers
table: instead of FROM customer
______________

Syntax Error In this case the syntax of the query is


(missing missing some key parts. For example, the
operator) in “FROM” clause is missing and so Access
query reports the approximate location of where
expression:
the problem occurs by showing the text of
______________
the query.

120
Documenting your SQL work
In this section I will describe some tips for formatting your queries and results so that they are
presented in a clear, concise way on your assignments and projects.
The assumption here is that you will be using a word processing program such as MS Word or other
word processing program that supports copying and pasting pictures and text.

For this exercise, assume the homework question is to show the first and last names of all of the
customers and to order the result by the customer’s last name.

1. Type in the SQL query as described on the prior section and run it to get the results:

2. In the Datasheet view, click on the small square box to the left of the column headings and at
the top of the row selection boxes. This will cause the entire set of results to be highlighted.

121
3. Right-click on the same small square box in the corner and select Copy from the pop-up
menu.

4. Switch over to MS Word (or other word processing program) and Paste the results into an
appropriate location:

Some other helpful hints that were also followed in creating this assignment document:

• Be sure to type in the full sentence describing the query you are solving (Don’t just put
“Question 1″). For example you may want to copy the question from the homework and
make it a part of the answer.
• When pasting in the SQL text for your query, use a Courier New font so that the characters
and spacing will line up. This makes it much easier to read.
• Paste in the results using the technique shown above instead of using a screen shot. This will
not only makes your Word document files smaller, but will also come out very clear when
you print it.
• Be sure to put your name, class/course and section on your assignment.
• For more complex queries that may involve Sub-queries or Inline queries, it is best to line up
the subqueries in an indented for to make them easier to read and debug. For example, instead
of writing a subquery like this:
122
SELECT accountnumber, balance
FROM accounts WHERE balance = (SELECT MIN(balance) from accounts)

Line up the sub query along the parentheses:

SELECT accountnumber, balance


FROM accounts
WHERE balance = (
SELECT MIN(balance)
FROM accounts
)

Conclusions
In this brief tutorial we covered how to work with SQL using MS Access. SQL is a fairly generic
programming language and anything you learn while writing SQL under MS access can be easily
transferred to other relational databases such as SQL Server, Oracle, Sybase, etc. For more notes on
SQL, visit my Structured Query Language (SQL) course notes page.

123
Part 5
Structured Query Language (SQL)

124
Database Management Systems
Notes on Structured Query Language (SQL)

History of Structured Query Language


1. SQL was first implemented in IBM’s System R in the late 1970’s.
2. SQL is the de-facto standard query language for creating and manipulating data in relational
databases.
3. Some minor syntax differences, but the majority of SQL is standard across MS Access, MS
SQL Server, Oracle, Sybase, MySQL, Postgres, Informix, etc.
4. SQL is either specified by a command-line tool or is embeddedinto a general purpose
programming language such as Cobol, “C”, Pascal, Java, C++, etc.
5. SQL is a standardized language monitored by the American National Standards Institute
(ANSI) as well as by National Institute of Standards (NIST).
o ANSI 1990 – SQL 1 standard
o ANSI 1992 – SQL 2 Standard (sometimes called SQL-92)
o ANSI 1999 – SQL 1999 – adds regular expressions, triggers, some Object oriented
concepts
o ANSI 2003 – SQL 2003 – XML features, autogenerated data (e.g., autonumber)
o ANSI 2006 – SQL 2006 – Further XML Integration using XQuery, XPath, etc.
o ANSI 2008 – SQL 2008 – Additional commands such as Truncate
6. SQL has two major parts:
1. Data Definition Language (DDL) – Used to create (define) data structures such as
tables, indexes, clusters
2. Data Manipulation Language (DML) – Used to insert, update, delete and retrieve
(select) data from tables.

Structured Query Language (SQL) Data Types


When creating tables in a database schema, we need to specify the data type for each column of the
table. For example, if we need to store a salary or a date of birth, we need to choose the right data
type that is supported by our target DBMS. Each vendor’s implementation of SQL uses slightly
different names for the data types.

SQL Numeric Data Types

• Integers: INTEGER, INT or SMALLINT


• Real Numbers: FLOAT, REAL, DOUBLE, PRECISION
• Formatted Numbers: DECIMAL(i,j), NUMERIC(i,j)

SQL Character String Data Types

• Two main types: Fixed length and variable length.


• Fixed length of n characters: CHAR(n) or CHARACTER(n)
• Variable length up to size n: VARCHAR(n)

125
SQL Date and Time Data Types

Note: Implementations vary widely for these data types.

• DATE
Has 10 positions in the format: YYYY-MM-DD
• TIME
Has 8 positions in the format: HH:MM:SS
• TIME(i)
Defines the TIME data type with an additional i positions for fractions of a second. For
example: HH:MM:SS:dd
• Offset from UTZ. +/- HH:MM
• TIMESTAMP Records an instant in time using full date and time with fractions of sections.
• INTERVAL Used to specify some span of time measured in days or minutes, etc.
• Other ways of expressing dates:
o Store as characters or integers with Year, Month Day:
19972011
o Store as Julian date:
1997283
• MS Access, SQL Server and Oracle store date and time information together in a DATE or
Date/Time data type.

Examples of SQL Data Types for Some Popular RDBMS

• Data types most often used are shown in Bold letters


• MS Access Examples from the MS Access Help File (c) Microsoft:

Storage
Data Type Range of Values
Size
Byte 1 byte 0 to 255
Boolean 2 bytes True or False.
Integer 2 bytes -32,768 to 32,767.
Long (long integer) 4 bytes -2,147,483,648 to 2,147,483,647.
-3.402823E38 to -1.401298E-45 for negative values;
Single(single-precision
4 bytes 1.401298E-45 to 3.402823E38 for
floating-point)
positive values.
-1.79769313486232E308 to -4.94065645841247E-324 for
Double (double-
8 bytes negative values; 4.94065645841247E-324 to
precision floating-point)
1.79769313486232E308 for positive values.
Currency (scaled -922,337,203,685,477.5808 to
8 bytes
integer) 922,337,203,685,477.5807.
Date 8 bytes January 1, 100 to December 31, 9999.
Object 4 bytes Any Object reference.
10 bytes +
0 to approx. 2 billion (approx. 65,400 for MS Windows
String (variable-length) string
version 3.1).
length
Length of
String (fixed-length) 1 to approximately 65,400.
string
Variant (with numbers) 16 bytes Any numeric value up to the range of a Double.
126
22 bytes +
Variant (with
string Same range as for variable-length String.
characters)
length

• Oracle supports the following data types:


o Numeric: BINARY_INTEGER, DEC, DECIMAL, DOUBLE PRECISION, FLOAT,
INT,
INTEGER, NATURAL, NATURALN, NUMBER, NUMERIC, PLS_INTEGER,
POSITIVE, POSITIVEN, REAL, SMALLINT
o Date: DATE Note: Also stores time.
o Character: CHAR, CHARACTER, STRING, VARCHAR, VARCHAR2
o Others: BOOLEAN, LONG, LONG RAW, RAW

Note: You will not need to memorize the above two tables for exams, etc. They are only there for
your reference.

Structured Query Language (SQL) Data Definition Language


DDL is used to define the schema of the database.

• Create a database schema


• Create, Drop or Alter a table
• Create or Drop an Index
• Define Integrity constraints
• Define access privileges to users
• Define access privileges on objects

SQL2 specification supports the creation of multiple schemas per database each with a distinct owner
and authorized users.

Creating a Schema

Note: To try out these SQL examples in MS Access, follow the instructions on Working with
Structured Query Language in Microsoft Access. Keep in mind that MS Access’s DDL syntax is
limited. Many of the DDL statements below (including domains) are not supported in Access.

Creating a Table:

CREATE TABLE employee (


employeeid VARCHAR(10) NOT NULL,
last_name VARCHAR(20) NOT NULL,
first_name VARCHAR(18) NOT NULL,
soc_sec VARCHAR(11) NOT NULL,
date_of_birth DATE,
salary NUMBER,
departmentid NUMBER
) ;

CREATE TABLE department (


departmentid NUMBER NOT NULL,
department_name VARCHAR(30) NOT NULL,

127
department_location VARCHAR(30)
);

Important: When naming tables, columns and other database objects, do not include spaces in the
names. For example, do not call the last name column: Last Name If you wish to separate words in
a name, use the underscore character.

Specifying Primary and Foreign keys:

CREATE TABLE order_header (


order_number NUMBER NOT NULL,
order_date DATE,
sales_person VARCHAR(25),
bill_to VARCHAR(35),
bill_to_address VARCHAR(45),
bill_to_city VARCHAR(20),
bill_to_state VARCHAR(2),
bill_to_zip VARCHAR(10),
PRIMARY KEY (order_number)
);

CREATE TABLE order_items (


order_number NUMBER NOT NULL,
line_item NUMBER NOT NULL,
part_number VARCHAR(12) NOT NULL,
quantity NUMBER,
price NUMBER,
PRIMARY KEY (order_number, line_item),
FOREIGN KEY (order_number)
REFERENCES order_header (order_number)
);

Adding an index to speed up retrieval

CREATE INDEX order_index


ON order_header (order_number) ;

CREATE INDEX items_index


ON order_items (order_number, line_item) ;

Example from MS Access:

CREATE TABLE workers (


FirstName TEXT,
LastName TEXT,
workerid INTEGER
CONSTRAINT workeridConstraint PRIMARY KEY
);

CREATE INDEX worker_index


ON worker (workerid) ;

More examples using Primary Key and Foreign keys


Note, if you already created these tables in your schema, you can drop them first with DROP TABLE
employee; for example).

128
CREATE TABLE department (
departmentid NUMBER NOT NULL
CONSTRAINT pk_department PRIMARY KEY,
department_name VARCHAR(30) NOT NULL,
department_location VARCHAR(30)
)

CREATE TABLE employee (


employeeid VARCHAR(10) NOT NULL
CONSTRAINT pk_Employee PRIMARY KEY,
last_name VARCHAR(20) NOT NULL,
first_name VARCHAR(18) NOT NULL,
soc_sec VARCHAR(11) NOT NULL,
date_of_birth DATE,
salary NUMBER,
departmentid NUMBER
) ;

Now add the foreign key constraint to link Employee to Department.

ALTER TABLE employee


ADD CONSTRAINT fk_department
FOREIGN KEY (departmentid)
REFERENCES department (departmentid)

Specifying Constraints on Columns and Tables

We apply constraints on columns so that we can ensure good data is added into the database and the
amount of NULL values is minimized

Constraints on Columns:

• NOT NULL – Attribute may not take a NULL value


• DEFAULT – Store a given default value if no value is specified
• PRIMARY KEY – Indicate which column(s) form the primary key
• FOREIGN KEY – Indicate which column(s) form a foreign key. This enforces referential
integrity
• UNIQUE – Indicates which column(s) must have unique values.

Specify when constraint should be enforced:

• Immediate
• Deferrable until commit time

Referential Integrity Constraint: Specify the behavior for child tuples when a parent tuple is
modified.

Action to take if referential integrity is violated:

• SET NULL – Child tuples foreign key is set to NULL – Orphans.


• SET DEFAULT – Set the value of the foreign key to some default value.
• CASCADE – Child tuples are updated (or deleted) according to the action take on the parent
tuple.

129
Examples of ON DELETE and ON UPDATE. (Note MS Access may not support these)
CREATE TABLE order_items (
order_number NUMBER NOT NULL,
line_item NUMBER NOT NULL,
part_number VARCHAR(12) NOT NULL,
quantity NUMBER,
PRIMARY KEY (order_number, line_item),
FOREIGN KEY (order_number)
REFERENCES order_header (order_number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE
);

Constraints can also be given names so that they can later be modified or dropped easily.
CREATE TABLE order_header (
order_number NUMBER NOT NULL,
order_date DATE,
sales_person VARCHAR(25),
bill_to VARCHAR(35),
bill_to_address VARCHAR(45),
bill_to_city VARCHAR(20),
bill_to_state VARCHAR(2),
bill_to_zip VARCHAR(10),
CONSTRAINT pk_order_header
PRIMARY KEY (order_number)
);

CREATE TABLE parts (


part_number VARCHAR(12) NOT NULL,
part_description VARCHAR(25) ,
part_price NUMBER,
CONSTRAINT pk_parts
PRIMARY KEY (part_number)
);

Assuming we have a “Parts” table:

CREATE TABLE order_items (


order_number NUMBER NOT NULL,
line_item NUMBER NOT NULL,
part_number VARCHAR(12) NOT NULL,
quantity NUMBER,
CONSTRAINT pk_order_items
PRIMARY KEY (order_number, line_item),
CONSTRAINT fk1_order_items
FOREIGN KEY (order_number)
REFERENCES order_header (order_number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE,
CONSTRAINT fk2_order_items
FOREIGN KEY (part_number)
REFERENCES parts (part_number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE
);

An even better approach is to create the tables without constraints and then add them separately with
ALTER TABLE statements:
CREATE TABLE order_header (

130
order_number NUMBER(10,0) NOT NULL,
order_date DATE,
sales_person VARCHAR(25),
bill_to VARCHAR(35),
bill_to_address VARCHAR(45),
bill_to_city VARCHAR(20),
bill_to_state VARCHAR(2),
bill_to_zip VARCHAR(10)
);

ALTER TABLE order_header


ADD CONSTRAINT pk_order_header
PRIMARY KEY (order_number);

CREATE TABLE order_items (


order_number NUMBER(10,0) NOT NULL,
line_item NUMBER(4,0) NOT NULL,
part_number VARCHAR(12) NOT NULL,
quantity NUMBER(4,0)
);

ALTER TABLE order_items ADD


CONSTRAINT pk_order_items
PRIMARY KEY (order_number, line_item) ;

ALTER TABLE order_items ADD


CONSTRAINT fk1_order_items
FOREIGN KEY (order_number)
REFERENCES order_header (order_number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE;

ALTER TABLE order_items ADD


CONSTRAINT fk2_order_items
FOREIGN KEY (part_number)
REFERENCES parts (part_number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE;

Creating indexes on table columns

• To speed up retrieval of orders given order_number:

CREATE INDEX idx_order_number ON order_header (order_number) ;

• To speed up retrieval of orders given sales person:

CREATE INDEX idx_sales_person ON order_header (sales_person) ;

• We give the first part of the index name as “idx” just as a convention.

Removing Schema Components with DROP

• DROP SCHEMA schema_name CASCADE


Drop the entire schema including all tables. CASCADE option deletes all data, all tables,
indexes, domains, etc.
• DROP SCHEMA schema_name RESTRICT
Removes the schema only if it is empty.

131
• DROP TABLE table_name
Remove the table and all of its data.
• DROP TABLE table_name CASCADE
Remove the table and all related tables as specified by FOREIGN KEY constraints.
• DROP TABLE table_name RESTRICT
Remove the table only if it is not referenced (via a FOREIGN KEY constraint) by other
tables.
• DROP INDEX index_name
Removes an index.
• DROP CONSTRAINT table_name.constraint_name
Removes a constraint from a table.

Changing Schema Components with ALTER

• Changing Column data type: ALTER TABLE student ALTER last_name VARCHAR(35);
• Dropping a default value: ALTER TABLE student ALTER gpa DROP DEFAULT
• Adding a new dafult value to a column: ALTER TABLE student ALTER gpa SET DEFAULT
0.00;
• Adding Attributes/Columns to an existing table: ALTER TABLE student ADD admission
DATE;
• Removing Attributes (not widely implemented): ALTER TABLE student DROP home_phone;

132
Data Manipulation Language (DML)
DDL is used to create and specify the schema. DML is then used to manipulate (select, insert,
update, delete) data.

Inserting Data into Tables using SQL

General syntax:

INSERT INTO tablename (column1, column2, ... columnX)


VALUES (val1, val2, ... valX);

Examples:

INSERT INTO stocks (symbol, close_date, close_price)


VALUES ("IBM", "03-JUN-94", 104.25);

INSERT INTO student_grades (student_id, test_name, score, grade)


VALUES (101, "Quiz 1", 88, "B+");

Quotes are placed around the data depending on the Data type and on the specific RDBMS being
used:

RDBMS Text Data Type Dates


MS Access TEXT: Either ” or ‘ DATETIME: Either # or ‘
Oracle VARCHAR: ‘ DATE: ‘
IBM DB2 VARCHAR: ‘ DATE: ‘
Sybase CHAR and VARCHAR: ” DATE: “

Examples for Employee and Department using MS Access syntax:

INSERT INTO department (departmentid, department_name, department_location)


VALUES (1, "Finance", "NY");
INSERT INTO department (departmentid, department_name, department_location)
VALUES (2, "Marketing", "NY");
INSERT INTO department (departmentid, department_name, department_location)
VALUES (3, "IT", "NJ");
INSERT INTO department (departmentid, department_name, department_location)
VALUES (4, "Accounting", "PA");
INSERT INTO department (departmentid, department_name, department_location)
VALUES (5, "Shipping", "CA");

INSERT INTO employee


(employeeid, first_name, last_name, soc_sec, date_of_birth, salary,
departmentid)
VALUES ("E101", "Joe", "Smith", "111-22-3344", '5/3/1972', 43000.00, 1)
INSERT INTO employee
(employeeid, first_name, last_name, soc_sec, date_of_birth, salary,
departmentid)
133
VALUES ("E102", "Mary", "Green", "333-11-2222", '12/4/1968', 41500.00, 2)
INSERT INTO employee
(employeeid, first_name, last_name, soc_sec, date_of_birth, salary,
departmentid)
VALUES ("E103", "Ed", "Jones", "777-66-5555", '1/9/1971', 39500.00, 3)
INSERT INTO employee
(employeeid, first_name, last_name, soc_sec, date_of_birth, salary,
departmentid)
VALUES ("E104", "Sally", "Smith", "661-61-6161", '8/19/1973', 55000.00, 3)
INSERT INTO employee
(employeeid, first_name, last_name, soc_sec, date_of_birth, salary,
departmentid)
VALUES ("E105", "Howard", "Brown", "777-88-9999", '8/12/1976', 45000.00, 1)
INSERT INTO employee
(employeeid, first_name, last_name, soc_sec, date_of_birth, salary,
departmentid)
VALUES ("E106", "Jane", "Foster", "222-22-2222", '1/1/1972', 35000.00, 4)

Retrieving Data from Tables with SQL Select

Main way of getting data out of tables is with the SELECT statement.

SELECT syntax:

SELECT column1, column2, ... columnN


FROM tableA, tableB, ... tableZ
WHERE condition1, condition2, ...conditionM
GROUP BY column1, ...
HAVING condition
ORDER BY column1, column2, ... columnN

Assume an employee table:


employee (employeeid, first_name, last_name, soc_sec, date_of_birth, salary, departmentid)
and a “Stocks” table:
stocks(symbol, close_date, close_price)

Some example queries:

SELECT employeeid, last_name, first_name


FROM employee
WHERE last_name = 'Smith'
ORDER BY first_name DESC

SELECT employeeid, last_name, first_name


FROM employee
WHERE salary > 41000
ORDER BY last_name, first_name DESC

SELECT *
FROM employee
ORDER BY 2;

SELECT last_name, first_name, salary


FROM employee
WHERE departmentid = 3

134
ORDER BY salary DESC

SELECT symbol, close_price


FROM stocks
WHERE close_date > "01-JAN-95" AND symbol = "IBM"
ORDER BY close_date

SELECT symbol, close_date, close_price


FROM stocks
WHERE close_date >= "01-JAN-95"
ORDER BY symbol, close_date

Relational Operators and SQL

Relational operators each have implementations in SQL.

• employee_id, last_name, first_name


( salary > 40000 (EMPLOYEE) )

SELECT employeeid, last_name, first_name


FROM employee
WHERE salary > 40000

• AVG (salary) ( departmentid = 3 (EMPLOYEE) )

SELECT AVG(salary)
FROM employee
WHERE departmentid = 3

• last_name = ‘Smith’ departmentid = 3 (EMPLOYEE)

SELECT *
FROM employee
WHERE last_name = 'Smith' AND departmentid = 3

SQL Built-in Functions

SQL has two main types of functions:

1. Aggregate Functions: Operate on a collection of records. For example, SUM, AVG,


MIN, MAX and COUNT are all aggregate functions.
2. Scalar functions: Operate on every record value individually. For example math
functions like SIN, COS, ROUND and text functions like UCASE, MID, LEN and
FORMAT.

Examples of Aggregate functions follow:

Average salary in the company:

SELECT AVG(salary)
FROM employee;
Results:
Expr1000
135
---------
43166.667

Note that MS Access will give a random name for the column (field) as a result of the aggregate
function. Use a Column Alias to re-name this column in the results:

SELECT AVG(salary) AS AverageSalary


FROM employee;
Results:
AverageSalary
-------------
43166.667

Give the name of the employee with the highest salary in the company (This is an example of a
subquery):

SELECT first_name, last_name, salary


FROM employee
WHERE salary =
(SELECT MAX(salary) FROM employee
);

Results:
first_name last_name salary
Sally Smith 55000

Show the employees with the highest salaries in each department:

SELECT first_name, last_name, departmentid, salary


FROM employee e1
WHERE salary =
(
SELECT max(salary)
FROM employee e2
WHERE e1.departmentid = e2.departmentid
)
ORDER BY salary DESC;

Results:
first_name last_name departmentid salary
Sally Smith 3 55000
Howard Brown 1 45000
Mary Green 2 41500
Jane Foster 4 35000

Note the two aliases given to the employee table: e1 and e2. These allow us to refer to different
views of the same table.

Show a COUNT of the number of employees in each department

SELECT departmentid, COUNT(employeeid) AS EmployeeCount


FROM employee
GROUP BY departmentid

Results:
departmentid EmployeeCount

136
3 2
1 2
2 1
4 1

In this case we need to use a GROUP BY clause to tell SQL that we want to do the count on groups
of departmentid.

SQL supports a variety of Scalar functions that operate on columns of each record instead of across
a collection of records. For example, various math functions and text formatting functions can be
used.

Show the First initial and last name of each employee

SELECT MID (first_name, 1, 1) AS first_init, last_name


FROM employee

Result:
first_init last_name
J Smith
M Green
E Jones
S Smith
H Brown
J Foster

Show the First initial and last name of each employee but make them all upper case

SELECT UCASE(MID(first_name, 1, 1)) AS first_init,


UCASE(last_name) AS Ulast_name
FROM employee

Result:
first_init last_name
J SMITH
M GREEN
E JONES
S SMITH
H BROWN
J FOSTER

Show the current salary and a proposed new salary for each employee:

SELECT first_name, salary AS CurrentSalary,


(salary * 1.04) AS SalaryWithRaise
FROM employee

Result:
first_name CurrentSalary SalaryWithRaise
Joe 43000 44720
Mary 41500 43160
Ed 39500 41080
Sally 55000 57200
Howard 45000 46800
Jane 35000 36400

137
Show the Date of Birth and the age of each employee in Department 3. This uses the Now() function
which returns the current date and time.

SELECT first_name, date_of_birth,


(Now() - date_of_birth) AS Age
FROM employee
WHERE departmentid = 3

Result:
first_name date_of_birth Age
Ed 1/9/1971 14901.5790625
Sally 8/19/1973 13948.5790625

Note that the “Age” is given in number of days. A better output would be to give this in years. So
divide answer by 365.

SELECT first_name, date_of_birth,


((Now() - date_of_birth) / 365) AS Age
FROM employee
WHERE departmentid = 3

Result:
first_name date_of_birth Age
Ed 1/9/1971 40.8262484462202
Sally 8/19/1973 38.2152895421106

Perhaps we do not want so many decimal places. In this case use FORMAT function (in MS
ACCESS)

SELECT first_name, date_of_birth,


FORMAT(((Now() - date_of_birth) / 365), "0.0") AS Age
FROM employee
WHERE departmentid = 3

Result:
first_name date_of_birth Age
Ed 1/9/1971 40.8
Sally 8/19/1973 38.2

Show all employees who have a birthday in August. this uses the MONTH function. Given a date,
MONTH (date) returns the month as a number. Similar functions include DAY and YEAR.

SELECT first_name, last_name


FROM employee
WHERE MONTH(date_of_birth) = 8;

Result:
first_name last_name
Sally Smith
Howard Brown

SQL SELECT From 2 or More Tables


In the FROM portion, list all tables separated by commas. This is called a Join. The WHERE part becomes the
Join Condition

List all of the employees working in New York:

138
SELECT employee.first_name, employee.last_name
FROM employee, department
WHERE employee.departmentid = department.departmentid
AND department.department_location = 'NY';

Results:
first_name last_name
Joe Smith
Howard Brown
Mary Green

The Where clause: WHERE employee.departmentid = department.departmentid is the Join


Condition

List each employee name and what state (location) they work in. List them in order of location and
name:

SELECT employee.last_name, department.department_location


FROM employee, department
WHERE employee.departmentid = department.departmentid
ORDER BY department.department_location, employee.last_name;

Results:
last_name department_location
Jones NJ
Smith NJ
Brown NY
Green NY
Smith NY
Foster PA

This is similar to a LEFT JOIN.

List each department and all employees that work there. Show the department and location even if no
employees work there.

SELECT department.departmentid, department.department_location,


employee.last_name
FROM employee RIGHT JOIN department
ON employee.departmentid = department.departmentid

Results:
departmentid department_location last_name
1 NY Smith
1 NY Brown
2 NY Green
3 NJ Jones
3 NJ Smith
4 PA Foster
5 CA NULL

What is the highest paid salary in New York ?

SELECT MAX(employee.salary)
FROM employee, department
WHERE employee.departmentid = department.departmentid
AND department.department_location = 'NY';

Results:
139
MAX(SALARY)
------------
45000

Joining more than 2 tables

To join additional tables, list them in the FROM clause and then add appropriate join conditions to
the WHERE clause.

In the employee/department database we also added a Project table and a Project_Assignment table.

Show each employee and project including the number of hours they work on each project.

SELECT first_name, last_name, project_name, hours_per_week


FROM employee, project_assignment, project
WHERE employee.employeeid = project_assignment.employeeid
AND project_assignment.project_number = project.project_id

first_name last_name project_name hours_per_week


Ed Jones RetailPOS 14.5
Ed Jones WebSiteDesign 12
Mary Green WebSiteDesign 6
Joe Smith Payroll 7
Mary Green Advertising 11
Joe Smith Inventory 4
Sally Smith RetailPOS 12
Sally Smith WebSiteDesign 22
Howard Brown Payroll 32
Ed Jones Inventory
Jane Foster Newbenefits 40
Howard Brown Advertising 4
Howard Brown Newbenefits 2
Joe Smith Advertising 15

Show the sum of the hours spent on projects managed by each department:

SELECT department_name, SUM(hours_per_week) AS Total_Hours


FROM department, project_assignment, project
WHERE department.departmentid = project.departmentid
AND project_assignment.project_number = project.project_id
GROUP BY department_name

department_name Total_Hours
Accounting 42
Finance 39
IT 96.5
Shipping 4

See if there are any projects managed by a department but where the project location is different
from the department location.

SELECT project_name, project_location, department_name, department_location


FROM project, department
WHERE project.departmentid = department.departmentid
AND project.project_location <> department.department_location

project_name project_location department_name department_location

140
Inventory NY Shipping CA

Cartesian Product

Cartesian Product of the two tables:

SELECT *
FROM employee, department;

Using DISTINCT to eliminate duplicates in the result. For example: In which states do our
employees work ?

SELECT DISTINCT department_location


FROM department;

Here is a combination of a function and a column alias (the AS part of the statement):

SELECT first_name, last_name, departmentid,


salary AS CurrentSalary,
(salary * 1.03) AS ProposedRaise
FROM employee;

Results:
first_name last_name departmentid CurrentSalary ProposedRaise
Joe Smith 1 43000 44290
Mary Green 2 41500 42745
Ed Jones 3 39500 40685
Sally Smith 3 55000 56650
Howard Brown 1 45000 46350
Jane Foster 4 35000 36050

Recursive Queries and Aliases

Recall some of the E-R diagrams and relations we dealt with had a recursive relationship. For
example: A student can tutor one or more other students. A student has only one tutor.

STUDENTS (StudentID, Name, Student_TutorID)

StudentID Name Student_TutorID


S101 Bill NULL
S102 Alex S101
S103 Mary S101
S104 Liz S103
S105 Ed S103
S106 Sue S101
S107 Petra S106

CREATE TABLE students (


StudentID VARCHAR(10) NOT NULL,
Name VARCHAR(20),
Student_TutorID VARCHAR(10))

141
INSERT INTO students VALUES ('S101', 'Bill', NULL);
INSERT INTO students VALUES ('S102', 'Alex', 'S101');
INSERT INTO students VALUES ('S103', 'Mary', 'S101');
INSERT INTO students VALUES ('S104', 'Liz', 'S103');
INSERT INTO students VALUES ('S105', 'Ed', 'S103');
INSERT INTO students VALUES ('S106', 'Sue', 'S101');
INSERT INTO students VALUES ('S107', 'Petra','S106');

Provide a listing of each student and the name of their tutor:

SELECT students.name AS Student, tutors.name AS Tutor


FROM students, students tutors
WHERE students.student_tutorid = tutors.studentid;

Results:
Student Tutor
---------- ----------
Alex Bill
Mary Bill
Sue Bill
Liz Mary
Ed Mary
Petra Sue

The above is called a “recursive” query because it access the same table two times. We give the table
an aliases called tutors so that we can compare different aspects of the same table. So on the one
hand we have students with tier name (students.name) and we have the tutors and their names
(tutor.name) However, as is, the results are missing something: We don’t see who is tutoring Bill
Smith. Use LEFT JOIN to solve this problem:

SELECT students.name AS Student, tutors.name AS Tutor


FROM students LEFT JOIN students tutors
ON students.student_tutorid = tutors.studentid;

Results:
Student Tutor
---------- ----------
Bill
Alex Bill
Mary Bill
Sue Bill
Liz Mary
Ed Mary
Petra Sue

Here is one more twist: Suppose we were interested in those students who do not tutor anyone? Use
RIGHT JOIN

New question: How many students does each tutor work with ?

SELECT students.name AS TutorName,


COUNT(tutors.student_tutorid) AS NumberTutored
FROM students, students tutors
WHERE students.studentid = tutors.student_tutorid
GROUP BY students.name;

Results:
TutorName NumberTutored
---------- -------------
142
Bill 3
Mary 2
Sue 1

WHERE Clause Expressions

There are a number of expressions one can use in a WHERE clause. Typical Logic expressions:

COLUMN = value

Also:

<
>
=
!=
=

Also consider BETWEEN


SELECT name, grade, "You Got an A"
FROM students
WHERE grade between 91 and 100

Using BETWEEN with dates: Show the employees who were born in the first 5 months of 1972.

For MS Access:
SELECT first_name, last_name, date_of_birth
FROM employee
WHERE date_of_birth BETWEEN #1/1/1972# AND #6/30/1972#

Result:
first_name last_name date_of_birth
Joe Smith 5/3/1972
Jane Foster 1/1/1972

Note for Oracle or DB2, enclose the dates in single quotes like so:

SELECT first_name, last_name, date_of_birth


FROM employee
WHERE date_of_birth BETWEEN '01-JAN-1972' AND '30-JUN-1972'

Subqueries using = (equals): Find the student with the highest grade.

SELECT name, grade


FROM students
WHERE grade =
( SELECT MAX(grade) FROM students );

Find the employee with the lowest salary:

SELECT first_name, last_name, salary


FROM employee
WHERE salary = (SELECT MIN(salary) FROM employee)

Result:
143
first_name last_name salary
Jane Foster 35000

This assumes the subquery returns only one tuple as a result. Typically used for aggregate functions.

Subqueries using IN:

SELECT last_name
FROM employee
WHERE departmentid IN (1, 3);

SELECT last_name, first_name


FROM employee
WHERE departmentid IN
(SELECT departmentid
FROM department
WHERE department.department_location = 'NY');

In the above case, the subquery returns a set of tuples. The IN clause returns true when a tuple
matches a member of the set.

Subqueries using EXISTS:

SELECT first_name, last_name, salary


FROM employee
WHERE EXISTS
(SELECT last_name
FROM EMPLOYEE e2
WHERE e2.salary > employee.salary)
AND EXISTS
(SELECT last_name
FROM EMPLOYEE e3
WHERE e3.salary < employee.salary)

Results:
first_name last_name salary
Joe Smith 43000
Mary Green 41500
Ed Jones 39500
Howard Brown 45000

The above query shows all employees names and salaries where there is at least one person who
makes more money (the first exists) and at least one person who makes less money (second exists).

The NOT EXISTS clause:

SELECT first_name, salary


FROM employee
WHERE NOT EXISTS
(SELECT last_name
FROM EMPLOYEE e2
WHERE e2.salary > employee.salary)

Results:
first_name salary
Sally 55000

144
Above query shows all employees for whom there does not exist an employee who is paid less.

INLINE SQL Queries

The result of a query is a table. Normally the results are shown to the user. However we can use the
reuslts of a query as the basis for another query. That is, the subquery becomes a table we can select
FROM. For exmaple:

SELECT first_name, salary


FROM (SELECT employee.first_name, employee.salary,
department.department_location
FROM employee, department
WHERE employee.departmentid = department.departmentid
AND department.department_location = 'NY'
)
WHERE salary > 35000

Recall this example:

SELECT s1.name AS TutorName,


COUNT(tutors.student_tutorid) AS NumberTutored
FROM students s1, students tutors
WHERE s1.studentid = tutors.student_tutorid
GROUP BY s1.name;

We might be interested in the maximum number of people one person is tutoring:

SELECT TutorName, NumberTutored


FROM (SELECT s1.name AS TutorName,
COUNT(tutors.student_tutorid) AS NumberTutored
FROM students s1, students tutors
WHERE s1.studentid = tutors.student_tutorid
GROUP BY s1.name
)
WHERE NumberTutored =
(SELECT MAX(NumberTutored)
FROM (SELECT s1.name AS TutorName,
COUNT(tutors.student_tutorid) AS NumberTutored
FROM students s1, students tutors
WHERE s1.studentid = tutors.student_tutorid
GROUP BY s1.name
)
)

SQL LIKE operator

Use the LIKE operator to perform a partial string match. Generally, the % character is used as the
wild card although in some DBMS, the * character is used.

Show all employees whose name starts with ‘S’

SELECT first_name, last_name, salary


FROM employee
WHERE last_name LIKE 'S%';

145
Show all employees whose name contains the letters ‘en’

SELECT first_name, salary


FROM employee
WHERE first_name LIKE '%ar%';

Note that characters within quotes are case sensitive.

Show all employees whose name contains the letter ‘e’ and the letter ‘n’ in that order:

SELECT first_name, salary


FROM employee
WHERE first_name LIKE '%a%r%';

Show all employees whose name contains the letter ‘e’ and the letter ‘n’ in any order:

SELECT first_name, salary


FROM employee
WHERE first_name LIKE '%a%r%' OR
first_name LIKE '%r%a%';

HAVING Clause Expressions

HAVING is like WHERE except that it works on aggregate functions. For example, assume we want
to get a total of salaries paid in each department but only want to show those with total salary greater
than $50,000:

SELECT department.department_name, SUM(salary) AS TotalDeptSalary


FROM employee, department
WHERE employee.departmentid = department.departmentid
GROUP BY department.department_name
HAVING SUM(salary) > 50000

Result:
department_name TotalDeptSalary
Finance 88000
IT 94500

Or we can put it another way. Show total of salaries paid by each department but only if the total is
greater than the average paid by each department

SELECT department.department_name, SUM(salary) AS TotalDeptSalary


FROM employee, department
WHERE employee.departmentid = department.departmentid
GROUP BY department.department_name
HAVING SUM(salary) > AVG(salary)

Suppose we are interested in the name of the department with the largest total salary. In this case we
need to find the MAX of the SUM

SELECT department.department_name, SUM(salary) AS TotalDeptSalary


FROM employee, department
WHERE employee.departmentid = department.departmentid

146
GROUP BY department.department_name
HAVING SUM(salary) =
(SELECT MAX(TotalDeptSalary)
FROM
(SELECT department.department_name,
SUM(salary) AS TotalDeptSalary
FROM employee, department
WHERE employee.departmentid = department.departmentid
GROUP BY department.department_name
)
)

Deleting Tuples with DELETE

DELETE is used to remove tuples from a table. With no WHERE clause, DELETE will remove all
tuples from a table.

Remove all employees:

DELETE employee;

Remove only employees making more than $50,000

DELETE employee
WHERE salary > 50000;

Remove all employees working in New York:

DELETE employee
WHERE departmentid IN
(SELECT departmentid
FROM department
WHERE department_location = 'NY');

DELETE will not be successful if a constraint would be violated. For example, consider the
department attribute in the Employee table as a Foreign Key. Removing a department would then
be contingent upon no employees working in that department. This is what we call enforcing
Referential Integrity

Change Values using UPDATE

The UPDATE command is used to change attribute values in the database. UPDATE uses the SET
clause to overwrite the value.

Change the last name of an Employee:

UPDATE employee
SET last_name = 'Smith'
WHERE employeeid = 'E101';

Give an Employee a raise:

UPDATE employee
SET salary = salary * 1.05
147
WHERE employeeid = 'E101';

Defining Views

It is possible to define a particular view of a table (or tables). For example, if we commonly work
with just 2 or 3 columns in a table, we can define a view on that table and then use the view name
when specifying queries. In MS Access, these are simply saved queries. So once we save a query
with a name, we can “query the query”.

Assume an employees table:


employees(employee_id, first_name, last_name, street, city, state, zip, department, salary)

Create a VIEW showing just the employee’s addresses:

CREATE VIEW emp_address AS


SELECT first_name, last_name, street,
city, state, zip
FROM employee;

Create a view showing juse employee’s names and salaries:

CREATE VIEW emp_salary AS


SELECT first_name, last_name, salary
FROM employee;

Create a VIEW summarizing the average salary of each department:

CREATE VIEW avg_sal_dept AS


SELECT department, AVG(salary)
FROM employee
GROUP BY department;

One can then query these views as if they were tables

SELECT *
FROM emp_address
ORDER BY last_name;

SELECT *
FROM avg_sal_dept
WHERE department = 'Finance';

148
Solving a Business Problem using SQL
There is a separate database that handles the Employee Benefits. That system does not use SQL. The
best we can do is copy and paste some data from a screen into Excel. Some benefits data is exported
to this spreadsheet: benefits.xls.

Due to a new tax law, any employees who are working in a department in NY are able to deduct a
higher percentage of their HEALTH benefits from their taxes. So we want to identify employees who
meet this criteria and send them a letter to let them know.

Your job is to import the benefits data into Access and write a query that can identify these
employees.

149

You might also like