Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Part I: Beginning MS Access. Relational database concepts: tables, records, fields, and keys. Relationships. Designing database schema. Normal forms; normalization of data model. Implementing schema: creating MS Access database. Tables in Design view and Datasheet view.
Chapter 1
Introduction to Microsoft Access
be declared upfront. Each column (field) must only contain data of the type it was declared. Data integrity is maintained automatically. Very good performance with up to tens of thousands of rows or even more Flexible user interface using forms (windows). Flexible reporting tool for better data presentation.
Development in MS Access
In Access, as well as any other relational database
system, development falls into two parts: database design and application design.
(contd)
Unlike Excel, in Access users should not enter
data directly into tables. Thats what the applications are for! Users enter data through the application. This greatly reduces chances of errors going undetected, and generally presents a nice, friendly way to work with data.
10
(contd)
Database design is different from application
design. A database is designed first, then the application. Access offers means for designing both databases and applications.
11
(contd)
Access stores all types of objects in .mdb files. A .mdb file may store both a database and an
application but they may also be stored in separate .mdb files.
12
(contd)
It is possible to create a non-Access application
that works with an Access database. And it is possible to work with a non-Access database from an non-Access application.
13
14
15
16
Conclusions
Microsoft Access is a desktop Database
management system Access offers much faster performance and more flexibility than Microsoft Excel. An Access developer designs databases and database applications. The former store data and the latter are used to work with the data.
17
Chapter 2
Database Design
18
19
Database table
A table stores data in records (rows) and fields
(columns). Each table should store information about one entity. Fields are attributes of the entity.
20
Creating a table
To create a table, one provides names of fields
what data type each field is going to be , what restrictions are placed on the fields, and which of them is (are) the primary key.
21
Primary key
Primary key of a table is a field or a group of fields that
uniquely identify each row in a table. There can be no two records with the same primary key in a table. There is always only one primary key in a table. A primary key may consist of one field or several fields. The latter is called composite primary key.
22
23
24
25
Foreign Key
Foreign Key is a field which is a primary key in
another table. Foreign key links two tables, setting up a relationship. In the example below, the tables are linked on the Employee_ID field.
26
Relationships
Relationships between tables reflect real-world
relationships between entities that these tables represent. For example, in a shipping company employee creates an order. In the database, there is a table that stores information on employees, and another that stores information on orders. The tables are linked with onetomany relationship, which means that an employee can create many orders, and each order can be created by only one employee.
27
Types of Relationships
One-to-one. An office computer can be assigned
to only one person. One-to-many. A publisher can print many books, and a book can be printed by only one publisher. Many-to-many. A book can have many authors, an author can release many books
28
Relationship - examples
We manage a building complex and want to
automate the management process There are several buildings in the complex, each has a different number of apartments. Apartments are of different size, each has a different number of tenants living in it.
29
30
Many-to-many Relationship
In relational databases, a many-to-many relationship
between two tables cannot be set. The answer to the problem is to introduce a third table that links the two main tables. The primary key in the linking table is a combination of primary keys in each of the two tables. The linking table may also contain data specific to the link. This converts one many-to-many relationship into two one-to-many relationships.
31
32
33
Normalization
Normalization is a process of organizing data in
an optimal way. That means eliminating redundancy and inconsistency Normalization is an integral part of database design.
34
Normalization: an example
We are creating a database on labor force based on existing documents
in the form of spreadsheets.
35
36
Note that the primary key for this table is composite and
consists of the fields age_group and sex.
37
38
39
40
Labor Force
41
42
43
Activity_Group
Officer
44
Entity-Relationship Diagram
45
47
Normalization process
Database designer does not have to strictly follow the
normalization steps. In fact, if a designer starts with a good picture of entities and relationships in to-be database, restructuring may not be required. Rather, he/she may design a structure and then test it to make sure that the database is normalized. The key to quick and efficient database design is to remember that each table must hold data on only one entity, and each field should be an attribute of that entity.
48
49
Referential Integrity
An essential feature if a relational DBMS supported by
Access. When set, database management system will ensure that there are no inconsistencies when inserting, updating or deleting data. In our example, this means that an attempt to add a record with a non-existing age group (attempt to insert an age_group_id that does not exist in Age_group table) will fail.
50
51
Data Types
In Access, like many other relational database
management system, each column (field) can hold values of only one data type. The type of each column is defined when the table is created.
52
55
56
57
NULL values
A field in a record may either have some value, or
NULL. NULL is not the same as zero or even an empty string. The latter are values. NULL means no value, nothing at all. Usually, primary key fields cannot be NULL. No field of a foreign key can NULL if referential integrity is set.
58
59
Field validation
Very often a piece of data can have only a limited range
of values. E.g., if the operator enters a year of 3002, this is clearly an error. It is possible to set up field validation at the table level using the Validation Rule property of a field. For the year, one may enter a validation rule like >1900 and <2100 With a validation rule in place, all new values in the field will validated, and violating values prohibited from being entered, in all data entry modes.
60
Cascade update/delete
When setting up a relationship in Access, there are
options to cascade update related fields or delete related records. The former means that if a records primary key is updated in the main table, the value will be automatically updated in child table(s). The latter means that if a record is deleted from the main table, related records will be deleted from child table(s).
61
Conclusions
In this chapter, we have covered:
The basics of relational databases; The role of primary and foreign keys; Normalization Type of relationships and how they are set; Data types; Specifics of physical database design in Access.
63
Queries
64
65
Queries in Access
Are database objects, just like tables, forms, or
reports. Can be saved or run at any time. Most often, queries are used by or in applications.
67
Select queries
Are used to retrieve data from a database Can derive da5a from many tables at once Can perform various operations on data, including
aggregation. E.g., we can ask for the average price of books in the library, or the total of economically inactive people across all age groups
68
69
Specifying tables
First we specify which table(s) will be used in the
query.
70
Specifying fields
Now, we specify which field(s) the query will
display. Asterisk (*) stands for all fields. labor_force.* means all fields form the labor_force table.
71
72
Selecting data
The first query selected all fields from the
labor_force table; and since we did not specify any criteria, it selected all rows. This is not very subtle, because we might just as well open the table. We always explicitly specify which field(s) we want to select. Usually, we also specify criteria for records. The query will only return records that meet the criteria.
73
74
The result
76
77
How it works
First, access finds records in the officer table where
the officer_name is Davies. Then it finds and displays records in the labor_force table whose officer_ids match the selected records from the officer table.
78
80
82
85
will restrict records to those whose values of the field officer_name are either Francis or Davies)
93
will restrict records to those whose values of the field price are form 20000 to 30000 inclusive.
94
officer_name LIKE [AJ]* will match officer names beginning with A or J. officer_name LIKE [A-J]* will match officer names beginning with letters A through J.
96
Joins
Are used to combine data from several tables In the Design View, joins are automatically
constructed along the lines of relationships as tables are added to the query. In SQL, joins must be explicitly stated. There are two types of joins: inner joins and outer joins. In (standard) SQL, all joins are defined in the FROM part of a standard, forming a table expression.
98
Inner joins
Create a result set where there are matches
between two tables on a selected field(s). The general syntax: a INNER JOIN b ON a.field1 = b. field2 [AND a. field3 = b. field4] Where a, b are tables and fielddX are linking fields. You can use any comparison operator, not just = (< ,>, <=,) but those are less frequently used.
99
101
Table aliases
On the previous slide, we took advantage of table
aliases. These are used in the FROM clause, and provide a way to give a table a short name. Syntax: table_name AS a or table_name a where a is an alias. Either way, the table table_name can then be referred to in the query as simply a. An alias can have several characters just as will, e.g. labor_force AS lf
103
Alternative syntax
For inner joins, there is an alternative, shorter
syntax: one may simply numerate tables in the FROM clause and specify join conditions in the WHERE clause. The INNER JOIN keywords is then not used. This is not part of the ANSI standard, but is supported on almost all database management systems. For outer joins, a valid table expression, with keywords LEFT JOIN or RIGHT JOIN, must always be provided in the FROM clause.
104
SELECT * FROM labor_force l, activity_group a WHERE l. activity_id = a.activity_id AND a.activity_description = Economically active AND l.year = 1980
105
Outer joins
Unlike inner joins, where matching records must
exist in both tables, an outer join takes all records from one table and then joins them with another table where there is a match. Outer joins can be left or right. Left joins table all records from the table on the left hand side of the join, and match them with records on the right hand side of the join. Right join does just the reverse. There is no keyword OUTER JOIN. There are, however, LEFT JOIN and RIGHT JOIN.
106
108
Parameter queries
Parameters are a mechanism that makes it possible to
supply restrictions on the query at execution time (vs. design time). In the easiest form, you can include parameters as terms in the WHERE clause by just providing a prompt: WHERE officer_name = [Enter officers name] At execution time, a window will be displayed requesting the user to enter the name. the prompt will be Enter officers name. The value will be used as though it was provided at design time.
109
Parameter queries
To reuse a parameter, specify the same parameter
(prompt) several times. The user will have to enter a value only once. SELECT l.*, [Occupation group:] FROM labor_force l, activity_group a WHERE l.age_group_id = a.age_group_id AND a.group_description = [Occupation group:] AND selected_group IN (15-19, 20-24)
110
Aggregation
One of the most important features of queries. Allows to perform such operations on data as
summing up, finding averages, finding minimum or maximum values. Aggregate functions are used to aggregate data. The most common are Sum, Avg, Min, Max, and Count. Can be combined with regular criteria.
111
Aggregation (contd)
The difference between regular functions and
aggregate functions is that the former always work within a record, whereas the latter operate across multiple records.
112
Aggregation (contd)
Find the average number if economically active
men in age group 1 for years 1980 through 1989
SELECT Avg(Value) FROM labor_force WHERE year BETWEEN 1980 AND 1989 AND age_group_id = 1 AND activity_id = A
113
Grouping (contd)
In the previous example, the Avg aggregate
function ran against the entire table restricted by the WHERE clause. Grouping is used to make an aggregate run against specific groups of records.
114
Grouping (contd)
List the number if recirds entered by each officer.
SELECT officer_id, count(*) AS [Number of records] FROM labor_force ORDER BY officer_id
115
Grouping (example)
Access first finds each distinct combination of
fields in the select list that are not aggregated. Then it runs the aggregate function against all records for each combination of these fields. In this example, Access finds all distinct officer_ids. Then it counts the number of records for each officer_id.
116
Grouping rules
Grouping requires the use of aggregate functions. If grouping, all fields in the select list must either
be grouped by or be aggregated (results of aggregate functions). There are no restrictions on which fields may appear in the WHERE clause. However, aggregate functions cannot be used in the WHERE clause. Several aggregates can be used in a query.
117
Aggregate functions
Sum(expr): sums up the values of the expression
expr. The expression can include field names, functions, and constants, but its results must be numeric. Example: Sum(value/1000) Avg(expr): calculates the arithmetic mean of the values of expr. Restrictions on the expression are the same as for Sum. Example: Avg(values) Min(expr), Max(expr): Display the minimum or maximum values of the expression expr. The expression may return a number, a string, a date.
118
119
Subqueries
You can nest SQL queries within other queries.
Such queries are called subqueries, and are usually used in the WHERE or HAVING clauses. Subqueries must always be in parentheses. You can use the result of a subquery as a term in an expression.
123
Subqueries: example
Find the total number if labor force per sex and
each year. SELECT year, sex, Sum(value) AS Total FROM labor_force GROUP BY year, sex HAVING Count(value) = (SELECT Count(*) FROM age_group) * (SELECT Count(*) FROM activity_group) ORDER BY year, sex
124
Subqueries: predicates
So far we have covered the use of subqueries
terms in expressions. These subqueries should always return one value. Subqueries can be used in more complex comparisons using predicates ANY, ALL, [NOT] EXISTS, and [NOT] IN.
125
129
UNION queries
Union queries consist of two or more SELECT
statements whose results are merged in the output. All of the SELECT statements in a union query must retrieve exactly the same number of fields, and data types of the fields must be identical.
131
UNION queries
SELECT *, Old AS [Revision] FROM labor_force UNION SELECT *, New AS [Revision] FROM revised_data ORDER BY year, age_group_id, sex, activity_id, Revision
For this statement to work, the tables labor_force and revised data must have identical structures.
132
136
Crosstab queries
Crosstab queries provide a mechanism to
transpose data. Normally, when we select data, we specify output columns, which can be fields from a table, or results of expressions on these fields. Crosstab queries, by contrast, let us retrieve output field names (and values) form a table. Crosstab queries group data both vertically and horizontally; on the left side of output table and across the top.
137
138
139
140
141
Crosstab queries
List labor force by year, sex, and economic
activity.
TRANSFORM Max(l.value) SELECT l.year, ag.group_description, l.sex FROM activity_group ac, labor_force l, age_group ag WHERE l.age_group_id=ag.age_group_id AND l.activity_id = ac.activity_id GROUP BY ag.group_description, l.year, l.sex PIVOT ac.activity_description
145
Crosstab queries
Characteristic functions
In VBA, there is a function IIf:
IIf(expression, true_part, false_part) expression is a condition to be evaluates; true_part is a value that will be returned if the expression is true; false_part is a value that will be returned if the expression is false. Thus, IIf(5<4,5 is less than 4, 5 is not less than 4) will return 5 is not less than 4.
147
148
149
INSERT statement
Is used to append record(s) to a table. Can append values typed in the statement (syntax 1) or values from another table (syntax 2). Syntax 1: INSERT INTO target [(field list)] VALUES (value list) target is the table to which records are to be appended.
152
154
156
UPDATE statement
Is used to modify existing data Syntax:
UPDATE target SET field1=expr1, field2=expr2, [WHERE criteria] target specifies the table whose records are to be modified, fieldX denotes fields whose contents are to be updated, expr is a value or expression whose results will be assigned to the field.
157
159
DELETE statement
Deletes records from a table. Syntax:
DELETE FROM target WHERE criteria
SELECTINTO statement
The SELECTINTO statement produces what
is called a make-table query in Access. SELECTINTO creates a new table and writes the results of the SELECT statement into it.
Conclusions
In this chapter, we have covered:
The role of queries; Types of queries Building queries in the Design View; The SQL language: simple select queries; inner and outer joins; aggregation and grouping; subqueries; union queries; crosstab queries; Action queries in SQL.
164
165
166
167
Creating a form
In the Design view, a form is created and edited.
In the Form view, the form interacts with the user.
168
Form elements
An Access form in reality is a window. Elements
that a form may contain are the elements of window interface: text boxes, combo boxes, labels, etc. These elements are called controls. The user enters data and receives feedback with the use of controls. There can be Visual Basic for Applications (VBA) code behind any form or control.
169
Controls
Available controls are listed as icons in the
toolbox at the left-hand side of the Access window in the Design view. To place control on a form, you select it in the toolbox and paste it on the form.
170
171
172
174
Create a form
178
179
180
183
184
185
186
187
188
189
190
The result
In the Form view, the user can select an activity
group from the list.
191
Option Groups
Option, or Radio, buttons, let the user select one
and only one, of a set of values in this way, they are similar to combo boxes. Since several controls participate in the selection (several buttons are present for the user to select one), the option buttons are grouped. We will use the Option Group control to let the user select an age group.
192
193
194
195
196
197
198
The result
199
Command buttons
Command buttons always trigger an action. The
wizard can configure button for mist common actions. E.g., lets place a button Delete Record on the form.
200
201
202
Reports
Are primarily intended for printing out contents
of the database, presented and formatted in a way that fits the users needs. Design is similar to forms, but reports are read only and usually do not interact with the user Can be created
With the AutoReport Wizard; With the (general) Report Wizard; In the Design View.
204
AutoReport Wizard
Creates a report that is simply a printout of a table
or query. To launch, select a table or query and select AutoReport form the New Object menu.
205
206
Report Wizard
The general Report Wizard is quite flexibel. Takes as input one or several tables or queries. Offers various grouping options. Offers several layouts and styles.
207
208
209
210
211
212
213
214
215
216
Report Section
While the report looks similar to form we have covered,
the most noticeable difference is that the report is divided into several sections. In fact , forms too can be divided into sections, but it is not as often used as with reports. Report Header, Page Header, Detail, Page Footer, and Report Footer are the standard section. The Report Header section appears once, at the beginning of the report, and Report Footer at the bottom. Page Header appears at the top of each page and Page Footer at the bottom of each page.
217
Report Controls
Although any control can be placed on a report.
Labels and Text Boxes are most commonly used. That is because report controls are not interactive. Labels contain static text, which never changes. The Caption property of a label determines what text it contains. Text Boxes are bound to fields. When it actually appears on the report, a text box takes the value of the field it is bound to as each record is displayed.
219
Grouping in reports
The Sorting and Grouping dialog box lets you
manually set grouping and sorting preferences. Fields on which the data are grouped are shown and can be selected in the Field/Expression column.
221
222
Aggregation in reports
Is performed with the use of aggregate functions
used in queries (Sum, Min, Max, Avg, Count). To get an aggregated field, the RecordSource property of the control (usually a text box) must be set in this format:
223
224
225
Reports: example
We want to reproduce the spreadsheets base don
which we designed the database. First, create a crosstab query that represents the data in their original format.
TRANSFORM Max(l.value) SELECT l.year, ag.group_description, l.sex FROM labor_force l, age_group.ag, activity_group ac WHERE l.activity_id=ac. activity_id AND l.age_group_id=ag. age_group_id GROUP BY l.year, ag.group_description, l.age_group_id, l.sex PIVOT ac. activity_description
226
227
228
229
230
231
232
234
235
236
237
238
240
241
242
The End
243