Download presentation
Presentation is loading. Please wait.
1
Database Design & Development
3 theory lessons of notes on web pages Analysis, Design, Implementation (SQL), Testing & Evaluation
2
Contents Analysis Flat Files, Linked Tables & Key Fields
Questions Flat Files, Linked Tables & Key Fields Design: Tables & Entity Relationship Diagrams Design: Fields & Data Dictionaries Data Validation The Data Protection Act Contents page with links to lesson topics
3
Multiple Table Searches Data Modification Testing & Evaluation
Queries & Searching Questions Complex Searches Sorting Multiple Table Searches Data Modification Testing & Evaluation
4
Database Analysis The first stage of developing a database is to analyse the brief or problem that has been set. This should produce a set of functional requirements. Functional requirements set out what the functions of the database are – what the database must be able to do. For a database, the functional requirements relate to the data that has to be stored in the database and how it is stored End user requirements set out what the user expects to be able to see in a database and how they expect to be able to change the information stored.
5
Data Stored Databases are structured collections of information. The functional requirements of a database should state the information that the database will store. This will be used to define a structure for the information at the design. The brief or problem should be examined to identify what information is needed to be stored in a database. Alternately, a systems analyst may interview and liaise with clients to elicit the information from them.
6
Example: Department Store
The following problem description is used to create a database: Marcie’s Department Store needs to store information about their products in a database. They require the database to keep track of stock and its cost. They also want to be able to identify which departments sell products, where they are in the store, which manager (including their seniority) and how many staff deal with them, when they are due to train and if they have achieved their sales target. The department store needs to know how to contact the staff responsible for each product.
7
From the problem description, we can infer that the database will store the following information:
Products stocked Number in Stock Cost Which Department it is stocked in Who manages the department The grade or seniority of the manager Contact details for the department Number of staff in that department The next staff training day for that department If they have achieved their sales target The location of the product in the store
8
Data Visualisation & Processing
Additionally, the end user requirements should identify the way data in the database is processed and viewed. Data visualisation is about how the data in a database is viewed. It is possible to view data in a database in part. The end user requirements should identify which views need to be created: Marcie’s Department Store needs to view a list of department managers that achieve sales targets in order to consider them for promotion. Data processing is about how the data in a database is manipulated and changed. The end user requirements should identify operations that the users will be able to carry out on the data: Marcie’s Department Store needs to be able to apply a 10% discount to menswear and womenswear during the summer sale. At National 5 level, these end user requirements define the SQL queries you will have to create.
9
Questions – Analysis Answer questions in full sentences!
What is meant by the functional requirements of a database? Explain the difference between the functional and end user requirements of a database. The school uses a database to record information about all of its pupils’ timetables. Identify: Information required to be stored in the database. A visualisation likely to be one of the functional requirements for this database. An operation likely to be one of the requirements of this database.
10
Flat File Databases Flat file databases contain a single table of data
The databases you have created before National 5 level have been flat file databases The collection of all information in the database table is known as the file. This flat file database shows the information identified in the analysis stage for Marcie’s Department store: Each single item of information is a field. In this flat file database, the columns are all the different values stored for that field The collection of all the different fields about one item, person or object is a record In this flat file database, the rows are all individual records
11
Flat File Databases There are disadvantages to using flat file databases: Flat file databases can have data duplication – the same items of data can reappear across multiple rows Data duplication is inefficient in terms of data storage. It can also result in modification errors – where a change is made to some but not all of the duplicated data
12
Linked Tables Flat file databases should be split into linked tables to prevent the problems caused by data duplication Because information is stored in different tables, there is no longer any data duplication. This also removes the risk of modification errors At National 5 level, you are required to link two tables together.
13
Linked Tables Key fields are used to link tables together In the example below, the Department Name / Department appears in both tables. This allows the two tables to be linked together. The information in the different tables can then be joined together.
14
Key Field The primary key field in a table is a unique identifier for records in that table. Every table must have a primary key. The primary key can contain no duplicate values A foreign key is a field in a table that uniquely identifies a record in a different table Not every table requires a foreign key. The foreign key field in a table is usually the primary key field in the related table
15
Questions – Flat Files vs Linked Tables & Keys
Answer questions in full sentences! Describe the difference between flat file database structures and linked tables database structures. What is data duplication? Explain how it is inefficient. What is a modification error? How do linked tables prevent data duplication? What is a primary key? Explain why the value in a primary key field has to be unique. What is a foreign key? Why is the foreign key field in a table often the primary key of a different table?
16
Design: Tables & E-R Diagrams
Take the following steps to split up tables with data duplication Identify columns with duplicated data Split into two tables, one for duplicated columns, one for others Identify primary keys Add primary key from table with duplicated columns to other table as foreign key Department Department Name Extension No Manager Manager Grade Floor Number of Staff Next Staff Training Day Sales Target Achieved Product Product ID Product Name Cost No in Stock Department *
17
Identify Columns With Duplicated Data
The Dept Name, Extension No, Manager, Manager Grade, Floor, Number of Staff Next Staff Training Day and Sales Target Achieved columns all show duplicated values Make sure that the same duplicates always occur in the same rows – Where Department Name Foodstore is duplicated, it is always duplicated with the 4571 as the Extension No and Wendy Faulds as the Manager
18
Split Into Tables You will need to split the flat file table into two. One table should be contain the fields with duplicated values. All other fields should be added to the other table. Give the two new tables a meaningful name based on their contents Department Department Name Extension No Manager Manager Grade Floor Number of Staff Next Staff Training Day Sales Target Achieved Product Product ID Product Name Cost No in Stock Department
19
Identify Primary Keys You will need to identify a suitable primary key for both tables The primary key field should not contain duplicate values. Fields that are an ID number are usually used as primary key fields Mark the primary key field by underlining it or writing the letters PK next to it Remember, although we split the table based on duplicate values, the duplicate rows will be removed. This will allow us to select a primary key field for the table that contained duplicated values Department Department Name Extension No Manager Manager Grade Floor Number of Staff Next Staff Training Day Sales Target Achieved Product Product ID Product Name Cost No in Stock
20
Add a Foreign Key The final step is to link the tables by adding a foreign key The primary key from the table that contained the duplicated values should be added to the other table Mark it with a * or the letters FK to indicate it is the foreign key Department Department Name Extension No Manager Manager Grade Floor Number of Staff Next Staff Training Day Sales Target Achieved Product Product ID Product Name Cost No in Stock Department * These tables should now be used to create an entity-relationship diagram.
21
Alternate Approach – Non Atomic Data
Another way to split your database is to look for non atomic data. A (partial) record for one department could be presented as follows: Any field that includes multiple values such as Product Name should be split into another table. Primary & Foreign keys can be added as described above. Dept Name Foodstore Manager Wendy Faulds Manager Grade Senior Extension No 4571 … Product Name 1L Milk, 1Kg Potatoes, 1Kg Sugar… Cost £1.35, £0.95, £0.95
22
Entity Relationship Diagrams
An entity relationship diagram shows the tables that make up a database and the relationship between them. They can also show the individual attributes or fields in each table. Entity relationship diagrams are one of the two design documents that you require to design a database. Extension No Department Name Product ID Manager Product Name Manager Grade Cost Departments Products Floor No in Stock Number of Staff Sales Target Achieved Department * Next Staff Training Day E-R diagram showing entities, relationships and attributes
23
One to Many Relationship
Entity-relationship diagrams must show the type of relationship between the tables. At National 5 level, you will only use one to many relationships. In a one to many relationship, a row in the one of the tables can have multiple matching rows in the other table. However, each row in the other table can only match to one row of the first table In our relationship diagrams, a one to many relationship will be denoted with a line with a crow’s foot at the many end of the relationship Departments has a one to many relationship with Products. A department stocks many products. A product is only stocked in one department. Departments Products
24
Questions – Tables & E-R Diagrams
Answer questions in full sentences! Describe what is meant by an entity-relationship diagram. Describe what is meant by a one-to-many relationship Split the following flat file into two separate tables and drawn an entity-relationship diagram including attributes / fields.
25
Split the following flat file into two separate tables and drawn an entity-relationship diagram including attributes / fields. Create an e-r diagram that includes fields using the following analysis notes: Footballers play for a football team. They have names, date of births, goals scored, international caps and positions Football teams have a name, a stadium and the year they were founded. They also have a badge and a manager
26
Fields & Data Types A field is a single element of information about one thing When designing a database, fields have a number of properties to describe how the information will be stored. The data type of a field describes what sort of information it will store. This affects how the information is encoded in binary on the computer Database data types include: Text Numbers Date Time Boolean Different database will describe these type differently
27
Data Types Text: Text fields store letters, numeric characters and symbols. ASCII or Unicode is used for storing text Numbers: Number fields store numeric values using binary Date: Date fields are a special kind of number field. Multiple numbers are stored in binary to represent the component parts of a date: year, month, & day. Time: Time fields are a special kind of number field. Multiple numbers are stored in binary to represent the component parts of a time: hours, minutes, & seconds. Some databases combine date and time types into one field type.
28
Data Types Boolean: Boolean fields can only contain one of two possible values. These are usually either true or false. Some databases use yes or no instead. It is possible to store a Boolean field in a single bit. Other Types Not Covered in National 5: Calculated Graphic Hyperlink Currency
29
Field Properties When defining the fields of a database there are additional properties that have to be considered in addition to the field type. The size of a field defines how much storage space is allocated for each instance of the field. For text type fields, the size will be the number of characters that can be entered into the field. For number type fields, the size will be the number of bytes used to store the number. This directly affects the range of numbers available and the accuracy to which they are stored. A field can include a validation rule. A validation rule limits the values that can be entered into a field in a database. If the value does not meet the rule, it will not be stored in the database. The different types of validation will be discussed later.
30
Data Dictionaries A data dictionary is used to indicate the properties of all the attributes / fields in an entity / table. Data dictionaries will usually include The name of the field / attribute Its data type Whether or not it is the primary or foreign key The size If the field is required – if it must be entered when creating a record. Sometimes this will be included as a validation rule instead Any validation rules
31
Questions – Fields & Data Dictionaries
Answer questions in full sentences! What is meant by the data type of a field? Why do fields need to have a data type? Describe in detail the information stored and how it is stored for four field types Create data dictionaries based on the following analysis notes. You do not need to create validation rules Football teams: Cars Football teams have a name, a stadium and the year they were founded. They also have a badge and a manager Sample Car data: Make: Ford Model: Focus Reg No: SD15REW Fuel: Petrol Colour: Red
32
Validation Rules A validation rule limits the values that can be entered into a field in a database. If the value does not meet the rule, it will not be stored in the database. Validation rules can prevent inaccurate data being entered into a database and prevent errors in the processing and presentation of data happening as a result. At National 5 level, there are a number of types of validation you need to know about: Range Check Length Check Presence Check Unique Check Restricted Choice
33
Range Check Validation
Range check validation ensures that the data entered falls within a range of values. Range check validation is usually used with numerical values – including currency and date/time fields. Range check validation is defined using comparison operators and values. For example: >=0 AND <=10 This range check validation rule only accepts numbers between 0 and 10. You can chain as many comparisons and logical operators together as needed.
34
Length Check Validation
Length check validation ensures the values entered into a field are of a certain size. Length check validation is usually used with text fields, as numbers are stored differently in a computer. The LEN or Length function is used in conjunction with a comparison to create a length check. For example: LEN([Mobile Number])=11 This rule forces any value entered into the Mobile Number field to be exactly 11 characters long. Other comparison operators can be used to specify minimum and maximum lengths for a field. Logical operators like AND can be used to ensure the length falls between two values
35
Presence & Unique Check Validation
Presence check validation ensures that a value is entered into a field. A field with presence check validation cannot be left empty. Not every field in a database should have presence check validation. Some fields might have good reason to be left empty. For example, the Next Appointment field in a hospital patient record would be empty until the appointment has been scheduled Unique check validation ensures that the value in a field is different from the corresponding fields in other records. Primary keys automatically use both presence and unique check validation
36
Restricted Choice Restricted choice validation limits the user to selecting a value from a list instead of typing a value in. Restricted choice validation should be used when there is a limited number of acceptable values. For example the Playing Position in a table of footballers might restrict the user to choosing from “Goalie”, “Defender”, “Midfielder” and “Striker”. Restricted choice validation should also be used for foreign key fields. This can help ensure that the user only enters values that are stored in the linked table.
37
Questions – Validation Rules
Answer questions in full sentences! Describe each type of validation rule? A validation rule is created for the Batting Percentage field in a table of baseball players. The rule is: >0 AND <100 Identify the error with this rule and correct it Describe what the following validation rule does: LEN([Discount Code])>=4 AND LEN ([Discount Code])<=6 Create range check validation rules for the following Goals scored this season by a footballer Marks out of 20 in a test
38
Create length check validation rules for the following
Ensure that the Password field has at least 8 characters Ensure that the Credit Card Security Number field has exactly 3 characters Use the following analysis notes to create a data dictionary for a table. Include validation rules: Sample Academy Pupil data: Pupil ID: AA-314 (all IDs are like this) First Name: Alice Last Name: Anderson Age: 15 Guidance Teacher: Mr Smith (three guidance teachers to chose from – Mr Smith, Ms West & Mrs Lang) Mentored by: Emergency Contact: Mr Alex Anderson
39
Data Protection Act The Data Protection Act governs the keeping of data about people – how it is to be used, updated, passed on and deleted. The Data Protection Act does not apply to: Data kept for national security purposes Data kept for crime prevention purposes Data kept for taxation purposes Data kept domestically – i.e. your personal address book The Information Commissioner regulates the application of the act and complaints about data controllers can be made through his office
40
Data Subjects Data subjects are the people about whom information is stored on a database. Data subjects are entitled to compensation if their rights are breached. The data subject has the following rights: a right of access to a copy of the information comprising their personal data a right to object to processing that is likely to cause or is causing damage or distress a right to prevent processing for direct marketing a right to object to decisions being taken by automated means a right to have inaccurate personal data corrected a right to claim compensation for damages caused by a breach of the act In general, data subjects need to give their consent to the data controllers organisation to permit it to process data about them, but there are some exemptions for “legitimate interests”.
41
Data Controller The data controller is the person within an organisation who is responsible for ensuring that the organisation complies with the Data Protection Act. The data controller must ensure that: Only data described in the organisation’s entry in the Registrar of Data Controllers is collected, and it is used for the registered purpose. The data is accurate and up to date The data is protected from accidental damage and unauthorised access Data is kept no longer than necessary Data is not transferred to other countries without similar laws in place Data is not transferred to other organisations without the subjects consent Data users are people in the organisation that make use of the data in a database. The data controller must make sure they do not break the Data Protection Act.
42
Implications for Organisations
The responsibilities of data controllers have implications for organisations that maintain databases of personal information As data must be kept accurate and up to date, the organisation must spend resources to ensure this happens. Organisations must spend money on security software and other precautions to prevent hacking and keep data secure. Organisations must ensure data users are adequately trained to only use data for the registered purpose. Organisations can only use the data with the data subject’s permission, so they must ensure that they have permission or otherwise prevent the data from being processed. Failure to protect the rights of data subjects can result in fines and compensation payments, costing an organisation money.
43
Questions – The Data Protection Act
Answer questions in full sentences! What type of data does the data protection act apply to? List: The rights of data subjects. The responsibilities of a data controller Aside from having to pay compensation for breaking data protection law, describe two implications of the Data Protection Act for organisations that store personal data.
44
For each of the following situations, state whether or not data protection law has been broken and why: Patrice signs up to airline website and ticks a box marked “Tick to receive offers from our partners”. She receives an unwanted from a car hire company based in the destination of her flight the following week. Tom’s friend asks him to pass on the of one of their mutual acquaintances. Tom forwards them the address. Marlene asks the police to let her see the information they have stored about her during an investigation so she can see if it is correct. They refuse to release the data. Jack stops paying the loan on his car. The car finance company passes on Jack’s personal details to a debt collection company so they can recover the car. Ingrid’s data is stored in a shop database so they can phone her when the good she ordered arrive in store. A store employee calls Ingrid to survey her shopping habits.
45
Queries & Searching One operation that can be carried out on a database is searching it. Searches can be carried out using a SQL query. A simple search finds all the records in a database that match a criterion set on one field. Comparison operators such as =, > and < are used to match the value in a given field for each record. For example: Cost < 0.10 Matches all records where the value in the Cost field is less than 0.10
46
Comparison operators Comparison operators are used to compare two different values. In a database search they are used to compare the value stored in a database field to a literal value. The comparison operators are: < Less than <= Less than or equal to = Equal to > Greater than >= Greater than or equal to <> Not equal to
47
Query Design Before creating a query in SQL, you should design it first. The design will identify which fields are to be displayed as part of the results, what tables to use and any searching, sorting or modifications being made. For example: In the department store database, find a list of all the managers on floor 3 and their phone numbers so the owner can call and tell them about the renovation plans for that floor. Gives the following query design: Fields Manager, Extension No Tables Departments Search Criteria Floor= 3 Sort Ordering
48
SQL Query SELECT says which fields are going to be used in the query. The query design can be used to create SQL for the query. Each row in the query design is a line of the SQL query: SELECT Manager, [Extension No] FROM Departments WHERE Floor=3; FROM identifies which tables in the database are to be used. WHERE searches the records. In this case only departments of floor 3. SQL queries are always ended with the ; symbol.
49
Questions – Queries & Searching
To answer the questions, use the following database table Players: Create query designs to solve the following problems: Find all the name and position of the players that play for the Chargers List the name of all the left footed players and how many goals they have scored Player ID Name Position Goals Scored Preferred Foot Team 7 Louise Denver Keeper Left Academicals 14 Penny Haines Midfielder 2 Right Chargers 62 Eliza McLeod Striker 17 United
50
For each problem and query, identify the error in the SQL and correct it:
What is the name and preferred foot of all the keepers? SELECT Name, [Preferred Foot] FROM Players WHERE Position = “Striker”; Find the name, position and goals scored of all players who are left footed. SELECT Name, Position WHERE [Preferred Foot] =“Left”; List the Name and Team of all players that have scored 5 goals or less. SELECT Name, Team WHERE [Goals Scored] < 5;
51
Use the following query designs to create SQL queries:
What is the name and preferred foot of all the keepers? Find the name, position and goals scored of all players List the Name and Team of all players that have scored Fields Player ID, Name Tables Players Search Criteria Preferred Foot = “Right” Sort Ordering Fields Name, Team, Position Tables Players Search Criteria Goals Scored = 0 Sort Ordering Fields Name, Goals Scored Tables Players Search Criteria Position = Midfielder Sort Ordering
52
Complex Searches A complex search is a search that uses more than one search criteria. Search criteria can be joined together using logical operators such as AND and OR. Individual search criteria are evaluated using the values in the specified fields for each record, giving a boolean value of TRUE or FALSE. The logical operators are then evaluated using these values.
53
Example of a Complex Search
Using the complex search criteria: Preferred Foot = “Right” OR Goals Scored >=10 And the record: The condition Preferred Foot = “Right” is TRUE because the value in that field for this record matches exactly. The condition Goals Scored >=10 is FALSE because the value in that field for this record is actually less than 10 However, following the rules for OR, the overall condition is TRUE and this record will be presented as part of the search results Player ID Name Position Goals Scored Preferred Foot Team 14 Penny Haines Midfielder 2 Right Chargers
54
AND The AND logical operator evaluates to true if both the values on the left and right of it are TRUE. AND is often used to define a range of numbers. For example: Goals Scored >=0 AND Goals Scored <=10 This complex search criteria will match all the records where the Goals Scored field has a value between 0 and 10
55
OR The OR logical operator evaluates to true if either of the search criteria on the left and right of it are TRUE. OR is often used when you are searching for different exact matches on the same field: Position = “Keeper” OR Position = “Defender” This complex search criteria will match all the records of both Keepers and Defenders
56
Using Multiple Logical Operators
You can chain multiple logical operators together to make increasingly complex conditions. AND is evaluated before OR when you use many conditions. You can use brackets to force OR to be evaluated first. For example Goals Scored >=10 AND Position=“Striker” OR Position = “Midfielder” This condition will find the Strikers that have scored 10 or more goals and all of the Midfielders. To only find Strikers and Midfields that have scored more than 10 goals, use brackets: Goals Scored >=10 AND (Position=“Striker” OR Position = “Midfielder”)
57
NOT The NOT logical operator is applies to one search criteria. It inverts the value – TRUE becomes FALSE and vice versa. NOT is evaluated before AND and OR. You will not be required to use NOT in your N5 exam, but it can be useful when creating SQL queries – especially with boolean and Yes/No field types. For example: SELECT [Department Name] FROM Departments WHERE NOT [Achieved Sales Target]; This query will list all the departments that do not have the Achieved Sales Target field in the Department Store database ticked.
58
Questions – Complex Searches
To answer the questions, use the following database table Players: Create query designs to solve the following problems: Create a list the names of all the Midfielders that play for United. What is the name and team of all the Keepers and Defenders? List the teams with Strikers that have scored less than 5 goals. Player ID Name Position Goals Scored Preferred Foot Team 7 Louise Denver Keeper Left Academicals 14 Penny Haines Midfielder 2 Right Chargers 62 Eliza McLeod Striker 17 United
59
For each problem and query, identify the error in the SQL and correct it:
List the names of all the Defenders and Midfielders who have scored more than 5 goals SELECT Name FROM Players WHERE Position = “Defender” OR Position = “Defender” AND [Goals Scored] < 5; What is the name of all the Chargers Defenders? WHERE Team=“Chargers” OR Position = “Defender”; List the Name and Team of all players that play for United and for Albion. SELECT Name, Team WHERE Team=“Chargers” AND Team=“Albion”;
60
Use the following query designs to create SQL queries:
What is the name and preferred foot of all the keepers? Find the name, position and goals scored of all players List the Name and Team of all players that have scored Fields Player ID, Name Tables Players Search Criteria Preferred Foot = “Right” AND Position = “Midfielder Sort Ordering Fields Name, Team, Position Tables Players Search Criteria Goals Scored = 0 AND Team = “Rovers” Sort Ordering Fields Name, Goals Scored Tables Players Search Criteria Position = “Midfielder” OR Position = “Keeper” Sort Ordering
61
Sorting A database sort puts the records, or results of a search, into order. A field can be specified as the basis for sorting. The sort can either be ascending (lowest value first) or descending (highest value first). For example: Sort by Name in ascending order The records will be displayed ordered by the Name field, starting at A and ending at Z.
62
Secondary Sort Fields A secondary sort field can be specified. When the values in the primary sort field are the same, the secondary field will be used to differentiate between the records. Here is an example of a sorted list of names. The primary sort field is the surname in ascending order. The secondary sort field is the first name in ascending order: Dave Small Alice Smith Bob Smith Carol Smith Aaron Stewart
63
Query Design Query Designs should include how the results are to be sorted where necessary. Searching and sorting are both optional parts of a query, so it is possible for the rows in your query design to be blank. If no ascending or descending order is specified, you should assume ascending order is used. For example: In the department store database, find a list of all the managers and the number of staff they have. List the order from the top floor downwards. Use the name to sort departments on the same floor. Gives the following query design: Fields Manager, Number of Staff Tables Departments Search Criteria Sort Ordering Floor descending, Department Name ascending
64
SQL Sorting ORDER BY indicates that the results of the query will sorted on the following fields. The query design can be used to create SQL for the query. Each row in the query design is a line of the SQL query: SELECT Manager, [Number of Staff] FROM Departments ORDER BY Floor DESC, [Department Name] ASC; The primary sort field is listed first. The DESC keyword indicates it will be sorted in descending, or highest to lowest order. The secondary sort field is listed second. The ASC keyword indicates it will be sorted in ascending, or lowest to highest order.
65
Identifying a sort You may be asked to identify how a database has been sorted. This will always be a sort on two or more fields The steps to identify a sort are: Identify the primary field for the sort – This should be the only field that the values go completely in order through the entire column. State if the primary field is sorted in ascending or descending order Identify groups of rows in the primary sorting field that have the same value Check each other column for evidence of sorting – only look at the rows with the same value in the primary sort field State the secondary sort field and if it is sorted in ascending or descending order
66
Identifying a sort Date is the only column that is in order for all the rows It is the primary sort field, in ascending order These are the groups of rows with the same value for date We have to check each group to see what order it is in So this database is sorted into date ascending order, then time ascending order
67
Questions – Complex Searches
To answer questions 1 & 2, use the following database table Players: Create query designs to solve the following problems: Sort the table to show the players in order of the number of goals scored. When two players have scored the same number of goals, list them in order of name. What players have scored more than 20 goals.? Sort the results in order of position then team name. Player ID Name Position Goals Scored Preferred Foot Team 7 Louise Denver Keeper Left Academicals 14 Penny Haines Midfielder 2 Right Chargers 62 Eliza McLeod Striker 17 United
68
Use the following query designs to create SQL queries:
What is the name and preferred foot of all the keepers? Find the name, position and goals scored of all players List the Name and Team of all players that have scored Fields Name, Team Tables Players Search Criteria Sort Ordering Team ascending, Name ascending Fields Name, Team, Position Tables Players Search Criteria Position = Striker Sort Ordering Goals Scored descending, Team ascending Fields Name, Goals Scored Tables Players Search Criteria Preferred Foot = Left and Position = Striker Sort Ordering Team descending, Goals Scored ascending
69
Identify the primary and secondary sort fields, as well as whether they are sorted in ascending or descending order, used to sort the following tables: What is the name and preferred foot of all the keepers? Find the name, position and goals scored of all players
70
Multiple Table Searches
At National 5 level you are required to create SQL queries that use up to two linked tables A join combines rows from two or more tables. An inner join or equi-join selects record that have matching values on the primary and foreign key. Joining two tables creates on big table temporarily that can then be searched and sorted: Foodstore products in the Products table are matched up to the Foodstore record in the Departments table
71
Query Design Query Designs for multiple table queries simply include both tables in the table row. You can identify this from the fields that appear in the fields row, or the search criteria row. If fields from a table do not appear in the fields row, but are used as search criteria, the table must be included in the tables ro For example: What is the name of all senior grade managers that sell products for less than £5. Gives the following query design: Fields Departments.Manager Tables Departments, Products Search Criteria Departments.Manager Grade=Senior and Products.Cost < 5 Sort Ordering
72
Multiple Tables & Field Names
When creating queries with multiple tables, it is possible for there to be ambiguity on the name of fields. This occurs when the same field name has been used in two different tables. It is most likely to occur with the primary and foreign keys. To make it clear which field you want to use, include the table name as well as the field name, separating each with a dot. Departments.Department Name This is the Department Name field from the Departments table. If a field name is not repeated in the other table, you do not need to specify the table name
73
SQL Multiple Tables INNER JOIN indicates the two tables to be joined together. The query design can be used to create SQL for the query. The FROM clause when using two tables takes the form shown below: SELECT Manager FROM Departments INNER JOIN Products ON Departments.[Department Name] = Products.Department WHERE [Manager Grade]=“Senior” AND Cost < 5 You should state that the primary key field of one table should be equal to the foreign key field of the other table. The ON keyword should be used immediately after the INNER JOIN.
74
Questions – Multiple Tables
To answer question 1 use the following database design: Create query designs to solve the following problems: Which Managers sell products costing more that £100? What extension number would you use to phone them? What products, and their costs, are sold by senior grade Managers? Sort the results by department then cost. Departments Products Department Name Extension No Manager Manager Grade Floor Number of Staff Next Staff Training Day Sales Target Achieved Product ID Product Name Cost No in Stock Department *
75
Write the FROM clause used by queries for the following databases: Remember this should be like:
FROM … INNER JOIN … ON … = … … Movie Name * Actor Year Movie Name Name Movies Characters Poster Picture Genre Founded Team Name * Goals Capacity Name Clubs Players Team Name Stadium Caps Last Vacinated Address Phone No. Name Age Name Pets Owners Animal Pet Name*
76
Changing the Contents of a Database
Another operation that can be carried out on a database is to change the information stored within it. These changes can be carried out using SQL too. There are three ways to changes the contents of a database: Insert: Add a new record to the database. Update: Change the values stored inside an existing record. Delete: Remove a record from a database. When updating and deleting, search criteria are used to specify exactly which records are to be changed or removed.
77
Query Design - Insertion
Query Designs should be used for adding new records. The fields that will be included should be specified in the query design – remember that not every field requires a value. Autonumber fields should never be assigned a value when inserting a record. In addition, we should include an additional row in the query design to state what kind of change is being made to the database For example: Kirsty Black is a left footed defender who has scored four goals. She has just left her previous team and is looking for a new one. Add her to the database. Gives the following query design: Fields Name, Position, Goals Scored, Preferred Foot Tables Players Search Criteria Sort Ordering Modification Add new record – Kirsty Black
78
SQL Inserting The query design can be used to create SQL for the query: The fields for which values will be provided for should be listed. Not every field needs to have a value supplied. INSERT INTO indicates that we will be adding record. The table which will be added to should be stated. INSERT INTO Players(Name, Position, Goals Scored, Preferred Foot) VALUES (“Kirsty Black”, “Defender”,4, “Left”); VALUES indicates that the data stored inside the new record will be listed. It should appear in the same order as the fields are listed in the INSERT INTO clause
79
Query Design - Updating
Query Designs should be used for changing records. As well as the change to be made, a search criteria should be specified to limit which records are changed by the query. For example: Albion and Thistle merge to create a new team called Albion-Thistle. All their players move to the new team. Gives the following query design: Fields Team Tables Players Search Criteria Team = Albion or Team = Thistle Sort Ordering Modification Team = Albion-Thistle
80
SQL Updating The query design can be used to create SQL for the query: SET states the change made to the record. This should include the field that has to be changed UPDATE indicates that we will be changing records. The table which will be changed should be stated. UPDATE Players SET Team = “Albion-Thistle” WHERE Team=“Albion” OR Team=“Thistle” The WHERE clause is used to search for only some of the records in the database and change them. It is used exactly the same way as in search type queries The new value for the field should be described. This can be a literal value, as in this example, or a calculation
81
Query Design - Deleting
Query Designs should be used for removing records. When deleting records, you should always specify a search criteria. The records that match the criteria will be deleted from the database. For example: Fiona Philips has decided to stop playing because of a recurring knee injury. Remove her from the database. Gives the following query design: Fields * Tables Players Search Criteria Name = Fiona Philips Sort Ordering Modification Delete record
82
SQL Deleting DELETE * FROM Players WHERE Name = “Fiona Philips”
DELETE indicates that we will be removing a record. The * states that all the fields in the record will be deleted The query design can be used to create SQL for the query: DELETE * FROM Players WHERE Name = “Fiona Philips” The WHERE clause is used to search for only some of the records in the database and delete them. It is used exactly the same way as in search type queries FROM is used to indicate which table a record will be deleted from. It is used in the same way as in search queries
83
Questions – Changing Databases
To answer the questions, use the following database table Players: Player ID Name Position Goals Scored Preferred Foot Team 7 Louise Denver Keeper Left Academicals 14 Penny Haines Midfielder 2 Right Chargers 25 Joan Smith Defender 3 Albion 38 Fiona Philips 4 42 Laura Wilson 11 Thistle 29 Striker 19 62 Eliza McLeod 17 United
84
For each problem and query, identify the error in the SQL and correct it:
A Chargers fan notices that their striker Joan Smith has the wrong number of goals. She has actually scored two less? UPDATE Players SET [Goals Scored]= [Goals Scored]-2 WHERE Player= “Joan Smith”; Left footed midfielders should now have their position listed as “Left Winger”. UPDATE Players SET Position = “Left Winger” WHERE [Preferred Foot] =“Left” OR Position=“Midfielder”; United sack all of their keepers. Remove them from the database. DELETE * FROM Players WHERE Team=“United” AND Position=“Goalkeeper";
85
For each problem create a query design and SQL to solve it:
Remove Albion star defender Joan Smith from the database as she has retired. The Chargers drub United Every chargers player except the keeper scores. Update the database Heather Lawson joins Thistle. She is a right footed striker, but has yet to score any goals. Add her to the database. Academicals run out of money and go bust. A new team called New Academicals is quickly formed using the same players.
86
Database Testing & Evaluation
When creating a database, there are a number of tests that should be carried out. Any queries created in SQL should be tested to ensure that they produce the correct results and display all the required information. Field validation should be tested to ensure that it works correctly. This will not be in the exam, but is required to ensure you achieve as many marks as possible in the coursework task. Testing should always be iterative. If your testing uncovers an error in your database, you should return to the implementation stage and attempt to correct it. Test your new solution to see if it works correctly now.
87
Testing Queries When testing an SQL query you should first examine the contents of the database and work out what you expect the results to be. You should write a short paragraph detailing this. Run the query and compare the actual results to your expectations. If they are the same the query works. You should also take a screenshot of the results as evidence I checked the database and the womenswear, toys and games and lighting departments are training in It should display these departments and their training days. This screenshot shows that query works correctly and displays the required information. Therefore it is fit for purpose.
88
Testing Validation When testing field validation, you should consider:
What values should the database accept. What values should the database reject. When testing range check and length check validation, you should identify normal, extreme and exceptional data, just as you would when testing a program you have written. A good idea is to produce a test data table. This example shows testing for the range check rule Len(Password)>=8 Try each item of test data in the field and record if it accepts or rejects the data. Screenshot evidence will not be necessary at National 5 level. Test Data Type Test Data Expected Result Actual Result Normal Password1 Accept Extreme Password Exceptional Pass Reject
89
Evaluation An evaluation of a database should state whether or not the database you have created is ‘good’. You judge this in terms of the database’s fitness for purpose: Does it do what it is supposed to do? There a number of criteria you should think about when judging if a database is fit for purpose: Does it work contain all the information that was identified as being required at the analysis stage. Is the information stored accurately and without error? Does it include working validation to help prevent errors from occurring? Does it include SQL queries to implement all the required views and operations identified in the analysis stage?
90
Questions – Testing & Evaluation
Answer questions in full sentences! Describe fully how to test if an SQL query works correctly. What should you do if testing shows that part of a database is not working correctly? Identify suitable test data sets for the following validation rules > 0 Len(Name)>=5 AND Len (Name)<=10 Describe three criteria that can be used to measure if a database is fit for purpose.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.