Databases
Databases
Specific Objectives
By the end of the topic the learner should be able to:
1. Define a database
2. explain the concepts of database
3. explain data organization in a database
4. create a database
5. edit a database
6. design a form
7. apply basic concepts of queries
8. create report and labels
9. print queries, forms and reports
INTRODUCTION
In our day to day activities, we are often faced with the need to keep, search for or give a report. i.e. use of tools
such as diaries. Traditionally human beings used to manage data and information manually by using simple
devices. However these methods have a number of weaknesses which include:-
1. Unnecessary duplication of data.
2. Boredom and time wastage especially when searching for a particular item.
3. Misleading reports due to poor data entry and organization.
4. Poor update of records.
However, in the current world electronic database have changed the way data and information is created,
managed and stored in order to address such weaknesses.
DATABASE CONCEPTS
- A database is a collection of structured and related data items organized so as to provide a consistent and
controlled access to the items.
OR
- A database is an organized collection of related data.
Database management
Is the process by which information is organized and stored on a computer in such a way that there is
efficient retrieval, updating and manipulation of the data.
MANUAL FILE SYSTEM
- This is where a file is set up in such a way that it holds information relating to a customer, project or even a
product and also employees’ information in an organization. For example in the hospital a doctor can
create a file and assign a unique number for each patient.
Major problems that arise with respect to Manual databases are:
a. Alteration – the records can be altered and falsified. Crucial documents such as financial records can be
wrongly changed by dishonest employees. Even though this can happen in any database system, it is
minimal due to the required log-in password, which requires only authorized personnel that can make
changes.
b. Data redundancy – it arises in the old filing system as a result of data duplication. New temporary files
are usually created whenever the original one is not available for some transactions which is a waste of
valuable space and other resources.
c. Data security – prevention of unauthorized access of sensitive information is never guaranteed in the
manual system.
d. Absent backup mechanism – backing up or records is not an easy process in the old filing system.
Natural disasters such as floods, earthquakes can destroy vital information.
Others include – destruction of vital information by employees, stealing, carelessness, data isolation and data
inconsistency.
- To create and manage database, they use Database Management System (DBMS) software. The software
facilitates the creation, organization and maintenance of databases. The DBMS lies between the physical
database itself and the users of the system. Examples of database management software include Microsoft
Access (Ms Access), Microsoft SQL Server, Oracle, FoxPro, DbaseIV, Lotus Approach and MySQL.
Database system
A database system consists of four major components:- data, hardware, software and users.
DBMS
Name
- The ellipses in the above figure represent the attributes. Student’s address, admission number, name etc
are called attributes.
- Any attribute or set of attributes can be used to uniquely identify a row in a table. Such attributes acts as a
candidate for a Primary key and is referred to as the Candidate Key.
- A candidate key can be chosen as a primary key depending on factors like uniqueness, usage etc. Thus a
primary key is a field or set of fields in a table that uniquely identifies every record.
A one-to-many relationship
Consider an order tracking database that includes a Customers table and an Orders table. A customer can
place any number of orders. It follows that for any customer represented in the Customers table, there can be
many orders represented in the Orders table. The relationship between the Customers table and the Orders
table is, therefore, a one-to-many relationship.
To represent a one-to-many relationship in your database design, take the primary key on the "one" side of
the relationship and add it as an additional field or fields to the table on the "many" side of the relationship.
In this case, for example, you add a new field — the ID field from the Customers table — to the Orders table
and name it Customer ID. Access can then use the Customer ID number in the Orders table to locate the
correct customer for each order.
Consider the relationship between a Products table and an Orders table. A single order can include more
than one product. On the other hand, a single product can appear on many orders. Therefore, for each record
in the Orders table, there can be many records in the Products table. In addition, for each record in the
Products table, there can be many records in the Orders table. This type of relationship is called a many-to-
many relationship because, for any product, there can be many orders and, for any order, there can be many
products. Note that to detect existing many-to-many relationships between your tables, it is important that
you consider both sides of the relationship.
To represent a many-to-many relationship, you must create a third table, often called a junction table, that
breaks down the many-to-many relationship into two one-to-many relationships. You insert the primary key
from each of the two tables into the third table. As a result, the third table records each occurrence, or
instance, of the relationship. For example, the Orders table and the Products table have a many-to-many
relationship that is defined by creating two one-to-many relationships to the Order Details table. One order
can have many products, and each product can appear on many orders.
A one-to-one relationship
In a one-to-one relationship, each record in the first table can have only one matching record in the second
table, and each record in the second table can have only one matching record in the first table. This type of
relationship is not common because, most often, the information related in this way is stored in the same
table. You might use a one-to-one relationship to divide a table with many fields, to isolate part of a table for
security reasons, or to split a table that would otherwise have too many fields. When you do identify such a
relationship, both tables must share a common field.
DATABASE MODEL
It is a specific method for describing the structure and processing within a database. The main database models
include:-
i. Flat file
ii. Hierarchical
iii. Network
iv. Relational
NB:
The current database model trend is towards new models namely object relational and object oriented models.
Flat File
The database holds only one set of data and is not any different from the manual files. For example, the teacher’s
assessment report may consist of performance cards for every student in a class. Another example is the cards
used in a library books catalogue. The cards are arranged sequentially for easy access e.g. alphabetically using
book’s title or by authors’ names. It is very hard to establish relationship between the items other than the
sequence in which they are stored.
Name Performance
Admission number 7680
Total marks 560
Number of subjects 8
Average 70
Position 2
Limitation
- It is not possible to insert a new level in the table without altering the structure. This makes it impossible
not to support many-to-many relationship.
Network Model
- These types of organization, links are used to express the relationship between different data items,
forming a network of data items. Access to one item can be through multiple paths and from any item. This
type of model brings about many-to-many relationship.
Validity integrity
- It checks if the data entered in the database matches the column data type. For example if a column NAME
is defined to be of character type and one tries to enter numeric value, then it will display an error
message.
- A DBMS checks this rule each time an add or update attempt is made on the column.
Entity integrity
- An entity refers to any data recorded in the database. The primary key is used as an identifier of the row.
- This does not allow duplication of data as no component of the primary key is allowed to accept a NULL
(blank or empty) value. For example, consider a table having student admission number and name,
where AdmNo is the primary key. Numbers cannot be duplicated.
AdmNo Name
7890 Ann
7870 Grace
7909 Jane
8790 Beatrice
Referential integrity
- It establishes a parent-child relationship between tables. A foreign key is defined on a column to declare
this constraint.
Example:-
STUDENT TABLE SCHOOL DETAILS TABLE
Programming module
- When a database becomes more and more complex, one needs a more powerful tool than the macros to
automate the database operations further.
- Most database software come with their own computer languages associated with them. For example
Microsoft Access comes with a language called Visual Basic included as a Module in the software. Using
this feature, you can create a program that will print a query result over and over again until a certain
condition is true.
Example:-
Print Student Report until Number of Students = 40
Pages
- Lets you publish live forms to a corporate intranet
Fields
- A field is a character or a logical combination of characters that represent a data item. For example, in a class
list, the student name is a field.
Records
- A record is a collection of related fields that represent a single entity. For example students’ performance
worksheet that may contain student’s name, class, admission number, subjects he/she doing, total marks,
average grade etc.
Tables
- It is a collection of related records. For example, the students’ file in a school database contains the
details of all the students in the school.
Database
- This is the highest in data organization hierarchy that holds all related files or tables. For example, a
school database may contain students and staff tables/files.
Summary:-
Fields
Value
F
A – Office button
B – Menu bar
C – Standard toolbar
D – Title bar
E – Object window
F – Status bar.
Form the application window, in the menu bar it has different features used for different purpose.
Under HOME on the menu bar, a list of menus will be displayed which includes:-
- View, Clipboard, Font, Rich text, Records, Sort and Filter, Find etc.
Under CREATE:-
- Tables in design view, Forms, Reports and others which include Macros, Modules, Query design and
Query wizard.
Under EXTERNAL DATA – this allows one either import some data from other application packages like Excel,
Word etc. This includes:- Import, Export, Collect data and Share points.
The Memo
- It is a data type that holds a variable amount of data from 0 to 65,536 characters for each record.
Therefore, if one record uses 100 characters, another requires only 10, and yet another needs 3,000, you
use only as much space as each record requires.
The Number
- It is a data type that enables you to enter numeric data; that is, numbers that will be used in mathematical
calculations. (If you have data that will be used in monetary calculations, you should use the Currency data
type, which enables you to specify many different currency types.)
The Date/Time
Format
- It determines how information appears on the screen when printed. For example, one can format a
number to scientific, currency, percentage or general format.
Decimal places
- For number and currency fields, one can specify the number of decimal places.
Input mask
- It automatically formats the field entry into a specified format. For example, one can enter a number such
as 02000100409874 and the input mask is set as 00-(00000)-000000, it is automatically displayed as 020-
(00100)-409874. This property is mostly used to format phone numbers and address entries.
- Others include – social security number, zip code, extension, password, long time and date, short time
and date, medium time and date etc.
- NB: - The input mask applies only to text and date/time data types.
Validation rule
- It is a logical expression that restricts the values to be entered in a field. For example, one can restrict
marks entered in a field to be between zero and a hundred, enter >=0 And <=100.
Validation text
- It is a message that appears once the validation rule is violated. For example, you may create a validation
text for the above validation rule to display “Please enter a number between 0 and 100” whenever the
user enters a value outside this range.
Required
- It determines if an entry must be made in the field before you proceed to the next field or record. For
example, if a primary key is required, one must enter it before you proceed.
Allow zero length
- It allows the user to proceed without making any entry in the field set as Zero length.
Indexed
- An index facilitates the organization of records for easy search. A primary key is an example of an index
set to No duplicates.
An index is a special internal file that is created to put the records in a table in some specific order. For instance,
the primary key field in the tblContacts table is an index that puts the records in order by idsContactID field.
Using an indexed table, Access can display records in a specific manner and quickly find any record within the
table using the index.
Primary Key
Deleting records
To delete a record:
1. Click the record you want to delete.
2. Click Home from the menu bar, under Records click Delete or Delete records. Alternatively right click at
the top left corner of the table; from the menu displayed select Delete Record.
3. A message appears, click Yes to confirm deletion.
Editing fields
To edit a field:-
a. Double click the field you want to edit.
b. Replace the cell content.
Searching for records
To find and replace a field:
1. On the menu bar, click Home; from the menu displayed under Find click Find (Ctrl + F) or Replace.
2. In the “Find What” and “Replace With” boxes, type the field to search for and replace with respectively.
NB:-
- You can use wildcards e.g. asterisks (*) if one is not sure of the search phrase. For example, if you wish to
search for all names that start with letter “J” in a Students table, type J*. All names that start with letter J
such as John, Jane, Joy, Joyce and James will be displayed
COPYING AND MOVING RECORDS
1. Select the record(s) to be copied or removed.
2. Under Home menu click Copy icon under clipboard to create a copy or click Cut icon to move.
3. Open the target datasheet. Under clipboard click Paste icon.
Sorting records
a. In datasheet view, select the records to be sorted.
b. On the Home menu under Sort and Filter, click Filter. From the menu displayed select either (Sort
Smallest to Largest / Sort Largest to Smallest).
Filtering records
- Use the same procedure like the one used in sorting records.
- Under sort and filter, select the type of filter; by selection or advanced.
- Under advanced; select the type of filter you want to use. Either Filter by Form; Apply Filter/Sort,
Advanced Filter/Sort.
MODIFYING A DATABASE
Modifying datasheet
To adjust the column size:
1. Point to the column border between the field’s header, then drag to the required size.
2. Alternatively, under Records in Home menu, click on More; from the pull down menu select column
width, a dialog box will be displayed from which you can enter width size. Default value is 11.75.
To adjust row height:
1. Point to the border between two rows in the row header and then drag.
2. Alternatively, under Records in Home menu, click on More; from the pull down menu select row height, a
dialog box will be displayed from which you can enter height size. Default value is 14.25.
To reorder fields:
1. Select the column of the field you wish to move by pointing to the desired field name.
2. Drag the column right or left to the top of the field where you want your field to appear and then drop.
Modifying table structure
When one creates a table, he/she may need to add more fields, remove some fields, reorder the fields or change
fields data types and properties. Before modifying the table, it is important to save a copy to avoid losing
everything in case you make a mistake.
To make a copy of the table:-
1. On the Office button, select Save As from the pull down menu. From the menu displayed besides select
Save Object As.
2. In the dialog box that appears, type the name of the table in the Save a copy as; e.g. Student table As
Student Details and then click Ok.
To modify the original table:
i. Open the table in design form by clicking the button that looks like a pencil and a set square under View
in the Home menu.
ii. Select design view from the pull down menu.
iii. Select the field(s) to be modified and make the necessary changes.
iv. Click the save button to save the changes.
NOTE:
If a table contains data and you make changes to the field data types, Ms Access may refuse to implement the
changes. To avoid this problem, exit without saving and delete all the records from the table then return to the
design view.
Importing tables:-
One can import a table from another database or a spreadsheet into the database. To import a table or a
worksheet:-
1. Select External Data from the menu bar; under Import, click Excel. From the resulting dialog box, select
the source and destination of the data.
2. Click Browse. File open dialog box will be displayed; look in one of the Save in folders and then select the
table(s) you wish to import and then click Open. Click Ok.
3. If the Spreadsheet contains more than one worksheet, select one of them then click next.
4. Specify the information about each of the fields you are importing. Click next.
5. Define the primary key of data in the worksheet. Choose my own primary key. Click next.
6. Click Finish.
The figure below shows a form designer for a table called STUDENT DETAILS
Unbound controls
Bound control
CREATING SUBFORMS
- Sub-forms are used to display data from several tables that have a one-to-many relationship. The main
form displays data from the parent table, and the sub-form from the child table. For example, to display
all the items on one order, a sub-form would be used.
Steps for creating a sub-form
- Open the form in design view.
- Under design in controls, select sub-form/sub-report icon displayed.
- Follow the steps on the screen that will take you through sub-form wizard.
- Select the table/query from which you want to draw the data for the sub-form.
QUERYING A DATABASE
- Queries are the fastest way to search for information in a database.
- A query is a database feature that enables the user to display specific records as well as perform
calculations on fields from one or more tables.
One can analyze a table(s) by using either a select query or an action query. Select query is the one we shall
discuss.
Select query
It is the most common type of query used for searching and analyzing data in one or more tables. Select query
lets the user specify the search criteria and the records that meet those criteria are displayed in a dynaset or
analyzed depending on the user requirements.
Run Query
You can also view the results of your query any other time by selecting the query, then clicking the Open button
from the database window.
Sorting the dynaset
To sort a dynaset:
1. In the sort row, click the down arrow that appears to specify the sort order i.e. ascending or descending of
the desired field.
2. Display the dynaset.
Creating a select query
a. Open the database that contains the records you want to update.
b. On the Create tab, in the Other group, click Query Design.
c. The query designer opens, and the Show Table dialog box opens.
d. Select the table or tables that contain the records you want to update, click Add, and then click Close.
e. The table or tables appear as one or more windows in the query designer, and the windows list all the
fields in each table. This figure shows the query designer with a typical table.
f. Double-click the fields that you want to update. The selected fields appear in the Field row in the query
design grid.
g. You can add one table field per column in the query design grid.
h. To add all the fields in a table quickly, double-click the asterisk (*) at the top of the list of table fields. This
figure shows the query design grid with all fields added.
Fig. 1
Creating calculated field
Fig. 2
Results of the calculated fields
Using Total functions
- With a query, one can analyze all record fields using the inbuilt functions such as Sum, Average, Minimum
and Maximum etc.
To use the total functions:
1. Open the query in design view.
2. Click the Totals button on the query toolbar.
3. Select the field you want to analyze.
4. For each field to be analyzed, click its cell in the Total row, and then select any of the functions.
Sum: - adds all the numerical data items.
Avg: - calculates the mean of all numeric data items in the field column.
8. In the layout dialog box, select the type of layout such as stepped and the click Next.
9. In the style dialog box, specify the report style by selecting Access 2007, Access 2003, Office, Metro,
Module, Median, Foundary, Windows Vista etc
10. Finally enter the name of your report, and then click Finish. The report will be displayed on the screen in
print preview mode.
Creating labels
- A label is a sticker or piece of paper put on an item for the purpose of identification. Examples of stickers
are mailing labels, label on the floppy disk where you write your name etc.
- Using the report label wizard, Ms Access lets you easily create labels of different sizes.
Steps
a. Open your database
b. On the database window, click Create on the Menu bar; under Reports select Labels.
c. In the resulting label wizard dialog box, specify the label size and then click Next.
d. From a series of dialog boxes displayed, specify the label size, font, text color, choose the fields to be
included on your mailing label by clicking the arrow > to move to the Prototype label.
e. You can sort your labels by one or more fields in your database by clicking > or >> and then click Next.
f. Enter the name of the Label then click Finish.
Label wizard.
Modifying labels
The way you modify a report or form, one can also modify a label by manipulating the layout controls.
Steps:
a. On the database window under Reports in the Create menu, click Labels or Open existing label and then
click Design View button under View.
b. The label design grid will be displayed. Edit the layout as desired, save and close the design grid.
c. To view the modified label, click the Preview button under the View button.
Printing the reports and labels
Before printing a report or a label, one must set the page options i.e. the margins, paper size and orientation.
a. Open the database that contains the report you want to print.
b. Select the Report you want to print, and then click the Preview button under View.
c. On the Office button, select print from the pull down menu.
d. Set the printer options i.e. the printer type, print range and number of copies.
e. Click Ok to print.
Macro design
Encrypting a database
Encryption compacts a database file and makes it indecipherable by a utility program or a word processor
especially on a networked environment. Encrypting a database does not restrict access to objects by users. To
encrypt a database:
i. Start Ms Access without opening a database because you cannot encrypt or decrypt a database when it is
open.
ii. On the Database tools menu, select Encode and Decode database.
iii. In the dialog box that appears, select the database you want to encode or decode and then click OK.
iv. In the Encrypt database dialog box that appears, specify the location and type the file name for the
encrypted or decrypted database, and then click Save.
Hiding database objects
i. Hide tables, queries, forms and reports and macros from casual users. This method of protection is the
least secure because it is possible to unhide the objects.
To hide objects:-
i. On the Show/Hide list under the Database Tools menu, select Property sheet.
ii. In the dialog box that appears, check Hidden.
iii. Click Apply, and then OK.