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

~ [;j) Data bas es

inth1scha pteryouw rtltearnhowto


• understa ndwhat a database 15
• underst an d flat-fi le an d r elational • sel appropnateda tatypes
database stru cture s "' setdisp layfo r matsof data

l t ~;!e;sla nd prima ry and foreign key : ~~;o,~~m


:~~a~en::d,~!~ :od:~ae:~51

• ~~!~::'~~~~;t0~~~a~~;i~2:~;nd ~o~~~:~ak~dl::at a well-designed


re lalionat databases * performsearc hes
• understanddat a typesandsub- * perform calculations
types * Produce a report
• createaftat-li.le databas efrornan * e~p~rtdata andreportsloruse
existing datafile Wil h manothe r package
t create a relational database by * sort data in a re port.
creating relationships between
tab les
fer this chapter you will need these source lites,

: :~::~~:rs.csv : ::~~~~~;-~·~:v
t orders.csv ,.. teachers.csv

18.1 Create a database structure


18.1.1 What is a database?
A database is an organised collection of data. Adatabase program is software
1hich stores and retrieves data in a structured way. This includes the data that
i1 stored and the links between the data items. All databases store data using a
lfltemof files, records and fields:
~A field is a single item of data, such as a forename or date of birth. Each fie ld
has a field name that is used to identify it within the database. Each fie ld
contains one type of data, for example numbers, text ?ra date_.
Arecord is a collection of fields, fo r example, all the information about one
Derson or one item. These may contain different data types.
Afile (in database terms) is an organised collection of records, usua ~ly where
a![ the records are organised so that they can be stored together. Afile can
haveone or more tables within it.
;~iough alt databases have these three elements in common, th ere are two
, ·,,e,: flaHHe databases and relational databases.

:s:~-2Flat-file databases . h.
organised by rows and
-~·file database stores its data in one table, w:~~t ~:achers, each record
-ns. For example, in the following database a

I
,r=

18.1.3 Rela tiona l da ta bas es


A relational database stores data in more than one linked table, stored in a fi~e.
Relat ional databasesaredesignedsothatthesame dataisnotstored many t imes. The
tables within a rela tion al database are lin kedwith relationships(hence the name).

Key fields
Each t able wi t hin a relational database will have a key field. The relationsh ips
linki ngthetablesuse t hese key fields .
Primary and foreign key fields
lhese t w
Most tab les wilt have a primary key field that holds uni que data (no two reco rds
teacher's
are t he same in th is fiel d) and is thefleld used to ide nt ify t hat reco rd. Some
111ust co1
ta bles will have one or mo re fo reign key fie lds. A fo reign key field in one data
tab le s tore s values from a pri ma ry key fie ld in another table.
18 .1. 4
Using the earlier example, If we wan ted to add to t he t ab le the names of each and r
student taug htby each te ache ru singaflat-filedatabase,the t a ble wou ld look
Fro m th
like this:
storage
Tea cl!ar_lD For• n1m t / sur111mt Subject Room Slude nl FN1me Sludt nt_SN1me saved f,
in a na l
cou nt ri
lhere c
contair
datai s
toa re
report
from t
Altho1
th a n1
valu e
andt
V- --+J='"="ie' - ---'1cK"w","
""'-
'- 'E ongg,!is h 42 ~:~~;: ~: :~::

T~::~:
c-'J~K\'---
r:TY P aul l Tyrell Scie nce t;,;-----, ,~,:c
"':""'----e= "----- -l-~ ~ - --' You ,.,
Wil\ t
PTY Paul / Tyrell Science 8 G12351 Offici
·~,
/ SJ R
/ S=
l e= J•' - - -=
1' ,',a·=:~ ~•••";:;:.._•- ti'~
"'.'-::--t'J,~.,o~,d=
'"'----"
"';"~'"-1;'39_•~~tlI'G12348
s"t"i•~~ilI~J•~m
;,,_;,~~~~;~~~;~~~
Addy
students'table:
-
Studen!_ID Student_FName Studenl_SName -. - - -,

~:: ~ne
~l~ _ Sclence

~ ;:: I J~ - - ~

~ !Addy ll¾r:des
SJR AVA

~ ey Lemoc-
o- -7 c:=---+-c-----,
~ nie J~
These two tables are linked with a 'one-to-many'relationship, because one
teacher's reco rd is linked to many students' records. The primary key fields {which
must contain unique data) are the Student_ IO and Teacher_ID.

18.1.4 Advantages and disadvantages of using flat-file


and relational databases
fro m the example above you can see how much internal memory and external
storage space is saved by not storing data more than once. Imagine the space
saved fora school with over a hundred teachers and over a thousand students, or
in a national database with data on every driver and every vehicle registered in a
country.
There are three common types of changes which can be made to the data
1 contained in a database. Records/data can be added, edited or deleted. Because
data is not repeated in a relational database, each change to an item of data or
lo a record has to be made only once. It is also much easier for users to produce
reports from a relational database, where data is held in two or more tables, than
from two or more flat-file databases.
Although people often think that it is quicker to search using relational rather
th
an ftat-file databases, it is not always the case. In some cases, where indexed
~a!ues are used, it can be true. It depen ds on the structure of both databases
and the quantity of the data being searched.
You will need to create both flat-file and relational databases, but the data for these
'Iii{( be provided. You will be using Microsoft Access, which is part of the Microsoft
Office suite. WhenusedwithasingtetableAcce.ssisaflat-filedatabase,butitcan
a~o be a relational database when used with more than one linked table.

m
18D ATABASES

18.1. 5 Data types and sub-types


When you create a new database yo u names

~~~:l~;t!~:ccess es bu~\e in

for them . The list below shows?;0ee; ay have _diffe~~n\~~:ee~ ; ~\~;:: of field
depending on the pac~ag~:i~eis' called a text field. e
:~;e:{p~~ :~~:r~tn::e~\c and Boolean.

Advice . . A cess ·percentage'isno1 anu rneric data sub-


While ,tisllsted 1n thesyHabu~,in '
type.it isJustaforrnat11n9 option.

a characters (text) or num~ri~ data d a text


» Alphanumeric da.ta can store al~\ calculations. In Access this is cal\e
{numbers) thatw1llnot be used O .

field. ests) is used to store n~menc values


» Anumeric data type (as the ~ame su~gdoes not include num~nc data such as
that may be used for calculations. This d. n a\phanumenc data type.
telephone numbers, which should be _, tl~r\hmr: are different types of numeric
In Access this is called a number 1ie · e
fietd including: . l bers In Access you can select an
- intege r sub-type, whic_h storest~; ~t~:ise lo use a long integer field i.f
integerfieldoralongmtegerie · . 1•
it is. goit g ~o tconta;h~:~e;i~r a~~: :\~~~se number of decimal places, or a
- :;:;;i: ds~es~X~:;d number if this is set in the field properties when the

_i~~::~: which will allow currency formatting to be added to the


display. This includes currency symbols and regional symbols. The database
does not store these symbols as this would use up val~able storage space
_ date and time sub-type, which stores a date and/or time as a number.
A Boolea n (or logical) data type stores data as 0/-1 but can display it as Yes/
No (or True/False, 0/1).

There are other data types, such as autonumber (which generates unique
numbers), but as they are not available in all packages you do not need to worry
about them. Some packages, such as Access, have long and short versions of their
data types (for example, long text and short text) but these are still versions of
alphanumeric data types.
Ot her data types that are not studied in depth here can often be found in

\
comme~cial data~ases -.for example, placeholders. for media such as images,
soundb1tes and video clips. These are often used 111 web applications where a
back-end database holds the media to_ be disp_layed in another application, such
as a web page. As stated above, you will be usmg Access. Microsoft Excel is not
suitable for database tasks as you cannot define dat a types.
_____ ___ ____ __": _ _"_: :":•_'.areaoarabasc srru,

Task 1aa
5
~r:i:;;~\1~ted
i,leca:::~:v
you work for a sma ll garage catted ·oo dgy Dave·s Motor
;:1:;~Y
:~"Ja~as~;~:bsl~odth':~i~~::.ackagc. imp or t t he

r,e~ _ _ _ _ T oatatype

~=====--------~Text
\'{M ma~ufactured the car? Tex I --

Colour - - , - ~ -- - - Text
~ at we boug ht the ca r for ~Numeri c/Curren cy/2 decimal place s
~ ew1 tlsel l thecar for j Num eric/Currency/2dec;ma\places
Year T Num; nc.~
1 ',cc<ec,:9•c:_
' _ _ _ __
~ - -- --i
Ooe,the ca rneeddean ing? I Boolean/Log,cal

Some fiel d name~ are inappropriate . Create appropriate and meaningful fie\d
names fo r tho~e f1el~ s- You may add another field as a primary key field if your
soflware requ1rest h1s.
Save the database

It is important to make sure that you use the field names exactly as given in
aquestion, unless you are asked to provide appropriate and meaningful field
names. In this task you are asked for appropriate and meaningful field names, so
>tart by looking at the detailed descriptions given instead of the fie\d names, or
even examine the data to work out what information each field contains.
For this task, the descriptions help you to work out meaningful field names.
These should always be short enough to allow printouts to fit easily on to as few
pages as possible. The first example is Who manufactured the car?; this could
be shortened to Manufacturer or even Make . Make is short, meaningful and
appropriate, so use t hat. Price that we bought the car for could be changed
1~ Purchase Price, Purchase, p Price, p_price or just PPrice. Although Access
wilt allow any of these, do not use field names with spaces in them, as they may
cause problems if you try to do more complex operations with the database_. You
could use any of the other three options, as all would be ac_ceptable._ For this .
t~sk, use PPrice. Similarly, the next field can be called. SPnce. Consider the final
~td, Does the car need cleaning?. Simply using the f1eldname Clean could
give the wrong idea, as it could mean 'Does the car need_ cleaning?' o_r 'Is the car
~lean?'. It is sensible to plan this and make the changes in the .csv file before
importing the data into Access.
.'.:.~~'. ~.~-~~-~~·-····· ··· ·· ··· ······· ····· ······· · ls and ty pe in tlw _new
. . Movei nto therelevan_t cel dat a file.S ,wci t
Ope n the ca rs .csv h ie m Ex~e/. re sav1ng t ~e . 1 da ta t\le. Task
fieldna rn es Checkt hespell,ng ca reu1 lly dbefore
notlosethe origi na
0
with t he fil~namecarsl.csv so th_atyo u
f om an existing file
18a is contin ued in the next section.

18.1.6 Create a flat-file database r

~:c:i~hal the data ~iles a re in th e co~rec t fo rrnt;lfor you r regional se tt ings before

r
aucrn pting thi s section ls ee ln trnduct ion. page I - ---~

Open Accessandselectthe Blankdesktop

D
database icon.

Usethe 8rowse button - - - - - - - - --


toselectthefolderthatyouwishto use to store your
~
-,
I
database,thentype inthe filename,inthiscasetaskt8a, I
and select Create.
This should open a new database
similar to this.
i- : :L:-;_ -- - -
Import data from existing files
tn•<>,- ;;~~
To import thefile carst.csv (remember, we saved
itwith anewfilename inanearliersection)for ~ -· I
thetask,selectthe ExternalData tab. In the
i: o~~ntkh!~c::~~•tc~~c~ r~~:~:w~e~ e~:t : elect
- - - - - - - -- -- - •
\gr-- ! -~ ~=- I
From File. From t he sub-menu select the option • - - \
for Text File as files saved in .csv format are text 1 ·- - :; -w- :!.
~~e: ;~~hm:~ch data item separated from the next ~--- ·~ ? _ ; ~·.::-;.~--

This icon opens the Get External .. _. _ _..,,_


--=~~=~-:~---_-:_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_~~~-c"
Data - Text File window, like this. - - - - -.... ! ,,.,,,,. ,
Use the Cg] button to find the file _ ... _ ,___ _ ., .. _
carsl .csv thenclickonthe CEE button.

- ==-- - . , ___________,.
Makesurethat thetop radio button is selected.
This willmakesurethatthe data is saved in a
new data table. Click on c:Ji!:J.
..... . ___.,....,,_,,, ____ II

Advice
A common erro r is selecting the bottom option to
!in kth eda tabase to data held inas preadsheet.so
becarefu! to avoid this

I
--
-~ -------
[lick on the ~ button to open the Import j
3J ,.,.11mp.,,,'if,«if><Ob<I. •

Sp@ cification window. - - - - - - - - - - - ' Ht_, @~ -=:J ,m~= c


QFq,,,1 -
g
8_:;:\
!_itl<!Dollo,ltt:

18.1.7 Set appropriate data types


Check that all the field names and data types match
those specified in the task. In this case the PPrice r~ ,T.,..,n..-i -
Dff!)'6ef: 0f<u0ot!...
SPiice and Valet fields do not have correct data ' o . u , ~: 0 Qw,c!rq {.. ot<'IOo"'"
types. The PPrice and SPrice fields need to be changed
10 numeric (cu rrency) fields and the Valet fie ld needs to n.Dela,ler: ·7
be chanoPrl tn ;:i Rnnl P;:in /Yp~/No) field .
To cha nge the PPrice field into a numeric fie ld with a
currency sub-type, click on the Datil Type cell fo r
this fie ld and use the drop-down list to select the
Currency data type.
Repeatthisprocessforthe SPrice field.Forthe
V;ilitt field,usethedrop-down list tochangethe
Text data type into a Yes/ No data type. Whe n all of
these changes have been made, click on c:E,:J. Select
~ twice.
Inthenextscreen,ensurethattheradiobutton
for Let Access add primary key isselected-
thisaddsa new field called ID to the
table Access will use this as the prnnary
=
· ! :_; J ?re: : ::":;::
key f,e[d Chck o, CEO aad rn the o• • ,~- " - •- - , •• -

:~.:'.:·:~::~.'i,:,i',,:::·;.::'::'
'tbl' shows you that 1t 1s a table and
Cars' gwes relevance to the data Click
on ~ toimportthedataandon
I_..-•- ,_
L
,
,
,.. , -
~P

,
.. -____, "'
::,. - , : . ·
~: ...... :;:"
......- .,_
.. -
-· . _

[=1 todosethew,wd Oooble O •· I ••- • ~•-• :::,


•••••• ....-.. -
.::::: .::;
~=• \ :: ::.,, ::-- - • /;;:::;::
= ::;::: = j
;(:\~,: tb LCa cs tod"playthetable
1--· . - - ·-
--- - ---~ ~ = __!0!£

-
Advice
The icon in the Views section of the Home tab wi ll lei yo u change betwee n
Oata s heet and Design View

Edit data types


Changes to the data types, or other
properties, can be made from the Home
tab. In the Views section click on the
Design View icon.
Set the number of decimal places
The task instructed you to set the
PPrice field to two decima l places.
You can check this by clicking the left
mouse button in the PPrice field and
viewing the number of Decimal Places
in the General tab at the bottom of the r-1------= """- GJ
window. - - - - - - - - - - ' ::::-
; ;-::: =-l __ I - ~-:;:::,:;::;::::••
:...~-~
18 1 Cre a re a c a1 a b~ :i <' 5t uc ti. r~

!'"rtJis se
sett tt:i: ~~ot~~ti~~c~~ca~ on
, the ceU conLw '"
Paces. /,,,\'.! dn d use the drop-down

~; peJI 1i,is process fo r th e SP~i, fie ld .


set e display fo rma t of Boolean fi eld s
111
r, that ;~i~:t".-'':-'..,"•"~'.,""!"'=""~".;·i;,,;";";.:",;;";:°',:;",:;":,e- · \ ·-
l~tlie Genera l tab, selec~ the Format _ __
I _use the drop -down hst to select th ~ -
;:;,,,
1 optiOO, ~- .:::.i.':. -'-~ .
,e the database as task18a .
9
~dyjce
.,~Jneed percenta geva\ues,set
~teger ortong integer dat a type
L__.= - _

31
,.Jselec i Percentage fro mthe
f,rmat drop -down menufor th is
,1td

Activity 18a
y uwo rk for a s hop_s e lli ng oili~e supplies called "Easy as ABC". Using a suitable
0
ditabasepackage. 1rnportthe h\e s tationery.csv. Usethesedatatypes!oreachlietd.

ri,tdname Oalalype
~ --------- Numeric / Integer
T/?e of pro du cltobesold Tex t
~ ptionottheprod ucttobesold Text
01J an111yofi tems ineac h pack Nurneric/lnteger I
Text
Colour Nurne ri c/Curre11cy/2decirnatplaces
Sales pric e Nurneric/Currency/2decimalplaces
Purc hase pr ice
~O'c''°:::
c ""::_
' _ __ _ __ _ i.:B
:c:o:::
ole::oa::'.
o/,:Lo,:_
gic:::_
al _ _ _ __ _

Some fi eld names are inappro priate. Create appropriate and meaningful field
Mmes for those fields . Use the Code field as your primary key. Save the database .
1

18.1.8 Enter data using a table


~ata_ is normally entered into a database using a fo rm but, if a for m is not asked
~ it may be quicker to use the table to enter new data

Task 18b
,°:" the database th at you sa,ed in Task t8a. Add this new car to the database.
I~ • I Model 7 Colour I PPrke 7 sPri<e l y,.r l E,tras I Valet
I~ Fom I sitoer I so I 22B5 I 2008 I Atacrn Centrallocking Alloy Wheel;-( >es
13
\,
Open th (' database savedi n Task l8a .First click
oulhe ,- c..- button.
To open the table in O;itasheet View. double
clicktheleft mousebutton onthe table name. 7 _ ·,- ...
To make su re that all the rnlumns are fully 1.'
_;=====-=--
visible. dic k the left mo us e butto n on t he grey ;:._

J . •-·•,. . -. . _. •
square to t he left of t he ID field na me to I :i •

highlight the entiredatasheet. 1


a:::=c
;:;._
~=~::e~n~~!t
Movethe cursr d ~c::ms::=+:f't~ ~n ,.. = "T,_ _ ' ·-:~•-.~._•.,•.-p'•~~ .~,,'"
··: •••."..
ie!
1

r
looksllketh,s
0

;;~ktheo doob~ ' ,.;-:-,,::• • •.,; ~:"o,,, ;1° -~ ::: . .


;,
2M• rcKles C200 SIi\ th
> r-- ~ UQ?,,,~,..., c1 ... i~ \
This will adjust the display widths of the columns. Scroll down the list of cars (ti
until you reach the entry with a star next to it, which will allow you to add a C
New carat the bottom. d
I
P9nte • Sl'fl(" • Yeat • • V•le\ ~ 1,<1,-1 :"
f6,99S.OO ES,1'5.00 ](112C•ntr, 1Loc'<ingt.ea tl>erSeallAlloy 'Mlffb ·I
64 - 1! Cho
6.'>Sl<oda Odav•• Slack r • llow £5,995.00 £7.0'5.00 ..013Ce nlr~llockir>g lHth " r Seats lllloy WhHls
P.o<<al Slact Eli,49S.00 £7,f>45 .00 2011
67 Ford UCOrt Silo..
-~
Click the cursor in the Make cell for the new car and add 'Ford'. The new ID
number will automatically appear in the ID field, as you set this field as an
AutoNumber data type. Move the cursor and enter the Model , Colour, Year and
Extras data from the task in the same way. You can always use copy and paste
for some data. For example, if you need to make sure the spelling of 'Focus' is
correct, copy and paste it from record 47 above. For the PPrice and SPrice fields,
enter only the numbers (and decimal point if this is required). Do not attempt
to enter any other characters, such as the currency symbol. As you press the
<Enter> key after adding the prices Access will set the data into currency format.
Each time you press the <Enter> key, Access automatically saves the changes you
made to the data. The Valet field will automatically default to 'No'. Move into
this field and enter 'Yes' in this cell. Access will automatically save each item of
data as you enter it.
Check your data entry carefully using visual verification. This is when you
compare the original data on paper (in this case, in the Task 18b brief) with the
data that you have entered into the computer. Data entry errors in a database
may cause problems when you try to use the database to search or sort. Save the
database as taskl8b.

I
::-:-,a::;
~~ T8·'·,· ·1,·..k9..·A··~, ~·~·;;~;·d···t·o···a·· ·n···•··x·••·s··t·i·n·· ··· ··a..b·· ·•·· ·············· ·· ·· ······ ···.'.?:'. .:'..'.'.'.'. .'. .' ''.'.".'"."'."'.''.''.
91 1
::., ~ °"~1' 8~d,:,.:, ,:..~,
Of"' =
ha<~
y=o,~,-,,-,,~,,~T
:as~,~'8~b~~- - -- -
~,jda11ewl!eld10 lh e databa sec all ed
tozO for the las t ca r added lo the dat a base . s,:,,,~dt:::,cJ:';~~t~as
seeas
date ot 20
Task HI Oe
. ccmb er

~tt
~ ;:;o's,':!'.::'o~:dti~~~ ;~ \able tb lCMs
field aad eote, the ,.:,,' ~::: •low ,= T -. ; ~ - ~
c
--s
~:=&c-_·-~-
",i,e oata Type box use the drop-down
tiSl
1 coselect the Date/ Time t ype. _ __ _
o,oosethe rno~t appropriate Format for
t;;.J~~t!"f~~:a~~se, the task asksfor a
,al'fthe databas;astask18candselect

~ 1:;%tr~f~~~~:t:~~eu::~;:cord
it,e Datasheet V_
1ew . Move the cursor

¥;_~==:?:;~~i]
C•lendar 1eon to select the correct
date.

: may need to double click to the right of the PDate column to widen the
umn. Save the database as tasktSc

Activity 18b
Open the file saved in Activity 18a.
Add the se three items of stationery to the database.

~ Le,e, A,ch e;Le Lamioatedl"" A,ch Files I1 I Red I 57 .22 \ 28.9'


I No -,
~ 2 Lmc Anch File Lam iaatedl"" Anch Files \ 1 I Yellow \ 57.22 128.9' \ No \
283
Spioe Label Easllighl Spioe Labels I 100 I 1 30 1 13.8' IYes I
::• field names are inappropriate. create appropriate and meaningful field names toe thOse
ds. Use the Code field as your primary key. Save the database.
18 DATA:B:A
.::".::'..••.•..•..............•...•.
18.1.10 Create a relational database
Task 18d
Yo u work lorTawara High School. You :;
Faculty.Usingasu,tabledatabasepac g ·
.
1 :~~;~~~h: d ta about the Mat he mat ,cs
file teachers.csv. U Se

thesefie(dnamesanddatalypes
D1t1typ1
Fletd nam•
Te~t
SCode
Text
FName
Tex1
SName
Text
Subject
Numeric/Integer

Setthe SCode fie!dasakeyfield.lmportthefilestudents.csvasanewtab le


inyour database. Set th e Student _ lD fie ldasa keyfield.C reateaone -to-many
re lationshipasalink betweenthe SCode fieldintheTeac he rs·tab\eand the
Maths fieldintheStudents "tab (e.

Use the techniques you practised in Task 18a to impo rt the t wo tables into the
database so that each table looks tike this.

Th
;,
di

l
"'
"T,
ti
_ _ _ ...-=:::::::- b

- -•·--• I 1
Select the Database Tools tab _ _.__ _ _ - - - - -~- -
1 th
the Relationships icon. ' ocate e Relationships section, then click on
1_
I R,lationships ,
~! dh:.a~~~~ ~o0 ~~en
an.d s~lect each table in turn
n th/1ghhgh:e;~~1~h1~~ame time,
Add Tables pane. After both 1
a?ded, the Relation ships tab
this. - - -- - -
'~:=::: I -- 7
~c~e the cursor to sit over the bottom right ::: I . :::- I
nerof the Stu dents'tablesothat it changes
(Dfdrag arrow; expand it slightly so that all
:~:fi eld names are fu lly visible .
0
:: ~::~et~hee S; ~e;!o~:l~nrnr:~:t~:::~iirs' table
1
1
~:v!~~:;~~s~ ~~!dt~: ~~~r!~ucdheenr~\~~~!e~nd I·•
dickthe left mouse. button on the SCode
field. Hold down this button, drag the cursor X
Edit Relationships
cothe tblStudents table and drop it on the
'4, ths field. The Edit Relationships window
Ifill appear.
This window shows the link between the fields
in both of the tables. The bottom of the window
displays the type of relationship that you have
created .
You cannot change it here: if the relationship is
not the correct type, you have probably missed C casca<1el,Jldate Related Relds
1etting one of the key fields. ~ (:ascade~tellelated Records

1 Jo correctthis,clickthe ~ button,add Real!onshpType:


the key fi eld and redo this task. You will

I t; ::r~:nh;:of~~ taken

~
with the <Alt> and <Prt Ser> keys will copy [ '
this intotheclipboard.Pastethisintothe
document that you will present as evidence
:., _..
·11 U
,__,,_
-: -;:
-
~== o'••::.:-~; . :':.
"""' ,,...... . \

LEJ1--1
o'.your method.Whenyouclick ~ the ·~ .:! ,'.='_.::• .., . ..::::_-, -'-.: A

" nfoww;11faappearaadthe Relationsh;ps_J; ' '" 1 • f, - '


tabw1 lllooklikethis
1 .
this relationship $Code is the primary key
- _,._
~
....~-
,,
I •: : :~- J~
:::;- :;;.
fie ld in tblTeachers and Maths is the foreign -· .,_
key field in tblStudents. If you wish to view - · '
or_edit the relationship again, you can double
~hck the mouse on the relationship line that
Joins the two tables.
Save the database as Task1Sd.
~'-""llY I U C
Open the f il e sa ve d in A c l ,vit y !8 ti .
lmportthefileorde rs .csY. U s.:, the s et ,eld n.-i m esandd o t atyp cs

~ •m• - -I-'!"'~'' _- _7

t;s~~~_]_~:: :.~:::~
~ -"' No _ +,Nurn e':'_~lnle CJ:".!:_ _

A s s i gn a ne w field as a key f ield . Import the !,(e customers.csv. U se the s e f ield


name s and data t ype s -

fl¾ ldname Data typ e

Nam e Te ~t
Addre ss 1

All
Address_3 Text se li
Z,p_Code Ci
t.E isco unt % cf
N u mer ic/2decimalpl.ices .J (C<
thi
Set the Customer_ ro field as a key field . Create a one-to-many relat ionship
between the Code field in the Stationer y table and th e Prod uc t_Code f ield in th e u
cf
Orders table. Create a one - to - many r e lationship between th e Cu stome r_lD field in
th
the Customers tab!e and the Customer_No field in the Orders lab le
Take screen shot ev idence showing t he Cl
» fie ld na m e s and data types tJSed in th ese two tables 11
relationsh ips between the three tables .
........ .... ..... .......... .. :":.:".'.'."'.."".''".'.''d.•~ra1>.1se s1rut!Urt

__
,
_ _ llo_ .......

.,,.,..,.,..,,_ .... -~-- -..........


,.,-,,n-•
.....

1--=~
' :::.::·
~ -can moveeac hfieldacross
: to thefor rnusingthesingle ~N

::a~:ef~~; ~:~sb~:bal~:; ~::. - -\-'.:=====:!


irr01¥key.but,asyouwantalt Soencte
1
,111oft he fie lds move into the
!tfectedfieldsbox. Click on
~ . Choose the layout
af thescreen that you require
~otumnar has been chosen for
this task} before clicking on \
~ a gain. Changethetitle - - ·· ,.., . ,~.
d theformto frmStudents so AJI A«~. e- ~ A

thatyoucaneasilytellthatit :::_ , frmS1udenB ____,..,...

L •
is aform. Click on ~ to
ope11theform. - - - - - -i-"'=" . - _ _ .
n.bottomoftheformhasa , -- · I _
navigation bar which can be
""' to mo,e from record to - -
rerordlikethis. I ==-----_~
'::·-'7=·="=·=·:::·:::· ~_:-=-____,__,.,.. II,

Record: 1 of 188

I I .

'' .. '
.

.
.

' .

'
to creat~ theh_
11DATABASES

15 4"! ..
second data entry form, which should look llke " 7 I~ · :!
::: :::;t:id;,~:~ ~~\;:ks~~trt:~1;r ~ 1•,:m,-
meaningful field names to store the data may not be "-
easyforotheruserstoun~erstand,particu\arly ifl ey
h
-= ·]
·;-"'
donotworkwithdatabasesregularly. For example, ~-,-
5
ifchildrenweretoadd their data, simpteque lions_ -~
would be better than encoded field names, a\ong with -··
instructions on howtocomp\etethe form. •
Savethedatabaseastask18e. l--- ~·-····
18.1.12 Edit a data entry form

Task 18f
Qpenthefilesa~ed inTask 18e. Editthedataentry for m forstudentdatat o m akei t
easie r forstudentstoentertheirowndata

= , . ., ,. . ,. ._ ""-•
Open the database saved in Task 1ae. Double click the left mouse then
the
~~~~~nf:r::~:~t~:eerettt. w
_h_;,_
h ,·_, _;, _th_e _lis_t o_f_da_ta_b,_s_
e o_bJ_·ec_ts__. ,..
Select the Home tab. theo the drnp-dowo anow ;, the Views
mtfoo to get the drnp-dowo meo, fo, the d;ffeceot ways of
f1l
l:J
• ; T :t- ;· \& • :
·· • ... ,,:::..- '. '-:;,-: :
ASS
toe
imp
viewing the form. Select Design View. -------,1c:Ji--. frmleachers
to
Click on the Shutter Bar Open/Close Button to hide the
'Navigation pane', giving you more room to work. - - - -
"'
the

The tab will change automatically to Design . From the Tools • o,


th
sectionofthistab,selectthe PropertySheet icon. io
This will open th_e Property Sheet pane for the current object. to
Move the cursor mto the Form Header and click on the outline lik
ofthetextboxsothat itchangestoorange. lo
;,
T
t
F
I
f
I

I
;1
. If you wish 1,
, colours or
ext(orany l.
)this can be
ySheet. In
t~is e~ample, Text Align has been
ihdngedto Center.
r,e fore Color and Back Co lor
1,l'ealsobeenchangedby
1
dicli:ingonthem, then the
~ button to their right,
r,en by choosing colours from
1
t/lepalette.
As students would be expected
to enter their own data, itis
importanttotellthemwhat
todo. From the Controls
section of the toolbar, select
toe label icon.
!llaga new label box into
the header and enter some
instructionstohelpthestudents
tounderstandwhattoenter,
likethis.
In the Detail row each field has two boxes. The left one
IS the label box This 1s what 1s displayed to the user r~-=;,,_,_ . . ,.,. _
Thenghtbox 1satextboxandth1s1s101nedtothedata
t.ble This box 1s where, when the form is displayed m
formView, the user will enter the data Select each
1.-- rf-'"""~
·-~--· ·· "':"!:
'T ' '
1i ~
-
'@ ~ > P "'
... ;
..
llbe! mturn and edit the text so it is more meaningful f ff
forthestudents Youmayneedtoresizesomeofthe _ _ _ ... __
libel boxes so that all the text fits. Each box has a •
large drag handle m the top left corner that will allow ::::::- _
to drag the box around the form to rearrange the 11
formwithout resmng the box. This 1s useful 1f you ; aer 1 - · - - -:_=-
treating your form to a particular design From the
~ ws section of the toolbar, use the drop-down arrow
llnder the View u:on to select Form View like this.
I: .: : : ··-
:::.::;;:: ,.. _

=.::::::: ...
s.ive the database as task18f. ie--,,-=- --·_ · ._ •._,_·_ _ _ _,,_"'_--'_"'_'-"'
""""'L
18DATABASES

18 113 Add a new field to an existing form

userac
Task 18g
~=:nn:: /i:~d:a:::i: ::::;:~ to the students' data. Use th ese fie ld na m<c~. da ta
ora9the
t!i~ oer,
typesandfie!ddescript,ons: _ ___ ) ieftroo u
~ ~ uerl ption_ _ _ _ 1
0pen l~1
~~ ~~ The~ o o ~ a n d l 1 1nctw,11·e_1 friter '
T utor - =2 enarneof1he studenfj !\ltor ro'"'-111
10 , yea r
_____J

Open the database. Remember you hid the Navigation Pane . Restore it using the
ShutterBu Ope11/ CloseButton arrow. - - - - -- -- - [ ] rnthe r
button '
Open tblStudents in Oesign View. In the blank row belowthe'Science' field, ; 5: arld
enter the Field Name, Year_Group (you can11ot shorten it to Year as this is a t,1 o yea r
reserved word in Access -try it and see ... ). The Data Type always starts in Short
(lick C
Textformat;clickon that cell assig ne
and use the drop-down menu to
select N,mbec. I ! :'.'" '""'" - •- - - •-·•--'" ... values f
theset'
:::eo:::/;::,~e:~;~::;t' ~ - I ";"__ • _:~ ..'.::.. .• c.::. the val 1
For No
:::,;'.;(;:'h:,::~;·::::~:~; l~i"" •;~..;- --.---=- ~--·- :·;:::.,.,,,,"
f:.,__-.· ·--~== """'"" . .--
to 0 . -

~r=~
the database. fo the blank When y
click [:

i
row below this, add the new "" ""_..,_
~~etl: ~~:: sri~:;t the ! ::::: =.: :;:;::;;,:;,:: therad
Storet
drop-di
~f:help,':~e~:
1o
:;';~;~';h::::~
impco,ethe focm aod
1:--·
.§:. •
cs-, -===-
:_:::;;-:• -:
Year
Thisw
to save lotsofstoragespace, ...- .- - - issele
we know that the tutors' I ~ :. isstor
'.nitialsarethreecharacters withi
in leng th • l 11 the General tab -::::~- - ~ the s
; ~z:h;obt om, set the Field ~;.,'!.~=- (whic
tick/
toch
Save thechangestothetable, thencloseit
°" t
~pen frm Students in Desi n Vi
~::o; n to, give e~ough roogm to :~dpt~;
. .
~!ot~:!oiie~~ the Form Footer and drag Give
as
ea r ro up f1eldcoulda s.
canontyholdfivepossiblev~pearontheformasatext b se\e
7, ~• !I, 10 and 11) it wou ld be ues ~because Tawara Hi h S ox but, as this data

llil
i
ra.d1~ buttons (Access calls the:esu1t~ble fie ld for g chool only has years
w1thm an option group. From the Ot 1~n Buttons)
~he Controls section, select the e~,gn tab, in
rcon. You may aeed to use the deO''"" Gcoup _
A r;:;;;,
a =D
4'n
\?,l, [;.,J
1'

>'
t~
it. Op•dowa meau to control!
_1,14 Ed it a da ta ent ry form
18
.,s,radiobuttons
iheframeforthe 0pt1on Gr_ou ~ into
p-agoeuitsectionoftheform,chckmgthe

P1t~~s~:~~t:~~:i:;!~~sa~~t!~~d:!~
t~~::~:a~:~/~:ai:~~ Y~:re:~~ear
l,flll'(ea r11a nd anadditionaloptionfor'No
~rgro upselected'-beforeclickingon

:t:~
i::,10·
dt:;a~~f :~:~~
js: andselecttheoptionyoutypedinfor
e
year group se lected.
110
QickeeCJ·Eachlabelhasavalue
,ssigned toit. Acces.s has tried to assign
values for you, but you need to change all
tile settings in this example. Fo r Yea r 7 set
ttievatueto 7, Years set to 8, and soon.
for tloyea r group select ed set the value
to O.
Whenyotr have changed atlofthe values
click ~ -Inthenextwindow,change
the radio button from the top option to
Store the value in this field:. Using the
drop-down menu to the right, select the
Ym_Group field.
This will make sure t hat, when a radio button
~selected, the value for that radio button
~stored in the correct field, Year_Group,
withinthetabte.Click ~ tochoose
the style of options selected (radio buttons
(~hichthe software calls option buttons),

-
tide/check boxes, or toggle buttons) and
to choose how the Option box will appear I ......_.....-,,cu..,tifltf_,, ... _....o1,~(lllllall"•1a:1.
,.,_.,_.,.....,...,.p,r1ara,-.pt,apr,Wl!il•
I Cio:J.
on the form. Make your choices, then click

Give the frame a meaningful caption such


as Which year group are you in? before
>electing ~ .
C a.., ,.. - :
•.. ;:.--.._,_,..:.
::
,:-_ : :F:;!..1-1- ·-

ff{
*p
Drag the text box for the Tutor 1f~ ;:-~ •:::~
;::::~:\~fsu f1:1;~~ly
L tft • :.
I

ffi ·- '-~•
- -'-
aoeds to hold th,ee ''""""·
Res izethelabe{ boxontheleftand
1./ -~. I+! I ~4 - _[:
t1
addthetext Tutor as_thel~bel. The , -- -;- ,I j t-
textbox labe!lookshketh1s.
(lickthecursor on the Unbound
text box and_, within the Property
Sheet forth1scont rot selectthe
Data tab. In the Control Source
- -
~
:-
tor
l I I IJJ]
:
_-_

: :
_

: ..,,L:.kl
]unbound
--
OiNd year j roup ~ ct§ I
,.
;
-~
II
- - -..,__ , --' ,

I I_
box, use the drop-down menu to ii - 1

select the Tutor field . Propi:,_rty Sheet


1
The text box changes from unbound to show the Tutor fie ld. The
text boxes for English, Maths and Science are also too large
as they can only contain three-lettered staff codes, so reduce
a
thesethreefieldsizestogetherbyselectingal(threetextboxes
together and dragging the right edge in so that they match the
Tutor field. Save the database as task18g. The finished Design
view and Fo rm view look like this.
'd I Create a da la base srructu re

,1av1 ce
:'.::~:,;::;',~"::ar~i f:~-;;;:t~~~i~l: t;e<j,;,~~~;;-;~~\: need le 1 ,! , t~ ,dd ,1II ynur

g.J.15 Wha t do es a well- de signed form look like?


1
!he most i~portan.t feature of form .design is to keep the lorn, ~,mple. with
,ieai quesuons, usmg dosed questions where pos~iblP. This 11 il\ limitthe
different answers to be s.tored in the dat~base and will 111 ake it easiei to search
1
~~:u~~~b:~~·:Otcer~~:=~~nt~~:~~~:.h~~t~: ~~:ef~~~~e f •t)fM:l'; l{fy1\),Wj la f fl
bfiween each data entry bo:c.. ;:~;:::;,:-:;::..;;::,::_"":;.::;:------•- -
rtiis formhas many fe~tures of a well-designed dat.i entry ..... _,_..._ .,,.,_ _ .
rorrn.The formhas a.t1tlethatstateswhat datais bcing
ci:i1tected.. There aremstructionsonfillingin the fo rm.
nie quest1onsarenotjustthefieldnamesbutwritten ..,,_ ,_,,...,_.,,.,..,....,
~;:~ft~sbeE:~~:~~l~n~a:h~~r~p;!:~: s~:tc~ef:~ ::;::;:=, ..::~~="::.
nieforrn has been appropriately filled by the text boxes ....,,...,.-,~.... , . ! ',.•:~•:•••,,
bJtthereisenough white space to keep it from being ':'.,
overcrowded. Radio buttons (ordrop·down menus)are o ,-,.
usedwherepossible.Therearenavigationbuttons ~ - - ..
on theform(already addedbyAccess) toallowause~ to ,....
add new records and move between records. In this form - · ,_,., · ·· •. .....
a\l ofthedataisimportant;insomeformskeyfieldscan
bl'highlighted toshow that thisdata must be completed
tteforethe recordcanbesaved.
In Design View of the form , move and resi2ethecontrolssothatyourform \ooks
lile the diagramabove. Changethetexttoberightalignedtextineachofthe
~bel boxes. Re-save the database.

Use drop-down menus


!tis often easier for the user of a database to use a drop-down menu to select
data rather than typing each data item every time. These can only be used when
there are a limited num ber of possible entries for a field, so fields containing
data such as names could never use drop-down menus - unless they contained
e'1ery name in the world, which would not be practical.

Task 18h
Openthefilesaved in Task18g.
Change the Tutor fi eld so that the user can select their tutor
lromthelistofstalfcodesintblTeachers.

Open the fi le saved in Task 18g and open frmStudents in


Design View. Delete the controls for the Tutor fie ld (both the
labetand text box). You will replace the text box with ano!her
type of control. from the Design tab, in the Controls section
th ere are two suitable options, a combo box or a list box. If you
wish to allow the user to type new item, s i~to th
box would be suitable, but for this tas: w ere
y~ud~o:~~~~;a~:\~l;el~s:, lo
able toc1ddtothelistitems, select a li 5t box.

!~s~~: r~,t as
9the data
Drag the control onto the for'.fl. The L~st ! i°~h~i za rd w:_dow -o~en s. Selert t ~- -
::~~::~~~: l.,,eQ,wq .. a
isheldintheteacherst,;1ble.Clickon ~ .In .... ,... ~"='- u.-,.,. • ..,. __ ...,
';;::'.fE3~·.~"?~:'.:~
.-.":,·.
the next window select Tab le: tblTeachers then
clickon ~ .Doubleclicktheleftmouse
button on the SCode field to move it from the
'Available fields:· to the 'Selected fields ;', then
r, -, ,_
OB........_ .,. •..,.1o. i.,,. ...,
l!l~...... ....., .......... """" 1
dick ~ .Selectthe SCode fieldinbo~l ~ -.......,
and make sure that the 'Ascending' button is
visibte,toshowthelistinalphabeticalorder. I~
Click ~ . Adjust the SCode column
usingthedraghand\e,thenclick ~ width
.The r ,- - -- _ - --- ~ .........._
,,,.c.,..,

value that you select will need to be stored in the


Tutor field so select from the Storethat valuei n -
thi s field: drop down menu the option for Tuto r. - ~
Click on ~ Tutor, then change the label for the list box name from the
suggested name to Tutor, then click on CE:J. Resize/move the controls and
change the alignment of the text in the label to right aligned so that it matches
---------
the other labels. Save the database as task18h.

18.2 Manipulate data


18.2.1 Perform searches
You can search for data in Access using a query. This allows you to select a subset
of the data stored in your table. Each query is created, saved and can be used
a~ain later. If new data is added to the table, when you open a query again it
will select the subset from all the data, including the new data.
Task 18i
Open the file that you sa~ed at the end of Task 18c.
1
~~: ;::~:~u~~~i~; ~ocr~;_ made by Ford. Find the custome r a list of au \he cars

Open the database that you saved at the end of Ta k


open the table that you created earlier. Select th sC 18
y
r
ou do n~t need to
Que ries section. Click on the Qu ery Wiza rd ico/ rea e tab and find the
This is the easiest way of performing a search a d
Select the Simple Query Wizard and click on ~ pens the ~ew Query window.
Wizard window, make sure that the correct tabl · In the Si mple Query
Tables/ Queries_box. As this is your first query t~i~ai;~h~as bleen s~lec~ed in the
box, but each time you create a new query it will b h on Y Option in this
previous query rather than the table, you are likel s ow~ here. If you select a
O
Y get incorrect results .
be appropriat e to
t he fiel ds eJ<cept
that the garage
t,e
~1ug11
Pfric• field )
~e dat e the. ga rage pu rchased t he
I:......
:;t (~he ,tt• te fie\d). -

1
;1n
se~~~tpeO~: i~~dtd on
- ·
I;:~ ==i -- Jl
;;e single.arrow to remove them from
the selection. - - - ~-
:::;':,:,:•;: ~.;;,','"'"' ::-:..:~.:::::._. I
~ again.
eranameforthe
cymaybe'"medt,toa
point and the name you
may become the title =---
- ~ : ;;:_;.-.
-
- - j\

au may therefore wish • • ~_::_


:,: :::;;.'" ,arne to the qaecy ,ame. _ __:,;~ ,.. .

5electthe radio button for Modify


1he querydesig n,thenclickon
[l;O.
This opens the query in Design View.
Datasheet View can be seen at any
time by selecting the drop-down list
under the Vi ew icon. However, at the
moment the query will still contain
all of the records as you have not yet
~rformed the search, so make sure you
are in Design View.
To perform the query,
move the cursor into the
Criteria: row of the Make
field and type in Ford .
You do not need to use
speech marks as Access wilt
put these in for you. This
will extract only the cars
made by Ford.
Task 18j
Ope o the file that yo" saved at the ~:cd do~1:~1:\:8~;! the Ford s that need valeting

Thcmanagcrwo ll ld likCtOSCeJll
h for Task lBi. Make sure you hav:
Create a query in a similar way tote one S l ct all the fields an d, when 1~
tbiCars selected and not rour for~ qu~ r7• ; ~f the Make column and ~es in the
~,'.:;'~,~~,7/ ,:~',:;;~;',;~:,';;\:~::;'h, ,e[ectloo will took tlke th" aad ooly
: : =-.-
two cars wiU be found using t his search. ___ _

; '~, : :;,
.:;I... B

: h~::::alled an AND Query, because the Make has to be Ford AN D the Vale t fiel d

has to be Yes

Task 18k
Openthe file tha t yousavedattheend ofTask 18j
The manager would (ike to see all the deta ils of att the cars made by Ford or Vawi:halt.

Create a query in a similar way to the one for Task 18j. In the Simple Query
Wizard window, make sure that the correct table name has been selected in the
Tables/Queries box. Jfyou select one of the previous
queries rat her than the tab le, you are likely to get Field: Mak.e \ Mode\
incorrectresults. Table: tblCars tblCa11

;;'~;;:;',\;),'\~:'c:'.,~,:'.~~1"S;:~ ~:;::~~u"~~'. ~~,:


9
,~:: _0 _
selection will look like this. _ _ _ _ _ _ __.Jr--- Criter~a;, ·Ford· Or-Vauxha1r I_ 0

37carswillbefoundusingthissearch.

You might also like