bcs-092 b3
bcs-092 b3
Introduction to
Indira Gandhi Databases
National Open University
School of Computer and
Information Sciences
Block
3
STRUCTURED QUERY LANGUAGE AND
DATABASE DEVELOPMENT
UNIT 11
Introduction to SQL 7
UNIT 12
SQL - Data Manipulation Language 28
UNIT 13
SQL - Join Statements 49
UNIT 14
Database Development Process 57
Structured Query Language
and Database Develoment
In all the Units of this Block, Check Your Progress and Answers to
Check Your Progress Questions are written and added in 2021 BY
Mr. Akshay Kumar, Associate Professor
SOCIS, IGNOU, New Delhi-110068
PRODUCTION
Mr. Tilak Raj Mr. Yashpal
Asst. Registrar (Pub.) Section Officer (Pub.)
MPDD, IGNOU, New Delhi MPDD, IGNOU, New Delhi
January, 2021
Laser Typesetting : Akashdeep Printers, 20-Ansari Road, Daryaganj, New Delhi-110002
2
IGNOU is one of the participants for the development of courses of this
Programme
Copyright
This course has been developed as part of the collaborative advanced ICT course
development project of the Commonwealth of Learning (COL). COL is an
intergovernmental organization created by Commonwealth Heads of Government
to promote the development and sharing of open learning and distance education
knowledge, resources and technologies.
The Open University of Tanzania (OUT) is a fully fledged, autonomous and
accredited public University. It offers its certificate, diploma, degree and
postgraduate courses through the open and distance learning system which
includes various means of communication such as face-to-face, broadcasting,
telecasting, correspondence, seminars, e-learning as well as a blended mode. The
OUT’s academic programmes are quality-assured and as centrally regulated by
the Tanzania Commission for Universities (TCU).
ACKNOWLEDGEMENTS By AUTHORS
The Open University of Tanzania (OUT), Faculty of Science, Technology and
Environmental Studies, (FSTES) and the ICT Department wish to thank those
below for their contribution to the production of this course material and video
lectures:
Authors:
Ms. Grace W. Mbwete (Assistant Lecturer, ICT Department, OUT)
Mr. Elia A. Lukwaro (Tutorial Assistant, ICT Department, OUT)
Copy Editor:
Mr. Justin Kimaro (Principal Editor, IEMT, OUT)
Reviewers:
Ms. Lilian C. Mutalemwa (Assistant Lecturer, ICT Department, OUT)
Ms. Regina Monyemangene (Instructional Designer, IEMT, OUT)
Video Production:
Mr. Othman Mwinchoum (Multimedia studio, IEMT, OUT)
Ms. Grace W. Mbwete (Assistant Lecturer, ICT Department, OUT)
Ms. Lilian C. Mutalemwa (Assistant Lecturer, ICT Department, OUT)
This course has been developed with the support of the Commonwealth of
Learning, Canada.
3
BLOCK INTRODUCTION
You have already learnt about the basic concepts of database system in Block 1,
including the database model. Block2 focused on database design and concepts like
Entity-relationship model, and normalization. This block addresses one important
concept of creating the database using SQL and inserting and manipulating data in the
database system. Structured Query Language (SQL) is one of the standard languages
across DBMSs for creating database, manipulating data in a database and retrieval if
data from the database systems. This Block also discusses the data development
process.
Unit 11 introduces the data definition language of SQL. It also explains the SQL
commands for creating database constraints.
Unit 12 explains the commands for data manipulation and data retrieval.
Unit 13 discusses the join operation on two tables. Join is an important operation for
a normalized database.
Unit14 introduces the overall process of database development.
You must perform all the activities listed in this Block to appreciate the process of
database creation, manipulation and information retrieval.
Structured Query Language
and Database Develoment
6
Introduction to SQL
UNIT 11 INTRODUCTION TO SQL
Structure
11.1 Introduction
11.2 Objectives
11.3 Terminologies
11.4 Introduction to SQL
11.5 Data Definition Language (DDL) Commands
11.5.1 Create Database Command
11. 5.2 Create Table Command
11.5.3 Drop Table
11.6 Table Constraints
11.6.1 IDENTITY constraint
11.6.2 UNIQUE constraint
11.6.3 FOREIGN KEY Constraint
11.6.4 CHECK constraint
11.6.5 DEFAULT constraint
11.7 User Defined Types
11.8 Video Lecture
11.9 Activity
11.10 Summary
11.11 Answers
11.12 Review Questions FromAuthors
11.13 References and Further Reading
11.14 Attribution
11.1 INTRODUCTION
Structured Query Language (SQL) is the main data definition language used for the
creation and maintenance of databases. In this unit, we will learn the basic SQL syntax,
including some data definition commands, how to define different types of constraints
and different user defined data types in the application environment of databases.
11.2 OBJECTIVES
Upon completion of this unit you will be able to:
Describe different SQL - DDL commands.
Identify where and when to use the appropriate SQL DDL commands.
Create database by using SQL DDL commands.
Create set of database tables using DDL commands.
Describe the various types of integrity constraints and how theyare used. 7
Structured Query Language
and Database Develoment 11.3 TERMINOLOGIES
SQL : Database language designed for managing data held in a relational
database management system.
DDL : Data Definition Language; standard for commands that define the
different structures in a database
DML : Set of syntax elements used for selecting, inserting, deleting and
updating data in a database.
Constraints : Rules enforced on data columns on table
Ensuring that the database name should be unique within the RDBMS.
After creating the database 'university'; you can now check your created database in
the list of databases by typing the following SQL statement;
SHOW DATABASES;
The result of this SQL statement should list down the databases that have been created
with 'university' database which has just been crated; as follows:-
Database
Shop
Customer
university
10 11. Float - Floatingprecision number data from-1.79E + 308 through 1.79E + 308
12. Real - Floating precision number data from -3.40E + 38 through 3.40E + 38 Introduction to SQL
13. Datetime - Date and time data from January 1, 1753, to December 31,
9999, with an accuracy of one-three-hundredths of a second, or 3.33
milliseconds
14. Smalldatetime - Date and time data from January 1, 1900, through June 6,
2079, with an accuracy of one minute
We can also use alter table use the ALTER TABLE statement to modify a column in a
table by using the following SQL statement;
MODIFY column_namecolumn_type
Look at the following example below where we will modifythe column ProgramName
by changing its data type.
You can confirm these changes by using SQLstatement DESC table_name to verify
the data structure changes.
DESC AcademicProgram;
14 );
11.6.2 UNIQUE constraint Introduction to SQL
The UNIQUE constraint prevents duplicate values from being entered into a column.
Both PK and UNIQUE constraints are used to enforce entity integrity.
Multiple UNIQUE constraints can be defined for a table.
When a UNIQUE constraint is added to an existing table, the existing data is
always validated.
A UNIQUE constraint can be placed on columns that accept nulls. Only one
row can be NULL.
A UNIQUE constraint automatically creates a unique index on the selected
column.
This is the general syntax for the UNIQUE constraint:
[CONSTRAINT constraint_name]
UNIQUE [CLUSTERED | NONCLUSTERED]
(col_name [, col_name2 […, col_name16]])
[ON segment_name]
This is an examle using the UNIQUE constraint.
CREATE TABLE Students
(
StudentRegNo CHAR(10) NOT NULL UNIQUE,
)
USE HOTEL
GO
CREATE TABLE tblRoom
(
HotelNo Int NOT NULL,
RoomNo Int NOT NULL,
Type Char(50) NULL,
Price Money NULL,
16 PRIMARY KEY (HotelNo, RoomNo),
FOREIGN KEY (HotelNo) REFERENCES tblHotel Introduction to SQL
CONSTRAINT Valid_Type
CHECK (Type IN ('Single', 'Double', 'Suite', 'Executive'))
)
In this second example, the employee hire date should be before January 1, 2004, or
have a salary limit of $300,000.
GO
CREATE TABLE SALESREPS
(
Empl_num Int Not Null
CHECK (Empl_num BETWEEN 101 and 199),
Name Char (15),
Age Int CHECK (Age >= 21),
Quota Money CHECK (Quota >= 0.0),
HireDate DateTime,
CONSTRAINT QuotaCap CHECK ((HireDate< "01-01-2004")
OR (Quota <=300000))
);
(
EmployeeID INT Primary Key,
EmployeeSIN SIN,
CONSTRAINT CheckSIN
);
Check Your Progress 2
Q1: You want to assign successive odd numbers to a field named security no
(starting form 1).
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
Q2: Create the following table with UNIQUE, PRIMARY KEY and FOREIGN KEY
constraints:
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
18
Q3: How will you check that Marital Status field is contains the value 'SINGLE' or Introduction to SQL
19
Structured Query Language ll. ACTIVITY
and Database Develoment 9
Activity 11.1
What to do:
, .-----------'t
V ISIT
b1 ed id (PK) MODEL ------------------------------ i
vis it id (PK) 1----
plan_id (FKl ) drummer_ id:NUli ( UK l, fK l) model id (Pt.'.)
drummer_id (FK2) -1 >o<:i--+-1mode l_id (1FK2 ) l>i!_::i--;..imode Lname (UKl)
bed_id (FK3) lette r_coide (UK2) manufacturer
¥isit_date surcharge cost_per_use
Activity 11.2
What to do:
Populate the table (MODEL) with data as detailed below. Please pay
attention to the order in which your tables are populated: primary key
columns must be populated before dependent foreign key columns.
20
Introduction to SQL
MODEL table
model_id model_name manufacturer cost_per_use
1 Super Crisp CrispTanCorp 10
2 Super Crisp CrispTanCorp 12
Deluxe
3 Roentgen CrispTanCorp 14.5
Radiator
Duration: Expect to spend about 1 hour on this activity
Feedback: This activity should be submitted to the course Instructor for
assessment and feedback.
Activity 11.3
Introduction to SQL Exercises
Aim: To become conversant with basic SQLoperations.
Resources: Unit 11 Learning materials and MySQL DBMS or its
equivalent.
What to do:
Populate the table (DRUMMER) with data as detailed below. Please pay
attention to the order in which your tables are populated: primary key
columns must be populated before dependent foreign keycolumns.
DRUMMER table
drummer_id drummer_name band
1 Keith Moon Who, The
2 John Bonham Led Zepplin
3 Charlie Watts Rolling Stones, The
Duration: Expect to spend about 2 hours on this activity.
Feedback: This activity should be submitted to the course Instructor for
assessment and feedback.
21
Structured Query Language
and Database Develoment What to do:
Populate the table (PLAN) with data as detailed below. Please payattention
to the order in which your tables are populated: primarykey columns must
be populated before dependent foreign key columns.
PLAN Table
plan_id plan_name rate
1 Walk-In 25
2 Lobster 15
3 Bronze 10
Duration: Expect to spend about 30 minutes on this activity
Feedback: This activity should be submitted to the course Instructor for
assessment and feedback.
22
Introduction to SQL
Resources: Unit 11 Learning materials and MySQLDBMS or its
equivalent.
What to do:
Populate the table (BED) with data as detailed below. Please pay attention
to the order in which your tables are populated: primarykey columns must
be populated before dependent foreign key columns.
BED table
bed_id drummer_id model_id letter_code surchage
1 NULL 1 A 0
2 3 2 B 1.25
3 NULL 1 C 0
Duration: Expect to spend about 2 hours on this activity.
Feedback: This activity should be submitted to the course Instructor for a
feedback.
23
Structured Query Language
and Database Develoment 11.10 SUMMARY
In this unit you learned about SQL which is divided into two main categories; DDL
and DML. These categories show how to create a database and tables in that
particular database. For this unit, the emphasis was on data definition language by
using SQL where we had a chance of creating database and tables; within their
respective data types and required constraints. In summary, this unit has covered
how to define structure of a database and its associated tables and how to manipulate
the data within.
11.11 ANSWERS
Check Your Progress 1
Ans 1: SQL is a standard language across DBMS, and is used for defining data,
manipulating data and retrieving data as per the need of the user.
USE Bank
);
Name CHAR(50)
Ans 2: You may use the following command provided. You have executed SQL
command to use the appropriate databases and created the PROGRAMME
table with a field name Programme-code which has same data type as of
STUDENT table.
24
CREATE TABLE STUDENT Introduction to SQL
Programme-code CHAR(10),
Ans 3:
...
maritalstatus CHAR(10),
Salary Int,
CONSTRAINT Valid-maritial-status
CHECK(maritalstatus IN ('SINGLE','MARRIED'))
Task 1
Create the database named 'Organization' then a table 'Employee' with the following
attributes and its corresponding data declaration:-
EMP_NUM CHAR(3)
EMP_LNAME VARCHAR(15)
EMP_FNAME VARCHAR(15)
EMP_INITIAL CHAR(1)
EMP_HIREDATE DATE
JOB_CODE CHAR(3)
25
Structured Query Language Task 2
and Database Develoment
Populate the table created in task 1 with the following data.
Task 3
Write the SQL code to change the job code to 501 for the person whose personnel
number is 107. After you have completed the task, examine the results, and then reset
the job code to its original value.
Task 4
Assuming that the data shown in the Employee table have been entered, write the SQL
code that lists all attributes for a job code of 502.
Task 5
Write the SQLcode to delete the row for the person named William Smithfield, who
was hired on June 22, 2004, and whose job code classification is 500. (Hint: Use
logical operators to include all the information given in this problem.)
Task 6
Add the attributes EMP_PCT and PROJ_NUM to the Employee table. The
EMP_PCT is the bonus percentage to be paid to each employee.
Task 7
Using a single command, write the SQL code that will enter the project number
(PROJ_NUM) = 18 for all employees whose job classification (JOB_CODE) is 500.
Task 7
Using a single command, write the SQL code that will enter the project number
(PROJ_NUM) = 25 for all employees whose job classification (JOB_CODE) is 502
or higher.
Task 8
Write the SQLcode that will change the PROJ_NUM to 14 for those employees who
were hired before January 1, 1994, and whose job code is at least 501. (You may
assume that the table will be restored to its original condition preceding this question.)
2. Intro to SQL: Querying and managing data. Retrieved September 12, 2016, from
KhanAcademy, https://www.khanacademy.org/computing/computer-
programming/sql?ref=resume_learning#sql-basics
3. Rogers, D. (2002). COMP210: Class notes. Retrieved May 15, 2016, from
Yukon College, http://college.yukondude.com/2006_09_comp210/html/notes.php
11.14 ATTRIBUTION
The content of this unit of the Learning Material - Introduction to Databases (including
its images, unless otherwise noted) is a derivative copy of materials from the book
Database Design by Adrienne Watt and Nelson Eng licensed under Creative
Commons Attribution 4.0 International License.
3. Unit Summary
27
Structured Query Language
and Database Develoment UNIT 12 SQL DATA MANIPULATION
LANGUAGE
Structure
12.1 Introduction
12.2 Objectives
12.3 Terminologies
12.4 Data manipulation Language (DML)
12.5 INSERT Statement
12.6 SELECT Statement
12.7 Where Clause
12.8 Special Operators
12.9 AND /OR Operators
SQLAggregate Functions
Order By Clause
Group By Clause
Video lecture:
Activity
Unit summary
Answers
Review Questions FromAuthors
References and Further Reading
Attribution
12.1 INTRODUCTION
In unit 11, you were introduced to Data Definition Language (DDL) which is a
prerequisite for this unit. In this unit, you have an opportunity to learn about Data
Manipulation Language (DML) whereby you will learn how to manipulate (query) a
database by using different SQL. Please note that this unit is a practical based unit,
where as you go along the content, you need to be hands on with a DBMS of your
choice.
12.2 OBJECTIVES
Upon completion of this unit you should be able to:
Construct basic queries using Distinct Clause.
Construct basic queries using Where Clause.
Construct basic queries using AND/OR operator.
Construct basic queries using Aggregate Functions.
28
Construct basic queries using Order By Clause. SQL - Data Manipulation
Language
Construct basic queries using Special Operator.
12.3 TERMINOLOGIES
Distinct Clause : SQL operator which is used to return only distinct
(different) values.
Where Clause : SQL operator which is used to filter records.
And/Or Operator : SQL operator which is used to filter records on one
or more conditions.
SQLAggregate Function : SQL functions which perform a calculation on a set
of values and return a single, or summary, value.
SQL Special Operator : SQL operators which filter records on special
conditions.
CourseTitle VARCHAR(255),
);
(ii) Confirming the structure of the table
DESC courses;
+-----------------+--------------+------+----- +--------+------ +
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+----- +--------+------ +
+-----------------+--------------+------+----- +--------+------ +
4 rows in set (0.06 sec)
Now, you have learned how to insert/populate data into our tables. Please note, you
have to be careful, with SQL syntax while creating and pulating the database. One,
spelling mistake, then the statement willnot go through.
30
SQL - Data Manipulation
12.6 SELECT STATEMENT Language
The SELECT statement, or command, allows the user to extract data from tables in a
selected database. Please, note the syntax of the SELECT statement below:
In a circumstance that you only want to select few selected columns fromthat
particular table, the following syntax applies.
SELECT column_name,column_name
FROM table_name;
In a circumstance that you only want to select allcolumns from that particular
table, the following syntax applies.
SELECT *
FROM table_name;
Example 1:
Referring to the table 'courses' that you had inserted data into; you are going to have
a look at what data the table holds after inserting the data in the previous section.
SELECT *
FROM courses;
The following should be the output;
Example 2:
If you want to select one or more columnfrom a particular table; the following syntax
holds;
SELECT column_name,column_name
FROM table_name;
Following, out table courses we had populated with data in the previous section;
SELECT CourseTitle
FROM courses;
31
Structured Query Language The following should be the result;
and Database Develoment
+------------------------------+
| CourseTitle |
+------------------------------+
| Software Design |
| OO Programming |
| Data Communication |
| Introduction to E-business |
| Database Design |
| Computer Security |
+------------------------------+
The following sections, you are going to learn more conditions that are used with the
SELECT statement in querying the database.
SELECT column_name,column_name
FROM table_name
Example 1
If we want to know Course Title courses which have 2 units, the syntax will be as
follows:
WHERE CourseUnits = 2;
+-----------------------------+
| coursetitle |
+-----------------------------+
32
| Introduction to E-business | SQL - Data Manipulation
Language
| Database Design |
+-----------------------------+
Example 2
If you want know how manycourses have 2 or more units, we would use the following
syntax:-
WHERE CourseUnits>= 2;
The following should be the output;
+-----------------------------+
| coursetitle |
+-----------------------------+
| OO Programming |
| Data Communication |
| Introduction to E-business |
| Database Design |
+-----------------------------+
Q1: What is the purpose of SELECT, UPDATE and DELETE commands in SQL?
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
Q2: Consider the courses table in university database (given in section 12.5)
How will you insert a record containing the following data into the courses table?
CourseCode BCS091
CourseTitle DBMS
CourseUnits 3
CourseCredits 30
33
Structured Query Language What will happen if you try to enter CourseCode and CourseTitle only?
and Database Develoment
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
Q3: Using the same table as above, list those CourseCode and CourseTitle for which
CourseCredits are less than or equal to 20.
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
34 AND CourseCredits=30;
The result should be as follows: SQL - Data Manipulation
Language
+----------------+--------------------- +------------------+-------------------+
| CourseCode | CourseTitle | CourseUnits | CourseCredits |
+----------------+--------------------- +------------------+-------------------+
| OIT214 | OO Programming | 3| 30 |
| OIT215 | Data Communication | 3 | 30 |
+----------------+--------------------- +------------------+-------------------+
2 rows in set (0.00 sec)
Example 2:OR Operator
We are going to select all courses which have 3 unit and 30 credits from our table
courses from previous section.
SELECT * FROM Courses
WHERE CourseUnits=2
OR CourseCredits=20;
The following should be the results;
+----------------+-------------------------- +---------------- +---------------+
| CourseCode | CourseTitle | CourseUnits | CourseCredits |
+----------------+-------------------------- +---------------- +---------------+
| OIT 219 | Software Design | 1 | 20 |
| OIT216 | Introduction to E-business | 2 | 10 |
| OIT217 | Database Design | 2 | 10 |
+----------------+-------------------------- +---------------- +---------------+
3 rows in set (0.00 sec)
For more querying of data, AND operator and OR operator can be combined.
40
SQL - Data Manipulation
12.14 ACTIVTIY Language
Activity 12.1
Aim: To acquire practical skills in using basic SQL operations.
What to do:
Create a database for the fictitious 'Singer Prop Rentals Company', which
rents WWII-vintage fighter aircraft to a select group of singing clients:
singers. The singers rent aircraft and fly between a numbers of European
capital cities and are charged by the company based upon the model of
aircraft and the length of the rental. The name of the database should be
'SingerProp'.
AIRCRAFT SINGER
aircraft id (PK) .s.i.n-g-e-r-(-P-K )-----------!
model (UK l) name (UK l)
seating t.+...o
.... ----L_,1,."31Jirthdate
fixed_charge_ec fa, vourite aircraft id : NULL
daily_rate_ec (FKl) - · -
discount_pct SINGER_RE NTAL
sin!le r (PK FK1l
Activity 12.2
Aim: To acquire practical skills in using basic SQL operations.
Resources: Unit 12 leaming materials and MySQL Database Software
or similar DBMS.
What to do:
Populate the following table which was created in a database 'Singer Prop
Rentals Company', in activity 12.1.
Structured Query Language
and Database Develoment 2 Corsair 1 275050 48280
3 Hurricane 1 199595 36050
4 Messers 1 120000 37595
chmitt
5 Mustang 1 223700 39425
6 Stuka 2 149595 41000
Duration: Expect to spend about 1hour on this activity.
Feedback: This activityshould be submitted to the course Instructor for
assessment and feedback.
42
SQL - Data Manipulation
SINGER Table Language
43
Structured Query Language
and Database Develoment 5 9
6 9
1 10
2 10
3 10
4 10
5 10
6 10
7 10
1 11
2 12
7 12
Duration: Expect to spend about 3 hour on this activity
Feedback: This activity should be submitted to the course Instructor for
assessment and feedback.
44
SQL - Data Manipulation
8 2006-08-12 2006-08-15 4 1 6 Language
9 2006-08-10 2006-08-11 1 4 6
10 2006-08-17 2006-08-19 1 6 3
11 2006-08-21 2006-08-21 2 3 5
12 2006-08-22 2006-09-02 6 3 2
12.15 SUMMARY
In this unit you learned about all the basic SQL data manipulationcommands. This was
mainlyhands-on based unit where we have learned how to use different SQL operators
like WHERE clause, Group By, order By, Aggregate functions and special operators.
All these functions are aimed at helping the database end user to filter their data as per
their specific requirements.
12.16 ANSWERS
Check Your Progress 1
Ans 1: SELECT - for retrieving formation from one or more SQL tables.
UPDATE - updating the data values stored in certain field or fields of a table
DELETE - to delete one or several records from a table.
Ans 2: USE university; INSERT INTO courses VALUES ("BCS091","DBMS",3,30);
Try to enter the data, most likelyyou will get an error message. Try to find out why?
Ans 3: SELECT CourseCode, CourseTitle
FROM courses
WHERE CourseCredits <=20;
Check Your Progress 2
Ans 1: SELECT *
FROM courses
WHERE CourseUnits < 2 AND CourseCredits > 10
Ans 2: SELECT sum (CourseUnits)
FROM Courses
WHERE CourseCredits > 10
Ans 3: SELECT Student-ID, AVG (Marks)
FROM Student
GROUP BY Student-ID 45
Structured Query Language
and Database Develoment 12.17 REVIEW QUESTIONS FROM AUTHORS
Aim: These questions are aimed at examining learners knowledge's of SQL basic
'select statements. Students have to get the exact answer which will prove that they
have done the activity section correctly.
Duration: Expect to spend 2hours on this activity.
By using 'SingerProp' database in the activity section please answer the following
questions;
1. What is the average aircraft fixed charge for all of the models of aircraft?
Answer: €2,042.40
2. What is the average aircraft fixed charge for all of the rentals?
Answer: €2,053.56
3. What price would each singer pay, including discounts, of a 3 day rental of the
Mustang? Sort the results in descending order by price. (Hint: you'll need to use
both the AIRCRAFT and SINGER table in your query, but you do not INNER
JOIN them together.)
Answer: 7 prices ranging from €3419.75 for Rafi down to €2906.79 for Justin
4. What is the average price a Singer would pay, including discounts, of a 5 day
rental of the Hurricane?
Answer: €3,548.84
5. What is the total landing fee incurred for any rentals of aircraft that have the letter
"c" (uppercase or lowercase) in the model name?
Answer: €15,422.90
6. Excluding Singer discounts, what is the total charge (fixed and daily rate) and
landing fee for each of the rentals? (Hint: calculate the number of days for each
rental by subtracting the departure date from the arrival date and then adding 1.)
Answer: 12 rows, totalcharge ranges from €1,905.95 to €7,578.50 and landing
fee ranges from €960.00 to €4,228.40
7. How many times has each model of aircraft been rented? Sort the results so that
the most-often-rented model appears first.
Answer: 6 rows, the Stuka has been rented 4 times
8. How many times has each airport been visited either as a departure or arrival city?
Sort the results so that the most-often-visited airport appears first. (Hint: use an
OR in the join condition between AIRPORT and RENTAL.)
Answer: 6 cities, Warsaw has been visited 5 times
9. What is the total amount charged per aircraft model (fixed charge and daily rate),
excluding singer discounts, for all of the rentals? Sort the results so that the model
producing the most income appears first. (Hint: starting with your query from
46 exercise #6 makes this a snap.)
Answer: 6 models, total charge ranges from €16,233.80 to €2,356.45 SQL - Data Manipulation
Language
10. What is the average profit or loss per aircraft model (total charge minus landing
fees), excluding singer discounts, for all of the rentals? Sort the results so that the
least profitable model appears first.
Answer: 6 models, average profit ranges from €-1,597.15 to €2,811.70
11. On what dates have airplanes departed from London?
Hint: (2 dates)
12. Which singers have favorite airplanes? And what is the model name and seating
capacity of those aircraft?
Hint: (4 singers)
13. Which singer have flown to Berlin (arrivals only)? And on which dates did they
arrive?
Hint: (2 singers )
14. Which models of aircraft (together with their seating capacities) have visited Paris
(arrivals or departures)?
Hint: (3 models, but one visited Paris twice)
15. Which singers have flown in an aircraft that is not their favorite model, other than
the Catalina (whether or not they have a favorite)? Display both the singer name
and model in your result set.
16. First try to answer the question without the "favorite model" restriction. That is,
start off by just finding the aircraft models in which each singer has flown.
12.19 ATTRIBUTION
The content of this unit ofthe Learning Material - Introduction to Databases (including
its images, unless otherwise noted) is a derivative copy of materials from the book
Database Design byAdrienne Watt and Nelson Eng licensed under Creative Commons
Attribution 4.0 International License. 47
Structured Query Language Download this book for free at http://open.bccampus.ca
and Database Develoment
The following material was written by Grace Mbwete:
1. Introduction
2. All SQL examples in the unit for manipulating data in the Databases.
3. Unit Summary
48
SQL - Data Manipulation
UNIT 13 SQL - JOIN STATEMENT Language
Structure
13.1 Introduction
13.2 Objectives
13.3 Terminologies
13.4 SQL Join Statements
13.5 Inner Joins
13.6 Outer Joins
Left Outer Join
Right Outer Joins
13.7 Video lecture
13.8 Activity
13.9 Summary
Answers
Case Study
References and Further Reading
Attribution
13.1 INTRODUCTION
Programmers frequently join data from a number of different tables in order to obtain
more information. In this unit, you will learn about SQL Joins, which allow us to
create complex queries, combine data from different tables, and obtain a new result
set that can provide you with a better understanding of the data and maximize database
flexibility.
13.2 OBJECTIVES
Upon completion of this unit you should be able to:
Explain the different methods for joining tables.
Construct advanced queries of two or more tables using join operations.
13.3 TERMINOLOGIES
Inner Join : SQL operator which connects two tables on a column with
the same data type.
Left Outer Join : SQL operator which specifies that all left outer rows be
returned.
Right Outer Join : SQL operator which includes all rows from the right table in
its result set.
49
Structured Query Language Group By : Aggregate functions in the SELECT clause <select> list
and Database Develoment
provide information about each group instead of individual
rows.
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
Check Your Progress 1
Q1: What is the need of Join Operation?
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
For Questions 2 & 3.
Consider the following tables
Student Subject
S-id Subject-code Subject-code Title Credits
S001 DBMS DBMS Database Management 3
System
S002 DBMS OS Operating System 3
50
SQL - Join Statements
S001 OS DS Data Structure 4
S003 DS
S003 OS
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
Q3: Write the INNER JOIN command as well as show the result of INNER JOIN.
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
SELECT column_name(s)
FROM table1
13.8 ACTIVITY
52
SQL - Join Statements
1. Show the list of all drummers, and the code of the tanning bed that
has been named for each, or "N/A" if a bed has not been named for
the drummer.
13.9 SUMMARY
In this unit you learned about inner and outer joinfunction which connects two tables in
which it allows creation of a new table with comparison of rows that have qualified..
13.10 ANSWERS
Check Your Progress 1
Ans 1: It combines the related rows of two or more tables. This operation is needed
as during normalization process, you decompose tables into several tables;
join recombines those tables to give you combined information. Please note
JOIN does not create a new table unless specifically asked, it is just an
information retrieval query.
Ans 2: At least ONE column/attribute should have the same domain. In the tables
given above Subject-code is the joining attribute.
Ans 3: SELECT S-id, Student.Subject-code, Title, Credits
FROM Student
INNER JOIN Subject 53
Structured Query Language ON Student.Subject-code = Subject.Subject-code
and Database Develoment
* You may notice the redundancyin the output.
Output
S-id Subject-code Title Credits
S001 DBMS Database Management 3
System
S002 DBMS Database Management 3
System
S001 OS Operating System 3
S002 OS Operating System 3
S003 DS Data Structure 4
S003 OS Operating System 3
FROM Student
FROM Student
13.13 ATTRIBUTION
The content of this unit of the Learning Material - Introduction to Databases (including
its images, unless otherwise noted) is a derivative copy of materials from the book
Database Design by Adrienne Watt and Nelson Eng licensed under Creative
Commons Attribution 4.0 International License.
Download this book for free at http://open.bccampus.ca
The following material was written by Grace Mbwete:
1. Introduction
2. Unit Summary
56
SQL - Join Statements
UNIT 14 DATABASE DEVELOPMENT
PROCESS
Structure
14.1 Introduction
14.2 Objectives
14.3 Terminologies
14.4 Overview
14.5 Software Development Life Cycle (SDLC)
14.6 Database Life Cycle
14.7 Video lecture
14.8 Activity
14.9 Summary
Answers
Review Questions byAuthors
References and Further Reading:
Attribution
14.1 INTRODUCTION
After learning all the basic theories and practical techniques of database design in all
previous thirteen units of this course; you will now have the required skills of designing
and implement a database given user requirements. This unit will cover the process of
software development life cycle, database development process which will assist you
in achieving design and implementation of database for a particular case.
14.2 OBJECTIVES
Upon completion of this unit you will be able to:
Understand the basic concepts of software development life cycle.
Analyze user requirements for database design and implementation process.
Convert user requirements into a logical design.
Realize the logical design and implement the database.
Test and maintain the implemented database.
14.3 TERMINOLOGIES
Analysis : Starts by considering the statement of requirements and
finishes by producing a system specification.
Data requirements : Used to confirm the understanding of requirements with
document the user. 57
Structured Query Language Design : Begins with a system specification, produces design
and Database Develoment
documents and provides a detailed description of how a
system should be constructed.
Establishing : Involves consultation with, and agreement among,
requirements stakeholders as to what they want froma system; expressed
as a statement of requirements.
Implementation : The construction ofa computer system according to a given
design document.
Maintenance : Involves dealing with changes in the requirements or the
implementation environment, bug fixing or porting of the
system to new environments.
Requirements : A process during which the database designer interviews
gathering the database user to understand the proposed system and
obtain and document the data and functional requirements.
Software Development : The series of steps involved in the database development
Life Cycle (SDLC) process.
14.4 OVERVIEW
A core aspect of software engineering is the subdivision of the development process
into a series of phases, or steps, eachof which focuses on one aspect of the development.
The collection of these steps is sometimes referred to as the software development life
cycle (SDLC). The software product moves through this life cycle (sometimes repeatedly
as it is refined or redeveloped) until it is finallyretired from use. Ideally, each phase in
the life cycle can be checked for correctness before moving on to the next phase.
Using these assumptions and Figure 14.2, we can see that this diagram represents a
model of the activities and their outputs for database development. It is applicable to
any class of DBMS, not just a relational approach. Database application development
is the process of obtaining real-world requirements, analyzing requirements, designing
the data andfunctions of the system, and then implementing the operations in the system.
14.6.2 Analysis
Data analysis begins with the statement of data requirements and then produces a
conceptual data model. The aim of analysis is to obtain a detailed description of the
data that will suit user requirements so that both high and low level properties of data
and their use are dealt with. These include properties such as the possible range of
values that can be permitted for attributes (e.g., in the school database example, the
student course code, course title and credit points).
The conceptual data model provides a shared, formal representation of what is being
communicated between clients and developers during database development - it is
focused on the data in a database, irrespective of the eventual use of that data in user
processes or implementation of the data in specific computer environments. Therefore,
a conceptual data model is concerned with the meaning and structure of data, but not
with the details affecting how they are implemented.
The conceptual data model then is a formal representation of what data a database
should contain and the constraints the data must satisfy. This should be expressed in
terms that are independent of how the model maybe implemented. As a result, analysis
focuses on the questions, "What is required?" not "How is it achieved?"
Figure 14.3: Asummary of the iterative steps involved in database design, by A. Watt.
First, for a given conceptual data model, it is not necessarythat all the user requirements
it represents be satisfied by a single database. There can be various reasons for the
development of more than one database, such as the need for independent operation
in different locations or departmentalcontrolover "their" data. However, if the collection
of databases contains duplicated data and users need to access data in more than one
database, then there are possible reasons that one database can satisfy multiple
requirements, or issues related to data replication and distribution need to be examined.
Second, one of the assumptions about database development is that we can separate
62 the development of a database from the development of user processes that make use
of it. This is based on the expectation that, once a database has been implemented, all Database Development
Process
data required by currently identified user processes have been defined and can be
accessed; but we also require flexibility to allow us to meet future requirements changes.
In developing a database for some applications, it may be possible to predict the
common requests that will be presented to the database and so we can optimize our
design for the most common requests.
Third, at a detailed level, manyaspects of database design and implementation depend
on the particular DBMS being used. If the choice of DBMS is fixed or made prior to
the design task, that choice can be used to determine design criteria rather than waiting
until implementation. That is, it is possible to incorporate design decisions for a specific
DBMS rather than produce a generic design and then tailor it to the DBMS during
implementation.
It is not uncommon to find that a single design cannot simultaneously satisfy all the
properties of a good database. So it is important that the designer has prioritized these
properties (usuallyusing information from the requirements specification); for example,
to decide if integrity is more important than efficiency and whether usability is more
important than flexibility in a given development.
At the end of our design stage, the logical schema will be specified by SQL data
definition language (DDL) statements, which describe the database that needs to be
implemented to meet the user requirements.
14.6.4 Implementation
Implementation involves the construction of a database according to the specification
of a logicalschema. This will include the specification ofan appropriate storage schema,
security enforcement, external schema and so on. Implementation is heavily influenced
by the choice of available DBMSs, database tools and operating environment. There
are additional tasks beyond simply creating a database schema and implementing the
constraints - data must be entered into the tables, issues relating to the users and user
processes need to be addressed, and the management activities associated with wider
aspects of corporate data management need to be supported. In keeping with the
DBMS approach, we want as many of these concerns as possible to be addressed
within the DBMS. We look at some of these concerns briefly now.
In practice, implementation of the logical schema in a given DBMS requires a very
detailed knowledge of the specific features and facilities that the DBMS has to offer. In
an ideal world, and in keeping with good software engineering practice, the first stage
ofimplementationwould involve matching the designrequirements with the best available
implementing tools and then using those tools for the implementation. In database terms,
this might involve choosing vendor products with DBMS and SQLvariants most suited
to the database we need to implement. However, we don't live in an ideal world and
more often than not, hardware choice and decisions regarding the DBMS will have
been made well in advance of consideration of the database design. Consequently,
implementation can involve additional flexing of the design to overcome any software
or hardware limitations. The following are the stages involved in the implementation of
database:
14.6.5 Testing
The aimof testing is to uncover errors in the design and implementation ofthe database,
its structure, constraints and associated user and management support. Testing is usually
considered to involve two main tasks - validation and verification. Without adequate
testing users willhave little confidence in their data processing.
Validation answers the question: has the right database been developed to meet the
requirements? It attempts to confirm that the right database has been constructed, with
the right characteristics to meet the specified requirements.
Verification answers the question: has the database designbeen implemented correctly?
Verification ensures that the processing steps, constraints and other 'programmed'
components of the database (security, backup, recovery, audit trails, etc.) have been
correctly implemented and contain no errors in program logic or execution sequences.
Of course, testing does not just take place only after all the above development steps
are complete. It is usually applied throughout the stages in the development processes
and includes appropriate reviews to scrutinise the outputs ofthe development activities.
The aim is to identify errors as soon as possible in the development life cycle.
14.6.6 Maintenance
Databases are one of the more enduring software engineering artefacts; it is not
uncommon to find database implementations whose use can be traced back for 15
years or more. Consequently, maintenance of the database is a key issue. Maintenance
can take three main forms: 65
Structured Query Language i) Operational maintenance, where the performance of the database is
and Database Develoment
monitored. If it falls below some acceptable standard, then reorganization of
the database, usually in the form of adjustments to the storage schema, takes
place to ensure that performance is maintained at an acceptable level.
ii) Porting and implementation maintenance, in which the DBMS, the user
processes, the underlying computer system or some other aspect undergoes
changes that require the database implementation to be revised. Of course,
the extreme formof porting occurs when the database is to be entirelyreplaced
- in which case the entire development life cycle is usuallyfollowed using the
existing database and its limitations as the starting point for requirements
analysis. Adjustments to the storage schema are almost inevitable as new
data storage capabilities become available. This caninvolve both restructuring
and reorganization, depending on the scope of the changes taking place.
iii) Requirements change, where the original requirement specification changes,
usually because databases are frequently used for purposes for which they
were not originallydesigned. This involves restructuring and typically involves
a 'mini life cycle' related to the development of changes to meet the new
requirements.
If we follow the three-schema architecture approach we would hope to minimize the
impact of change and build systems which are easily maintained.
Check Your Progress 3
Q1: Whyis testing done?
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
................................................................................................................................
Q2: What are different types of maintenance?
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
...............................................................................................................................
66
Database Development
14.8 ACTIVITY Process
14.9 SUMMARY
In this unit you learned about Database Development Process. In summary, relational
database systems underpin the majority of the managed data storage in computer
systems. In this unit we have considered database development as an instance of
the waterfall model of the software development life cycle. We have seen that the
same activities are required to develop and maintain databases that meet user
requirements.
14.10 ANSWERS
Check Your Progress 1
Ans 1: SDLC is the process of development of software. The software develpment
goes through these cycles till it is replaced.
Ans 2: No, design requires extensive detailing of what is to be developed, that can be
done only if proper analysis has been done.
Ans 3: Database life cycle is the process of analysis, design and development of a
database for a system.
Check Your Progress 2
Ans 1: It provides a specification for logicalschema, which can be directlytransformed
to tables. 67
Structured Query Language Ans 2: It is a creative process and detailing and discussion at each step makes design
and Database Develoment
robust.
Ans 3: Realizing the design, populating the database, supporting users & user processes.
Check Your Progress 3
Ans 1: Testing uncover errors.
Ans 2: Operational maintenance; Porting; Requirement changes.
3. What is SDLC model? Mention three types of the most common used SDLC
models.
4. What is a waterfall model? Outline the steps in waterfall model.
5. What are the advantages of using waterfall model?
6. Explain when to use waterfall model.
7. What are the disadvantages of using waterfall model?
8. Explain in details the steps involved in Database Life Cycle.
9. Describe the tasks involved during implementation stage ofdatabase life cycle.
10. Outline the activities which take place during testing and evaluation of a
database.
14.13 ATTRIBUTION
The content of this unit (Database Development Process) of the Learning Material -
68 Introduction to Databases (including its images, unless otherwise noted) is from Chapter
13 of the book Database Design by Adrienne Watt and Nelson Eng licensed under Database Development
Process
Creative Commons Attribution 4.0 License.
Download this book for free at http://open.bccampus.ca
The following materialof this unit was written by Grace Mbwete:
1. Introduction
2. Activity 14.0
3. Unit Summary
Video 20 - Review Questions and Activities
https://tinyurl.com/j59x9rz
69