0% found this document useful (0 votes)
14 views

P2 - Unit 9 - Databases

Uploaded by

vijahat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

P2 - Unit 9 - Databases

Uploaded by

vijahat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

The database concept

A database is a structured way to store data so that it


can be retrieved using queries
Table name Field Field name
Animals
Table Animal Length TopSpeed
Brown bear 2.48 21.7
Elk 1.4 45.1
Record Lion 2.8 49.7
Elephant 6.5 25.7
Data types
• Some possible fields of a Etisalat Customer table
with their data type:
Field names Data type
FirstName Text/alphanumeric
LastName Text/alphanumeric
MobileNo Text/alphanumeric
DateJoined Date/Time
PhoneNumbersOwned Integer/ number
MonthlyBill Real/ Currency
Isprepaid? Boolean
Primary keys
• A primary key is a field, where every value stored in
it will be unique
• It identifies the record and it is unique , doesn’t repeat itself

Customers

CustomerID FirstName LastName Mobile DateJoined NumberOfCustomer


Orders
1 Grace Evans 07700 900 452 6/10/2020 17
2 Lily Thomas 07700 900 218 17/07/2020 23
3 Rosie Scott 07700 900 213 09/05/2021 11
4 Nadia Rahman 07700 900 892 26/02/2021 8
Validation
Validation allows rules to be placed on fields to ensure
that data input meets a certain criteria

• One rules is that a mobile number to start with a zero


• The rule for this is:
Like "0*"
• This means the text entered must start with 0 and then have
any other characters after
• What other validation could be carried out on the data?
Validation

• Data will need to be the correct data type (type validation)


• A length check can be used for the firstName, Lastname and
mobile number ( can’t have more then 10 digits).
• Please note: Phone number datatype is string because it
store numbers starting from 0. Integer/number datatype can’t
store numbers starting with 0
• The DateJoined may also be validated
A validation to check a date of joining can’t be after the todays
date
Validation Checks
• Validation is checking an input to see that it is
realistic or conforms to a set of rules
Validation check Meaning Example
Range check Check that a value is between two An age must be between 0
values and 120
Length check Checks to see that the length of input is Password length is at least 8
a given number of characters characters
Type check Check if a value is the correct data type A no of rooms in the school
can’t be letters/ strings or a
decimal number, it must be a
whole number
Presence check Check if a value is present or not "y" (present)
"" (not present)
Format check Check the input matches a format. Car plate number starts with
the Letter followed by Number

Checks: Presence, Format, Length, Range, Type, check digit


Algorithm to apply Length check
OUTPUT "Please enter Mobile number:"
INPUT PhoneNo
While LENGTH(PhoneNo) < 10 or LENGTH (PhoneNo) > 10 Do
OUTPUT "Invalid, length must be 10 characters“
Input PhoneNo
END While
Please note phone input is taken as a string that is why Length
method is used to find the length of the number

* Please note that for any validation code, following must be done
1. Use a while loop to ensure that input is taken in loop until correct input is
given by the user
2. Input must be taken prior to the while loop
3. While loop must have the condition which is not acceptable
4. Inside the while loop output a message that what is expected and take
input again
How to apply Presence check
• In a presence check we are just checking that
something has been input
output ‘ Enter Username’
Input Username

WHILE Username ==“ “ DO


output ‘ Nothing Entered’
Input Username
END while
Range Check
A range check is checking a number to see that it is in
a range of numbers
To check an age of new admission in school is from 3
to 20, inclusive:
Output “ Enter age “
Input Age
WHILE Age < 3 or Age > 20 DO
output ‘ Age Not in accepted range’
Input Age
ENDWHILE
Type check
• A type check makes sure that the data a user enters
contains the correct data type
• The below code uses a function Type that checks if
a variable is of a certain data type
Declare Length : Real
Output ‘ Enter Length”
INPUT Length
While NOT Type(Length, Real) do
OUTPUT “Invalid Entry, Input Again"
Input Length
End While
Format check
• A string can be checked to see that it has
the format that is required e.g. contains digits and
numbers in some specific format
• Car Plate Number in UAE has one Letter followed
by number. Function Meaning
isalpha() Contains letters
• String Functions are used
isalnum() Contains letters
In a programming language or numbers
isdigit() Contains digits
to check the format. Example isnumeric() Contains a number

Methods are given here isupper() Is in uppercase


islower() Is in lowercase
Algorithm for format check of Student ID, two letter & two digits

Output ‘ Enter Student ID, Two Letters and two Digits”


Input SID
While (SubString(SID,1,2). Isalpha() == False) or
(SubString( SID, 3,2 ).Isdigit() == False)
Output “ Incorrect ID”
Input SID
End while
Check digits
• A check digit is an additional digit at the end of a set
of other numbers designed to check for mistakes in
input or transmission
• Printed books have a unique barcode with an ISBN
(International Standard Book Number)
• Other products contain bar codes using formats such as UPC
(Universal Product Code)
• Both codes make use of check digits to make sure
they have been scanned or entered correctly
Calculating the check digit
• Check digits are calculated by
multiplying each number by a weight
of 1 or 3 as shown below
• The rest of the algorithm is then completed
ISBN 5 0 1 4 0 1 6 1 5 0 8 2 1
Weight 1 3 1 3 1 3 1 3 1 3 1 3
Multiplicatio
5 0 1 12 0 3 6 3 5 0 8 6
n
Addition Add all the numbers 49
Remainder Find the remainder when divided by 10 9
Subtraction Subtract the result from 10 1
Algorithm to calculate Check Digit
Declare ISBN : Array [1: 13] of Integer
Declare, Total , Remainder, x, CheckDigit : Integer
For x 1 to 12
Input ISBN[ x]
Next x
Total = 0
For x 1 to 12
if I x MOD 2 < > 0 then
Total = Total + ISBN[x] * 1
Else
Total = Total + ISBN[x] * 3
Next x
Remainder = Total MOD 10
CheckDigit = 10 – Remainder
ISBN[13] = CheckDigit
Verification
• Validation can only check that the data entered
is reasonable
• Verification is used to double-check that the data has been
typed in correctly. It has two types
Double data entry:
• For example, a user setting a new password may be
asked to type it in twice
• If the two passwords don’t match, they will be asked to enter the
password again
• This is known as double-entry check

Visual Check : Users may make a visual check of data


and then press a button to confirm it is correct
Three types of error in the
program
1. Syntax Error
2. Logical Error
3. Runtime Error
Syntax errors
• There are two syntax errors in the program
• Any instruction that don’t conform to the grammar of the
language, so the compiler doesn’t know how to translate
them, produces a syntax error

INPUT Num1 IF Num2 >= Num3


INPUT Num2 THEN
INPUT Num3 AND MaxNum = Num2
MaxNum  0 ELSE
MaxNum  Num3
IF Num1 >= Num2 AD ENDIF
Num1 >= Num3 ENDIF “ is missing
THEN
MaxNum  Num3 OUTPUT "Max number: , maxNum
ELSE
Logical errors
• The remaining error is a logical error
• The program will run, but it won’t work as the programmer
intended to
• It will give the wrong maximum number if Num1 is greatest

INPUT Num1 THEN


INPUT Num2 MaxNum = Num2
INPUT Num3 ELSE
MaxNum  0 MaxNum  Num3
ENDIF
IF Num1 >= Num2 AND Num1 >= Num3 ENDIF
THEN
MaxNum  Num3 Num1 OUTPUT "Max number: , maxNum
ELSE
IF Num2 >= Num3
Runtime errors
• Look at the following program:
INPUT NumberOfCakes
INPUT NumberOfPeople
cakePerPerson  NumberOfCakes / NumberOfPeople
OUTPUT cakePerPerson, "cakes per person"
• What will the program output if cakes = 10 and people = 2 ?
Output: 5.0 cakes per person
• What will the program output if cakes = 20 and people = 0 ?
Output: ZeroDivisionError: division by zero
Runtime errors
• The program outputs a “ZeroDivisionError”
• This is because you cannot divide a number by zero

• This is a runtime error as it will only happen when


the program is running
• There is nothing wrong with the syntax or logic of the program
Testing
• It is important that programs are fully tested to find
any errors that may occur
• Before testing, a test plan is created which will
test for, test data of following types are used to test
the program
• Normal data ( data withing acceptable range)
• Abnormal data ( data out of acceptable range)
• Extreme data ( largest and smallest Acceptable data on the
boundary)
• Boundary data ( largest and smallest Acceptable and
unacceptable data on the boundary)
Test Data
Program: Enter a number between 1 and 100
• Some examples of test data for the above range
check:
• Normal data: 5 , 14 ( acceptable data)
• Boundary data: 1 and 100 (smallest and largest acceptable
boundary), 0 and 101 ( Smallest and largest unacceptable
boundary)
• Extreme data: 1 and 100 (the smallest and highest acceptable
values)
• Abnormal: -50, 173, abc ( abnormal data is data that falls
outside of what is acceptable)
Reason of testing with different
types of data
Types of test Reason to test with this type of data
data
Normal Data This data is used to confirm that data in the acceptable range
is accepted by the program
Extreme data This data is used to confirm that smallest and largest data on
the acceptable boundary is acceptable, and no error is
produced
Abnormal This data is used to confirm that data out of accepted range is
data rejected, and error is produced
Boundary The data in the acceptable boundary is accepted and data at
Data the unacceptable boundary is rejected
Writing a query using SQL
• The SQL syntax for querying a database is:
SELECT … (list the fields to be displayed)
FROM … (specify the table name)
WHERE … (list the search criteria)
The SELECT statement
MemberID FirstName Surname Gender Town
1 David Johnson M Ipswich
2 Christine Bates F Woodbridge
3 Jasmine Hamid F Ipswich
4 Peter Okello M Colchester
5 Stephen Hines M Woodbridge

• The table above is named members


• The following SQL statement will select all the records and
fields from the table
SELECT MemberID, FirstName, Surname, Gender, Town
FROM members
Using a wild card
MemberID FirstName Surname Gender Town
1 David Johnson M Ipswich
2 Christine Bates F Woodbridge
3 Jasmine Hamid F Ipswich
4 Peter Okello M Colchester
5 Stephen Hines M Woodbridge

• You can use a “wild card” * to mean “all columns”


SELECT *
FROM members
• You can select specific columns in a query:
SELECT FirstName, Surname
FROM members
The WHERE clause
MemberID FirstName Surname Gender Town
1 David Johnson M Ipswich
2 Christine Bates F Woodbridge
3 Jasmine Hamid F Ipswich
4 Peter Okello M Colchester
5 Stephen Hines M Woodbridge

• The WHERE clause is used to select only records


satisfying a specified condition:
SELECT FirstName, Surname
FROM members
WHERE Town = ‘Woodbridge’
The WHERE clause
MemberID FirstName Surname Gender Town
1 David Johnson M Ipswich
2 Christine Bates F Woodbridge
3 Jasmine Hamid F Ipswich
4 Peter Okello M Colchester
5 Stephen Hines M Woodbridge

SELECT FirstName, Surname


FROM members
WHERE Town = ‘Woodbridge’
• Query result: FirstName Surname
Christine Bates
Stephen Hines
Operators in the WHERE clause
• You have already used some of these operators
in queries:
<. <, =, <=, >=, < >, AND, OR, NOT
• You can use these operators in SQL queries:
SELECT *
FROM members
WHERE Town = 'Colchester' OR Town = ‘Woodbridge'

SELECT FirstName, Surname


FROM members
WHERE (Town = 'Colchester' OR Town = ‘Woodbridge') AND
Gender = 'F'
SELECT queries
• Look at the following table named ‘Dogs’
DogID Name Breed Colour Gender Age
1 Coco Labrador Brown M 3
2 Milly Spaniel Black F 5
3 Sasha Retriever Golden F 4
4 Mark Labrador Black M 3
5 Marlee Retriever Golden F 2
6 Alfie Spaniel Brown M 6
7 Georgie Labrador Brown M 4

• Write SQL queries to find:


• All the names and breeds of female dogs
• All fields for dogs older than four (including those aged four)
SELECT queries
• Dogs table DogID Name Breed Colour Gender Age
1 Coco Labrador Brown M 3
2 Milly Spaniel Black F 5
3 Sasha Retriever Golden F 4
4 Mark Labrador Black M 3
5 Marlee Retriever Golden F 2
6 Alfie Spaniel Brown M 6
7 Georgie Labrador Brown M 4

• All the names and breeds of female dogs


• SELECT Name, Breed FROM Dogs WHERE Gender = 'F'

• All fields for dogs older than four (including those


aged four)
• SELECT * FROM Dogs WHERE Age >= 4
Sorting: the ORDER BY keyword
• ORDER BY allows a query to sort data by ascending
or descending order
• For ascending order
SELECT * FROM members
ORDER BY Surname ASC
• For descending order
SELECT * FROM members
ORDER BY Surname DESC
Sorting
MemberID FirstName Surname Gender Town
1 David Johnson M Ipswich
2 Christine Bates F Woodbridge
3 Jasmine Hamid F Ipswich
4 Peter Okello M Colchester
5 Stephen Hines M Woodbridge

• What will the result be for the following query?


SELECT FirstName, Surname , Town
FROM members
ORDER BY Town ASC
Result of sorting
• Result after execution of the statement:
SELECT FirstName, Surname, Town
FROM members
ORDER BY Town ASC

FirstName Surname Town


Peter Okello Colchester
David Johnson Ipswich
Jasmine Hamid Ipswich
Christine Bates Woodbridge
Stephen Hines Woodbridge
SUM and COUNT
• SQL is often used to count records or find the sum of
a particular field
• What do you think the results of the following
queries are?
SELECT COUNT(Quantity)
Receipts
FROM Receipts
ReceiptID Product Quantity Cost
SELECT SUM(Cost)
FROM Receipts 1 Apples 6 £2.20
2 Cheese 1 £2.50
Select COUNT ( Quantity)
3 Bread 2 £1.50
FROM Receipts Where
4 Pears 6 £1.80
Quantity = 6
SUM and COUNT
SELECT COUNT(Quantity) FROM Receipts
Result:
COUNT(Quantity)
4

SELECT SUM(Cost)
FROM Receipts
Receipts
SUM(Cost)
8.00 ReceiptID Product Quantity Cost
1 Apples 6 £2.20
Select COUNT ( Quantity) 2 Cheese 1 £2.50
FROM Receipts Where
3 Bread 2 £1.50
Quantity = 6
4 Pears 6 £1.80
Count (Quantity)
2
Practice
Animals
• Look at the table called Animal Height_m Weight_kg
Animals on the right Rhino 1.8 2000
Giraffe 5.5 1800
• create SQL
Emu 1.8 55
statements for the following:
Llama 1.7 200
• Find all animal names in Sea lion 2.4 360
alphabetical order
• Find all animal names and weights that are over 1000 kg
• Find all animals, including all fields that are over 2 m
Practice Answer
Animals
• All animal names in alphabetical order
Animal Height_m Weight_kg
SELECT Animal FROM Animals
ORDER BY Animal ASC Rhino 1.8 2000
Giraffe 5.5 1800
• All animal names and weights
Emu 1.8 55
that are over 1000 kg
SELECT Animal, Weight_kg FROM Llama 1.7 200
Animals WHERE Weight_kg > 1000 Sea lion 2.4 360

• All animals, including all fields that are over 2 m


SELECT * FROM Animal WHERE Height_m > 2

You might also like