Database Systems Lab Manual - Updated Sep 2023
Database Systems Lab Manual - Updated Sep 2023
Database Systems Lab Manual - Updated Sep 2023
Database System
(CS – 220)
Fall Semester 2023
Version 2.4
PREFACE
This lab manual has been prepared to facilitate the students of software engineering in studying and analysing
various components of a database system. The lab focuses on creating and manipulating databases. The
programming language for database system Structured Query Language (SQL) is taught. The manual also
addresses advanced concepts including transaction, indexing, concurrency and optimization.
PREPARED BY
Lab manual is prepared by Lec Ayesha Naseer under the supervision of Head of Department Dr. Naveed Iqbal
Rao in year 2013. This course will provide a thorough introduction to the theory and practices of database
systems. The emphasis will be on the theoretical considerations involved in modeling data and in designing
efficient database systems.
GENERAL INSTRUCTIONS
a. Students are required to maintain the lab manual with them till the end of the semester.
b. All readings, answers to questions and illustrations must be solved on the place provided. If more space is
required, then additional sheets may be attached.
c. It is the responsibility of the student to have the manual graded before deadlines as given by the instructor
d. Loss of manual will result in re submission of the complete manual.
e. Students are required to go through the experiment before coming to the lab session. Lab session details will
be given in training schedule.
f. Students must bring the manual in each lab.
g. Keep the manual neat clean and presentable.
h. Plagiarism is strictly forbidden. No credit will be given if a lab session is plagiarised and no re submission
will be entertained.
i. Marks will be deducted for late submission.
VERSION HISTORY
Date Update By Details
July 2013 Lec Ayesha Naseer First Version Created
Sep 2014 Lec Ayesha Naseer Second version created. Labs improved
Sep 2015 Kabeer Ahmed Labs improved &Updated exercises
Sep 2016 Kabeer Ahmed Labs improved &Updated exercises
Sep 2017 Kabeer Ahmed Labs improved &Updated exercises included the Views
Sep 2018 Lec Ayesha Naseer and Kabeer Ahmed Updated exercises included CLOs and lab rubrics
Sep 2019 Lec Ayesha Naseer and Kabeer Ahmed Updation exercises and CLOs
Sep 2020 Lec Ayesha Naseer and Kabeer Ahmed Updation of CLOs, Labs and exercises
Sep 2021 Lec Ayesha Naseer and Kabeer Ahmed Update Lab Rubrics
Sep 2022 Lec Ayesha Naseer and Kabeer Ahmed Updated CLOs and Exercises
Sep 2023 Dr Ayesha Naseer Revised CLO mappings with experiments
Department of Computer Software Engineering
Lab Rubrics
Query Formulation
1. Student Management:
Maintain student profiles with details such as name, contact information, date of birth, and
address.
Assign a unique student ID to each student.
Store historical data of student enrolments and academic performance.
2. Course Management:
Manage course details including course code, title, description, credits, and prerequisites.
Store information about faculty members assigned to each course.
3. Enrolment:
Allow students to browse available courses and enrol in them.
Ensure that students meet prerequisites before enrolling in advanced courses.
Limit the number of students per course if necessary.
Handle waitlists for courses that have reached maximum enrolment.
4. Academic Records:
Record grades for each student in their enrolled courses.
Calculate GPA and maintain a transcript for each student.
Generate reports for students, faculty, and administration.
5. Faculty Management:
Maintain faculty profiles including name, contact information, and areas of expertise.
Assign faculty members to specific courses.
Entities:
1. Student
2. Course
3. Faculty
4. Enrollment
5. Academic Record
Relationships:
1. Student-Course (Many-to-Many):
• A student can enroll in multiple courses, and a course can have multiple students enrolled.
• This relationship will have attributes like enrollment date. Each enrollment is associated with one
course, but a course can have multiple enrollments (students).
2. Student-Academic Record (One-to-Many):
• Each student has one academic record, but an academic record contains multiple course grades.
Design the Entity Relationship Diagrams (ERDs) by leveraging Crow's Foot notations within the user-friendly
interface of ER Assistant.
THEORY
The entity relationship diagram (ERD) is a graphical representation that depicts things of interest (entities) and
relationship among entities. ERD’s have three basic elements: entity types, relationships and attributes.
Components of ER Diagram
Attribute: Attribute are the properties that define the entity type. For example, Roll No, Name, DOB, Age,
Address, and Mobile No are the attributes that define entity type Student. In ER diagram, the attribute is
represented by an oval.
Relationship Cardinality: The number of times an entity of an entity set participates in a relationship set is
known as cardinality. Cardinality can be of different types:
cardinalities constrain the number of entities that participate in a relationship.
1. One-to-One (1:1): This cardinality indicates that each entity instance in one entity is related to exactly one
entity instance in another entity, and vice versa. It is often denoted as 1:1.
2. One-to-Many (1:N): This cardinality signifies that each entity instance in one entity can be associated with
multiple entity instances in another entity, while each instance in the other entity is related to at most one
instance in the first entity. It is represented as 1:N.
3. Many-to-One (N:1): This cardinality implies that multiple instances in one entity can be related to a single
instance in another entity. It is often depicted as N:1.
4. Many-to-Many (N:N): This cardinality represents a complex relationship where multiple instances in one
entity can be associated with multiple instances in another entity. To implement a many-to-many relationship in
a database, an intermediary table is typically used. It is denoted as N:N.
Optional Relationship: An optional relationship indicates that an entity instance may or may not participate in
a relationship. It implies that the existence of an entity instance is not dependent on its participation in the
relationship. In an ERD, it is represented by a dashed line connecting the entities.
Classification of Cardinalities:
Weak entities and Identifying relationships: Entity types that borrow part or their entire primary key are
known as weak entities. The relationship that provides components of the primary key is known as an
identifying relationship.
1. Draw an ERD containing Student and Paper entity types connected by a 1-M relationship. The Student
entity type should have attributes for StdNo (primary key), StdFirstName, StdLastName, StdAdmitSemester,
StdAdmitYear, and StdEnrollStatus (full or part-time). The Paper entity type should have attributes for
PaperNo (primary key), PaperTitle, PaperSubmitDate, PaperAccepted (yes or no), and PaperType (first,
second, proposal, or dissertation). Add a 1-M relationship from Student to Paper.
2. Extend the ERD with an Evaluator entity type and an M-N relationship between Paper and Evaluator. The
Evaluator entity type should have attributes for EvalNo (primary key), EvalFirstName, EvalLastName,
EvalEmail, and EvalOffice. The M-N relationship should have attributes for EvalDate, EvalLitReview (1 to
5 rating), EvalProbId (1 to 5 rating), EvalTechWriting (1 to 5 rating), EvalModelDev (1 to 5 rating),
EvalOverall (1 to 5 rating), and EvalComments.
3. Transform the M-N relationship from problem 9 into an associative entity type and identifying relationships.
Part 2
Part 3
Problem [15]
1. Draw an ERD containing the LabVisit and Patient entity types connected bya 1-M relationship from Patient
to LabVisit. Choose an appropriate relationship name using your common knowledge of interactions
between patients and lab visits. Define minimum cardinalities so that a patient is required for a lab visit. For
the Patiententity type, add attributes PatNo (primary key), PatLastName, PatFirstName, PatDOB (date of
birth). For the LabVisit entity type, add attributes for the LVNo (primary key), LVDate, LVProvNo, and
optional LVOrdNo (for orders from physicians). If you are using a data modeling tool that supports data
type specification, choose appropriate data types for the attributes based on your common knowledge.
2. Extend problem 1 with the Lab entity type connected by a 1-M relationship from Lab to LabVisit. Choose
an appropriate relationship name using your common knowledge of interactions between labs and lab visits.
Define minimum cardinalities so that a lab is required for a lab visit. For the Labentity type, add attributes
LabNo (primary key), LabName, LabStreet, LabCity, LabState, and LabZip. If you are using a data
modeling tool that supports data type specification, choose appropriate data types for the attributes based on
your common knowledge.
3. Augment your ERD from problem 2 with the Specimen entity type. For each specimen collected, the
database should record a unique SpecNo, SpecArea (vaginal, cervical, or endocervical), and
SpecCollMethod (thin prep or sure path). You should also add a 1-M relationship from LabVisit to
Specimen. A lab visit must produce at least one specimen. A specimen is associated with exactly one lab
visit.
OBJECTIVE
Create Entity Relationship Diagrams (ERDs) that align seamlessly with the context of narrative scenarios.
THEORY
Data modeling involves the collection and analysis of business requirements resulting in an ERD to represent
the requirements. Business requirements are rarely well structured. Rather, as an analyst you will often face an
ill-defined business situation in which you need to add structure. You will need to interact with a variety of
stakeholders who sometimes provide competing statements about the database requirements.
In collecting the requirements, you will conduct interviews, review documents and system documentation, and
examine existing data. The main goal when analyzing narrative problem statements is to create an ERD that is
consistent with the narrative.
The ERD should not contradict the implied ERD elements in the problem narrative.
Identifying Entity Types
In a narrative, you should look for nouns involving people, things, places, and events as potential entity types.
The nouns may appear as subjects or objects in sentences. For example, the sentence, "Students take courses
at the university" indicates that student and course may be entity types.
1. Strong Entity
A Strong Entity is a type of entity that has a key Attribute. Strong Entity does not depend on other Entity in the
Schema. It has a primary key, that helps in identifying it uniquely, and it is represented by a rectangle. These are
called Strong Entity Types.
2. Weak Entity
An Entity type has a key attribute that uniquely identifies each entity in the entity set. But some entity type
exists for which key attributes can’t be defined. These are called Weak Entity types.
Determining Attributes
The properties often indicate attributes of entity types. For example, the sentence, "Students choose their
major and minor in their first year" indicates the major and minor may be attributes of student. The sentence,
"Courses have a course number, semester, year, and room listed in the catalogue" indicates that course number,
semester, year, and room are attributes of course.
2. Composite Attribute
An attribute composed of many other attributes is called a composite attribute. For example, the Address
attribute of the student Entity type consists of Street, City, State, and Country. In ER diagram, the composite
attribute is represented by an oval comprising of ovals.
3. Multivalued Attribute
An attribute consisting of more than one value for a given entity. For example, Phone_No (can be more than
one for a given student). In ER diagram, a multivalued attribute is represented by a double oval.
4. Derived Attribute
An attribute that can be derived from other attributes of the entity type is known as a derived attribute. e.g.; Age
(can be derived from DOB). In ER diagram, the derived attribute is represented by a dashed oval.
Identification of primary keys is an important part of entity type identification. Ideally, primary keys should be
stable and single purpose. "Stable" means that a primary key should never change after it has been assigned to
an entity. "Single purpose" means that a primary key attribute should have no purpose other than entity
identification. Typically, good choices for primary keys are integer values automatically generated by a DBMS.
Adding Relationships
Relationships often appear as verbs connecting nouns previously identified as entity types. For example, the
sentence, "Students enroll in courses each semester" indicates a relationship between students and courses.
For relationship cardinality, you should look at the number (singular or plural) of nouns along with other words
that indicate cardinality. For example, the sentence, "A course offering is taught by an instructor" indicates
that there is one instructor per course offering. You should also look for words such as "collection" and "set"
that indicate a maximum cardinality of more than one.
For example, the sentence, "An order contains a collection of items" indicates that an order is related to
multiple items.
Minimum cardinality can be indicated by words such as "optional" and "required." In the absence of indication
of minimum cardinality, the default should be mandatory.
Practice Problem
The water utility database should support the recording of water usage and billing for water usage. To support
these functions, the database should contain data about customers, rates, water usage, and bills. Other functions
such as payment processing and customer service are omitted from this description for brevity. The following
list describes the data requirements in more detail.
Customer data include a unique customer number, a name, a billing address, a type (commercial or residential), an
applicable rate, and a collection (one or more) of meters.
Meter data include a unique meter number, an address, a size, and a model. The meter number is engraved on the
meter before it is placed in service. A meter is associated with one customer at a time.
An employee periodically reads each meter on a scheduled date. When a meter is read, a meter-reading document
is created containing a unique meter reading number, an employee number, a meter number, a timestamp (includes
date and time), and a consumption level. When a meter is first placed in service, there are no associated readings for
it.
A rate includes a unique rate number, a description, a fixed dollar amount, a consumption threshold, and a variable
amount (dollars per cubic foot). Consumption up to the threshold is billed at the fixed amount. Consumption greater
than the threshold is billed at the variable amount. Customers are assigned rates using a number of factors such as
customer type, address, and adjustment factors. Many customers can be assigned the same rate. Rates are typically
proposed months before approved and associated with customers.
The water utility bills are based on customers' most recent meter readings and applicable rates. A bill consists of a
heading part and a list of detail lines. The heading part contains a unique bill number, a customer number, a
preparation date, a payment due date, and a date range for the consumption period. Each detail line contains a
meter number, a water consumption level, and an amount. The water consumption level is computed by subtracting
the consumption levels in the two most recent meter readings. The amount is computed by multiplying the
consumption level by the customer's rate.
Solution
For each kind of account, the software provides a separate data entry screen. The following list describes the
fields on the data entry screens for each kind of account:
• For all accounts, the software requires the unique account identifier, the account name, date established, and
the balance.
• For checking accounts, the software supports attributes for the bank name, the bank address, the checking
account number, and the routing number.
• For credit cards, the software supports attributes for the credit card number, the expiration date, and the
credit card limit.
• For stocks, the software supports attributes for the stock symbol, the stock type (common or preferred), the
last dividend amount, the last dividend date, the exchange, the last closing price, and the number of shares (a
whole number).
• For mutual funds, the software supports attributes for the mutual fund symbol, the share balance (a real
number), the fund type (stock, bond, or mixed), the last closing price, the region (domestic, international, or
global), and the tax-exempt status (yes or no).
OBJECTIVE
Exécute SQL DDL (Data Definition Language) statements to define and manage the structure of a database,
including creating, modifying, and deleting database objects such as tables, indexes, views, and schemas.
THEORY
Note:- The column_name parameters specify the names of the columns of the table and data_type parameter
specifies what type of data the column can hold (e.g. varchar, integer, decimal, date, etc.).
Example:
CREATE TABLE Customer
( CustNo CHAR(8),
CustFirstName VARCHAR(20) CONSTRAINT CustFirstNameRequired NOT NULL,
CustLastName VARCHAR(30) CONSTRAINT CustLastNameRequired NOT NULL,
CustStreet VARCHAR(50),
CustCity VARCHAR(30),
CustState CHAR(2),
CustZip CHAR(10),
CustBal DECIMAL(12,2) DEFAULT 0,
CONSTRAINT PKCustomer PRIMARY KEY (CustNo) )
ALTER TABLE
Alter command is used to:
Add a new column.
Modify the existing column definition.
To include or drop integrity constraint.
Example:
To add the Column in a table
ALTER TABLE Customer
ADD Martial_Status char(1);
DROP TABLE
Drop statement is used to delete a table including records inside the table.
Syntax: DROP TABLE <TABLE NAME>;
Example:
DROP TABLE Customer;
TRUNCATE TABLE
Truncate statement is used to delete data from a table. If there is no further use of records stored in a table and
the structure has to be retained then the records alone can be deleted.
Syntax: TRUNCATE TABLE <TABLE NAME>;
Example:
TRUNCATE TABLE Customer;
a) Domain Integrity
This constraint sets a range and any violations that take place will prevent the user from performing the
manipulation that caused the breach. It includes:
Not Null constraint:
While creating tables, by default the rows can have null value. The enforcement of not null constraint in a table
ensures that the table contains values.
Example:
CREATE TABLE Customer
(CustNo CHAR(8),
CustFirstName VARCHAR(20) CONSTRAINT CustFirstNameRequired NOT NULL,
CustLastName VARCHAR(30) CONSTRAINT CustLastNameRequired NOT NULL,
CustStreet VARCHAR(50),
CustCity VARCHAR(30),
CustState CHAR(2),
CustZip CHAR(10),
CustBal DECIMAL(12,2) DEFAULT 0,
CONSTRAINT PKCustomer PRIMARY KEY (CustNo))
You can add not null constraint, If you forget to add not null constraint on table while creating table.
Example:
ALTER TABLE Customer
ALTER COLUMN CustCity char(30) NOT NULL;
This command will ensure that the user enters a value for the CustCity columns on the Customer table, failing
which it returns an error message.
Check Constraint:
Check constraint can be defined to allow only a particular range of values.when the manipulation violates this
constraint; the record will be rejected.Check condition cannot contain sub queries.
Example:
CREATE TABLE Customer1
(CustNo CHAR(8) check (len(CustNo)>=8),
CustFirstName VARCHAR(20) CONSTRAINT CustFirstNameRequired1 NOT NULL,
CustLastName VARCHAR(30) CONSTRAINT CustLastNameRequired1 NOT NULL,
CustStreet VARCHAR(50),
CustCity VARCHAR(30),
CustState CHAR(2),
CustZip CHAR(10),
CustBal DECIMAL(12,2) DEFAULT 0,
CONSTRAINT PKCustomer1 PRIMARY KEY (CustNo))
b) Entity Integrity
Maintains uniqueness in a record. An entity represents a table and each row of a table represents an instance of
that entity. To identify each row in a table uniquely we need to use this constraint. There are 2 entity
constraints:
a) Unique key constraint
It is used to ensure that information in the column for each record is unique, as with telephone or drivers license
numbers. It prevents the duplication of value with rows of a specified column in a set of column. A column
defined with the constraint can allow null value.
If unique key constraint is defined in more than one column i.e., combination of column cannot be specified.
Maximum combination of columns that a composite unique key can contain is 16.
Example:
CREATE TABLE Customer2
(CustNo CHAR(8),
CustFirstName VARCHAR(20) CONSTRAINT CustFirstNameRequired1 NOT NULL,
CustLastName VARCHAR(30) CONSTRAINT CustLastNameRequired1 NOT NULL,
CustStreet VARCHAR(50) CONSTRAINT cust_uniq_street UNIQUE,
CustCity VARCHAR(30),
CustState CHAR(2),
CustZip CHAR(10),
CustBal DECIMAL(12,2) DEFAULT 0,
CONSTRAINT PKCustomer2 PRIMARY KEY (CustNo))
You can add unique constraint, If you forget to add it while creating table.
Note: Can’t be defined using alter command when there is records in the table having null values.
c) Referential Integrity
It enforces relationship between tables. To establish parent-child relationship between 2 tables having a
common column definition, we make use of this constraint. To implement this, we should define the column in
the parent table as primary key and same column in the child table as foreign key referring to the corresponding
parent entry.
Foreign key
A column or combination of column included in the definition of referential integrity, which would refer to a
referenced key.
Referenced key
It is a unique or primary key upon which is defined on a column belonging to the parent table.
Example:
Summary
An integrity constraint is a mechanism used by oracle to prevent invalid data entry into the table. It has
enforcing the rules for the columns in a table.
OBJECTIVE
Exécute SQL DML (Data Manipulation Language) statements to manipulate data stored in a relational database
management system (RDBMS).
THEORY
Insert Command
This is used to add one or more rows to a table. The values are separated by commas and the data types char and
date are enclosed in apostrophes. The values must br entered in the same order as they are defined.
Example:
insert into Customer values ('C0954327','Sheri','Gordon','336 Hill
St.','Littleton','CO','80129-5543',$230.00)
Example:
insert into Customer values
('C1010398','Jim','Glussman','1432 E. Ravenna','Denver','CO','80111-0033',$200.00),
('C2388597','Beth','Taylor','2396 Rafter Rd','Seattle','WA','98103-1121',$500.00),
('C3340959','Betty','Wise','4334 153rd NW','Seattle','WA','98178-3311',$200.00)
Select Commands
It is used to retrieve information from the table. It is generally referred to as querying the table. We can either
display all columns in a table or only specify column from the table.
Example
select * from Employee
Example:
Select empno, empfirstname from employee;
Wildcard Operators
Use of Like operator (% and _ are used for
multiple & Single Char matching)
Update Command
It is used to alter the column values in a table. A single column may be updated or more than one column could
be updated.
Delete command
After inserting row in a table we can also delete them if required. The delete command consists of a from clause
followed by an optional where clause.
Summary
A data manipulation language (DML) is a family of syntax elements similar to a computer programming
language used for selecting, inserting, deleting and updating data in a database. Performing read-only queries of
data is sometimes also considered a component of DML. Data manipulation language comprises the SQL data
change statements, which modify stored data but not the schema or database objects. Manipulation of persistent
database objects, e.g., tables or stored procedures, via the SQL schema statements, rather than the data stored
within them, is considered to be part of a separate data definition language. In SQL these two categories are
similar in their detailed syntax, data types, expressions etc., but distinct in their overall function.
Web Resources for Additional Studies
http://www.1keydata.com/
http://www.w3schools.com/
In ascending order.
In descending order
OBJECTIVE
Execute SQL Group by and having clauses to group and filter data in the result set of a SQL query based on
certain criteria.
THEORY
Group Functions
A group function returns a result based on group of rows.
aggr
2. Max:
Example: select Max(EmpCommRate) from Employee;
3. Min
Example: select Min(EmpCommRate) from Employee;
4. Sum
Example: select sum (custbal) from customer;
Count Function
In order to count the number of rows, count function is used.
Group by clause
This is function is used in conjunction with the aggregate functions to group the result-set by one or more
columns. This allows us to use simultaneous column name and group functions.
Example:
Select CustState, max(CustBal)
from Customer
Having clause
This is used to specify conditions on rows retrieved by using group by clause.
Example:
Select CustState, max(CustBal)
from Customer
group by CustState
Having max(CustBal)>300;
Special Operators
In / not in – used to select a equi from a specific set of values
Any - used to compare with a specific set of values
Between / not between – used to find between the ranges
Like / not like – used to do the pattern matching
Summary
The group by clause is used to group the data. The group by and having clauses are very important for data
analysis.
EventPlan
planno eventno workdate notes activity empno
P100 E100 25-Oct-2018 Standard operation Operation E102
P101 E104 03-Dec-2018 Watch for gate crashers Operation E100
P102 E105 05-Dec-2018 Standard operation Operation E102
P103 E106 12-Dec-2018 Watch for seat switching Operation
P104 E101 26-Oct-2018 Standard cleanup Cleanup E101
P105 E100 25-Oct-2018 Light cleanup Cleanup E101
P199 E102 10-Dec-2018 Standard operation Operation E101
P299 E101 26-Oct-2018 Operation E101
P349 E106 12-Dec-2018 Cleanup E101
P85 E100 25-Oct-2018 Standard operation Setup E102
P95 E101 26-Oct-2018 Extra security Setup E102
OBJECTIVE
Exécute SQL aggregate functions to perform calculations on sets of values in a database table.
THEORY
Functions
Function accepts zero or more arguments and both return one or more results. Both are used to manipulate
individual data items. Operators differ from functional in that they follow the format of function_name(arg..).
An argument is a user defined variables or constants. Most operators accept at most 2 arguments while the
structure of functions permit to accept 3 or more arguments. Function can be classifying into single row
function and group functions.
Date Function
They operate on date values and produce outputs, which also belong to date data type except for months,
between, date function returns a number.
1. DATEADD(): This function returns a date after adding a specified date with specified number of days,
months or years.
2. Months_between
It gives the difference in number of months between d1 & d2.
Example:
SELECT DATEDIFF(YYYY, '15-Jan-2017', GETDATE())
5. Round
This function returns value, which is rounded to the unit specified by the format model.
Example:
SELECT ROUND(235.415, 2) AS RoundValue;
Numerical Functions
6. Replace
The REPLACE() function replaces all occurrences of a substring within a str, with a new substring.
Parameter Description
str Required. The original string
old_str Required. The string to be replaced
new_str Required. The new replacement string
Example:
SELECT REPLACE('Jack and jue', 'j', 'bl');
7. Substring
This function extracts some characters from a string .
Parameter Description
str Required. The string to extract from
start Required. The start position. The first position in string is 1
length Required. The number of characters to extract. Must be a positive
number
Example:
SELECT SUBSTRING('information', 3, 4) AS 'Part of String';
Character Functions
Conversion Function
1. Date Converstion
This function converts date to a value of varchar type in a form specified by date format. If format is negelected
then it converts date to varchar2 in the default date format.
Example:
SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM (or PM) SELECT convert(varchar,
getdate(), 101) -- mm/dd/yyyy - 10/02/2015
SELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd – 2015.10.02
SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy
SELECT convert(varchar(12),getdate(),106) --dd-mon-yyyy 15 Nov 2015
Summary
A built-in function is an expression in which an SQL keyword or special operator executes some operation.
Built-in functions use keywords or special built-in operators. Function accepts zero or more arguments and both
return one or more results. Both are used to manipulate individual data items. Operators differ from functional
in that they follow the format of function_name (arg..).
Perform complex filtering and retreive data from multiple tables uisng SQL nested queries.
THEORY
Nested Queries
Subqueries
The query within another is known as a subquery. A statement containing subquery is called parent statement.
The rows returned by subquery are used by the parent statement.
Syntax
Example: To get employee, whose commission is greater then the commission of Amy.
select EmpNo, EmpFirstName, EmpPhone, EmpCommRate
from Employee
where EmpCommRate >(select EmpCommRate
from employee
where EmpFirstName ='Amy');
Note:- The subquery (inner query) executes once before the main query (outer query) and The result of the
subquery is used by the main query.
Types
Subqueries can also return more than one value. Such results should be made use along with the operators IN,
ANY and ALL
Operator Meaning
Example: To get customer, whose balance is greater then balance of all customer belongs to ‘CO’ state.
select custno, custBal
from customer
where custbal >all (select custbal
from customer
where custState ='CO');
2. Multiple queries
Here more than one subquery is used. These multiple subqueries are combined by
means of ‘and’ & ‘or’ keywords.
SetOperators
The Set operator combines the result of 2 queries into a single result.The following are the operators:
Union
Union all
Intersect
Minus
The rules to which the set operators are strictly adhere to:
The queries which are related by the set operators should have a same number of column and column
definition.
Such query should not contain a type of long.
54 CS 220 Database System –Sub Queries
Labels under which the result is displayed are those from the first select statement.
Union:
Rules:
• SELECT statement within the UNION must have the same number of colns.
• The columns must also have similar data types.
• The columns in each SELECT statement must be in the same order.
Syntax:
select * from Customer where Custcity='Denver' or CustCity='Englewood'
union
select * from Customer where Custcity='Denver' or Custcity='Littleton'
Intersect:
Syntax:
select * from Customer where Custcity='Denver' or CustCity='Englewood'
intersect
select * from Customer where Custcity='Denver' or Custcity='Littleton'
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were
coming from one single table.
The query within another is known as a subquery. A statement containing subquery is called parent statement.
The rows returned by subquery are used by the parent statement. A Subquery or Inner query or Nested query is
a query within another SQL query and embedded within the WHERE clause.A subquery is used to return data
that will be used in the main query as a condition to further restrict the data to be retrieved.
FROM your_table_name
SELECT MAX(estcost)
FROM your_table_name
);
SELECT *
FROM customers
WHERE city = (
SELECT city
FROM customers
WHERE name = 'Babar Nawaz'
);
SELECT *
FROM Eventrequest
SELECT MAX(estcost)
FROM ApprovedEvents
);
SELECT *
FROM Eventrequest
WHERE estcost < (
SELECT AVG(estcost)
FROM Eventrequest
);
b. List all event requested, which has estimated cost is greater than all pending events using ALL operator.
SELECT *
FROM EventRequests
WHERE estcost > ALL (
SELECT estcost
FROM PendingEvents
);
c. List all event requested, which has estimated cost is less than any pending events using ANY operator.
SELECT *
FROM EventRequests
WHERE estcost < ANY (
SELECT estcost
FROM PendingEvents
);
FROM Customers;
EventRequest
eventno dateheld datereq facno custno dateauth status estcost estaudience budno
E100 25-Oct-2018 06-Jun-2018 F100 C100 08-Jun-2018 Approved $5,000.00 80000 B1000
E101 26-Oct-2018 28-Jul-2018 F100 C100 Pending $5,000.00 80000 B1000
E102 14-Sep-2018 28-Jul-2018 F100 C100 31-Jul-2018 Approved $5,000.00 80000 B1000
E103 21-Sep-2018 28-Jul-2018 F100 C100 01-Aug-2018 Approved $5,000.00 80000 B1000
E104 03-Dec-2018 28-Jul-2018 F101 C101 31-Jul-2018 Approved $2,000.00 12000 B1000
E105 05-Dec-2018 28-Jul-2018 F101 C101 01-Aug-2018 Approved $2,000.00 10000 B1000
E106 12-Dec-2018 28-Jul-2018 F101 C101 31-Jul-2018 Approved $2,000.00 10000 B1000
E107 23-Nov-2018 28-Jul-2018 F100 C105 31-Jul-2018 Denied $10,000.00 5000
Exécute SQL joins to retrieve and present data from multiple tables in a single result set based on combine rows
from two or more tables based on related columns between them.
THEORY
SQL Joins:
The purpose of a join concept is to combine data spread across tables. A join is actually performed by the
‘where’ clause which combines specified rows of tables.
PROGRAMS
Syntax:
• Select
• From
• Join
• On
• Where
Cross Join
• A cross join (also called a Cartesian join) is a join of tables without specifying the join condition.
• In this scenario, the query would return all possible combination of the tables in the SQL query.
• CROSS JOIN returns the Cartesian product of rows from tables in the join.
• In other words, it will produce rows which combine each row from the first table with each row from the
second table.
Cartesian product
• In mathematics, a Cartesian product (or product set) is the direct product of two sets.
• Specifically, the Cartesian product of two sets X (for example the points on an x-axis) and Y (for
example the points on a y-axis), denoted X × Y, is the set of all possible ordered pairs whose first com-
ponent is a member of X and whose second component is a member of Y (e.g., the whole of the x–y
plane):
Example:
• A = {1,2}; B = {3,4}
• A × B = {1,2} × {3,4} = {(1,3), (1,4), (2,3), (2,4)}
Inner join
• Inner join creates a new result table by taking
• Cartesian product
• filter (join predicate)
Types of Join
Composite join: This join has more than one condition on single ON clause.
Example:
SELECT * FROM Customer
INNER JOIN OrderTbl ON Customer.CustNo = OrderTbl.CustNo and CustState='CO'
Equi join: This join has an only equality comparison on join predicate.
Example:
SELECT * FROM Customer
INNER JOIN OrderTbl ON Customer.CustNo = OrderTbl.CustNo;
Non-equijoin: This join has other operator than equality on join predicate.
Example:
SELECT * FROM Customer
INNER JOIN OrderTbl ON Customer.CustNo != OrderTbl.CustNo;
Multitable join: This join is used to join more than two tables. Processing starts from left to right.
Example:
SELECT Customer.CustNo, CustFirstName, OrderTbl.OrdNo, OrdDate, Product.ProdNo, ProdName FROM
Customer
INNER JOIN OrderTbl ON Customer.CustNo = OrderTbl.CustNo
INNER JOIN OrdLine ON OrderTbl.OrdNo = OrdLine.OrdNo
INNER JOIN Product ON OrdLine.ProdNo = Product.ProdNo
Summary
A SQL join clause combines records from two or more tables in a database. It creates a set that can be saved as
a table or used as it is. A JOIN is a means for combining fields from two tables by using values common to
each. ANSI-standard SQL specifies five types of JOIN: INNER, LEFT OUTER, RIGHT OUTER, FULL
OUTER and CROSS. As a special case, a table (base table, view, or joined table) can JOIN to itself in a self-
join.
Perform SQL outer join to retrieve data from multiple tables while including unmatched rows from one or both
of the joined tables.
THEORY
SQL Joins:
68 CS 220 Database Systems – Sub Queries
The purpose of a join concept is to combine data spread across tables. A join is actually performed by the
‘where’ clause which combines specified rows of tables.
Example: Write a query to display the employee and their Supvisor Name.
Outer Join (Left, Right, Full): Outer join gives results by taking:
• Cartesian product
• filter (join predicate)
• get outer rows
Summary
A SQL join clause combines records from two or more tables in a database. It creates a set that can be saved as
a table or used as it is. A JOIN is a means for combining fields from two tables by using values common to
each. ANSI-standard SQL specifies five types of JOIN: INNER, LEFT OUTER, RIGHT OUTER, FULL
OUTER and CROSS. As a special case, a table (base table, view, or joined table) can JOIN to itself in a self-
join.
Perform Nested queries in SQL combined with joins to achieve more complex and sophisticated data retrieval
and manipulation.
THEORY
An SQL Join statement is used to combine data or rows from two or more tables based on a common field
between them. A subquery is a query that is nested inside a SELECT, INSERT, UPDATE, or DELETE
statement, or inside another subquery. Joins and subqueries are both used to combine data from different tables
into a single result.
In the example below, the subquery actually returns a temporary table which is handled by database server in
memory. The temporary table from the subquery is given an alias so that we can refer to it in the outer select
statement.
Note that the left and right table of the join keyword must both return a common key that can be used for the
join. Also note that, using subquery in JOIN operation should generally be avoided if you can rewrite your
query in a different way, the reason being that no indexes can be used on a temporary table in memory.
Example :-
select y.CategoryID,
y.CategoryName,
round(x.actual_unit_price, 2) as "Actual Avg Unit Price",
round(y.planned_unit_price, 2) as "Would-Like Avg Unit Price"
from
(
select avg(a.UnitPrice) as actual_unit_price, c.CategoryID
from order_details as a
inner join products as b on b.ProductID = a.ProductID
inner join categories as c on b.CategoryID = c.CategoryID
group by c.CategoryID
) as x
inner join
(
select a.CategoryID, b.CategoryName, avg(a.UnitPrice) as planned_unit_price
from products as a
inner join categories as b on b.CategoryID = a.CategoryID
group by a.CategoryID
) as y on x.CategoryID = y.CategoryID
First of these is a subquery in a FROM clause using a GROUP BY to calculate aggregate values.
Example :-
SELECT city, sum_price
FROM
(
SELECT city, SUM(price) AS sum_price FROM sale
GROUP BY city
) AS s
WHERE sum_price < 2100;
The subquery selects the cities and calculates the sum of the sale prices by city. The sum of all sale prices in
each city from the sale table is calculated by the aggregate function SUM(). Using the results of the subquery,
the outer query selects only the cities whose total sale price is less than 2,100 (WHERE sum_price < 2100).
You should remember from previous lessons how to use aliases for subqueries and how to select an aggregate
value in an outer query.
Summary
Customer
custno custname address Internal contact phone city state zip
C100 Faisal Naseer Box 352200 Yes Mary Manager 6857100 Boulder CO 80309
C101 Mubashir Nazir Box 352400 Yes Sally Supervisor 5431700 Boulder CO 80309
C103 Babar Nawaz Box 352020 Yes Bill Baseball 5431234 Boulder CO 80309
C104 Waheed Iqbal Box 351200 Yes Sue Softball 5434321 Boulder CO 80309
C105 Hashir Shahid 123 AnyStreet No Coach Bob 4441234 Louisville CO 80027
EventRequest
eventno dateheld datereq facno custno dateauth status estcost estaudience budno
E100 25-Oct-2018 06-Jun-2018 F100 C100 08-Jun-2018 Approved $5,000.00 80000 B1000
E101 26-Oct-2018 28-Jul-2018 F100 C100 Pending $5,000.00 80000 B1000
E102 14-Sep-2018 28-Jul-2018 F100 C100 31-Jul-2018 Approved $5,000.00 80000 B1000
E103 21-Sep-2018 28-Jul-2018 F100 C100 01-Aug-2018 Approved $5,000.00 80000 B1000
E104 03-Dec-2018 28-Jul-2018 F101 C101 31-Jul-2018 Approved $2,000.00 12000 B1000
E105 05-Dec-2018 28-Jul-2018 F101 C101 01-Aug-2018 Approved $2,000.00 10000 B1000
E106 12-Dec-2018 28-Jul-2018 F101 C101 31-Jul-2018 Approved $2,000.00 10000 B1000
E107 23-Nov-2018 28-Jul-2018 F100 C105 31-Jul-2018 Denied $10,000.00 5000
EventPlan
planno eventno workdate notes activity empno
P100 E100 25-Oct-2018 Standard operation Operation E102
P101 E104 03-Dec-2018 Watch for gate crashers Operation E100
P102 E105 05-Dec-2018 Standard operation Operation E102
P103 E106 12-Dec-2018 Watch for seat switching Operation
P104 E101 26-Oct-2018 Standard cleanup Cleanup E101
P105 E100 25-Oct-2018 Light cleanup Cleanup E101
P199 E102 10-Dec-2018 Standard operation Operation E101
P299 E101 26-Oct-2018 Operation E101
P349 E106 12-Dec-2018 Cleanup E101
P85 E100 25-Oct-2018 Standard operation Setup E102
P95 E101 26-Oct-2018 Extra security Setup E102
EXPERIMENT 11 – PROGRAMMABLE OBJECTS IN SQL
OBJECTIVE
Perform T-SQL that includes a set of programming constructs and extensions to the standard SQL language,
making it a powerful tool for working with these database systems.
THOERY
Variables
Begin
PRINT 'Welcome to '+CHAR(10)+'MCS, NUST';
PRINT CHAR(10);
PRINT 'Current date and time is ' +CONVERT(VARCHAR(20), GETDATE());
End
Example:
• Declare a variable:
DECLARE @per_marks double
DECLARE @min_range , @hi_range int
• Assign a value into a variable:
SET @min_range = 0, @hi_range = 100
SET @ per_marks = 70.53
• Assign a value into a variable in SQL statement:
SELECT @sal = salary FROM Employee WHERE EmpId = ’23091‘
Example:
Begin
DECLARE @sal int
SELECT @sal=salary FROM Employee WHERE EmpId=2312
print 'Your Salary is '+convert(varchar, @sal)
End
Defines conditional and, optionally, alternate execution when a condition is false following is general syntax.
IF Boolean_expression
T-SQL_statement | block_of_statements
[ELSE
T-SQL_statement | block_of_statements ]
Example:
Begin
DECLARE @sal int
SELECT @sal=salary FROM Employee WHERE EmpId=2313
if (@sal>5000)
print 'Your Salary is greater then 5000'
else
print 'Your Salary is less then 5000'
End
Example:
Declare @var int
Set @var = 1
If @var = 1
Print ‘this is the code executed when true’
else
Print ’this is the code executed when false’
Example:
DECLARE @Counter INT
SET @Counter=1
WHILE ( @Counter <= 10)
BEGIN
PRINT 'The counter value is = ' + CONVERT(VARCHAR,@Counter)
SET @Counter = @Counter + 1
END
Example:
DECLARE @intFlag INT
SET @intFlag=1
WHILE ( @intFlag <= 10)
BEGIN
PRINT 'The flag value is = ' + CONVERT(VARCHAR,@intflag)
SET @intFlag = @intFlag + 1
END
Example:
DECLARE @Counter INT , @MaxId INT, @EmpName NVARCHAR(100)
SELECT @Counter = min(Id) , @MaxId = max(Id) FROM EmpTable
WHILE(@Counter IS NOT NULL
AND @Counter <= @MaxId)
BEGIN
SELECT @CountryName = EmpName
FROM EmpTable WHERE Id = @Counter
PRINT CONVERT(VARCHAR,@Counter) + '. employee name is ' + @EmpName
SET @Counter = @Counter + 1
END
Summary
Modularized program development using conditions and loop structures.
EventRequest
eventno dateheld datereq facno custno dateauth status estcost estaudience budno
E100 25-Oct-2018 06-Jun-2018 F100 C100 08-Jun-2018 Approved $5,000.00 80000 B1000
E101 26-Oct-2018 28-Jul-2018 F100 C100 Pending $5,000.00 80000 B1000
E102 14-Sep-2018 28-Jul-2018 F100 C100 31-Jul-2018 Approved $5,000.00 80000 B1000
E103 21-Sep-2018 28-Jul-2018 F100 C100 01-Aug-2018 Approved $5,000.00 80000 B1000
E104 03-Dec-2018 28-Jul-2018 F101 C101 31-Jul-2018 Approved $2,000.00 12000 B1000
E105 05-Dec-2018 28-Jul-2018 F101 C101 01-Aug-2018 Approved $2,000.00 10000 B1000
E106 12-Dec-2018 28-Jul-2018 F101 C101 31-Jul-2018 Approved $2,000.00 10000 B1000
E107 23-Nov-2018 28-Jul-2018 F100 C105 31-Jul-2018 Denied $10,000.00 5000
EXPERIMENT 12 – STORED PROCEDURES
OBJECTIVE
Construct SQL procedures to write SQL code once and reuse it multiple times in various parts of an application
or across different applications.
THOERY
Stored Procedures
A procedure is a block that can take parameters (sometimes referred to as arguments) and be invoked.
Procedures promote reusability and maintainability. Once validated, they can be used in number of applications.
If the definition changes, only the procedure are affected, this greatly simplifies maintenance.
Sql server compiles each stored procedure once and then store compile and execution plans in query cache and
reuse for subsequent executions. so you get tremendous performance boost when stored procedures are called
repeatedly.
Abstraction:
Stored procedures provide an abstraction layer that shields applications from the underlying database structure.
Example:
• Parameters are local variables that are used to pass values into a stored procedure when it is executed.
• U can create two types of parameters:
• Input and output
• Output parameters are used when u need to return a single value to an application.
Practice
1: Write and execute a procedure (Print_Emp) to print all employee of computer with their salary.
2: Write and execute a procedure (Print_Dept) to print department wise no of employee and sum of their salary.
3: Write and execute a procedure (Print_Employee_Info) to print the complete details of a single employee
whose empno pass as parameter.
4: Write and execute a procedure (Increase_Sal) to 25% increase in the salary of all employees.
5: Write and execute a procedure (Add_Emp) to insert newly hired employee all info passed as parameters. This
procedure observe the following rules.
Checks the empno pass as parameter is not exist
Checks the deptno exits in department table.
Checks the salary of employee must be >= 5000
Summary
A procedure is a block that can take parameters (sometimes referred to as arguments) and be invoked.
Procedures promote reusability and maintainability. Once validated, they can be used in number of applications.
If the definition changes, only the procedure are affected, this greatly simplifies maintenance.
Modularized program development:
· Group logically related statements within blocks.
· Nest sub-blocks inside larger blocks to build powerful programs.
· Break down a complex problem into a set of manageable well defined logical modules and implement the
modules with blocks.
Customer
custno custname address Internal contact phone city state zip
C100 Faisal Naseer Box 352200 Yes Mary Manager 6857100 Boulder CO 80309
C101 Mubashir Nazir Box 352400 Yes Sally Supervisor 5431700 Boulder CO 80309
C103 Babar Nawaz Box 352020 Yes Bill Baseball 5431234 Boulder CO 80309
C104 Waheed Iqbal Box 351200 Yes Sue Softball 5434321 Boulder CO 80309
C105 Hashir Shahid 123 AnyStreet No Coach Bob 4441234 Louisville CO 80027
Employee
empno empname department email Salary phone
E100 Chuck Coordinator Administration [email protected] 5000 3-1111
E101 Mary Manager IT [email protected] 6000 5-1111
E102 Sally Supervisor Planning [email protected] 7000 3-2222
E103 Alan Administrator Administration [email protected] 5500 3-3333
EXPERIMENT 13 – TRIGGERS
OBJECTIVE
Construct SQL Triggers to enforce Data integrity constraints in relational database systems.
THEORY
A trigger is a PL/SQL block or a PL/SQL procedure that executes implicitly whenever a particular event takes
place. It can either be:
2. Database Trigger: Fires whenever a data event (such as DML) occurs on a schema or database.
DDL Triggers
• Create
• Alter
• Drop
• For/After (create/alter/drop)
• AFTER specifies that the DML trigger is fired only when all operations specified in the triggering SQL
statement have executed successfully. All referential cascade actions and constraint checks also must
succeed before this trigger fires.
• AFTER is the default when FOR is the only keyword specified.
DML Trigger
• Insert
• Update
• Delete
• For/After ( insert, update, delete)
• Instead of ( insert, update, delete)
• Specifies that the DML trigger is executed instead of the triggering SQL statement, therefore, overriding
the actions of the triggering statements. INSTEAD OF cannot be specified for DDL or logon triggers
and DML.
• When a trigger is executed, two special tables inserted and deleted are available.
• These tables help to maintain the record of updates.
PROGRAMS
Summary
A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server.
DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events
are INSERT, UPDATE, or DELETE statements on a table or view. These triggers fire when any valid event is fired,
regardless of whether or not any table rows are affected. For more information, see DML Triggers.
DDL triggers execute in response to a variety of data definition language (DDL) events. These events primarily
correspond to Transact-SQL CREATE, ALTER, and DROP statements, and certain system stored procedures that perform
DDL-like operations. Logon triggers fire in response to the LOGON event that is raised when a user sessions is being
established. Triggers can be created directly from Transact-SQL statements or from methods of assemblies that are
created in the Microsoft .NET Framework common language runtime (CLR) and uploaded to an instance of SQL Server.
SQL Server allows for creating multiple triggers for any specific statement.
Customer
custno custname address Internal contact phone city state zip
C100 Faisal Naseer Box 352200 Yes Mary Manager 6857100 Boulder CO 80309
C101 Mubashir Nazir Box 352400 Yes Sally Supervisor 5431700 Boulder CO 80309
C103 Babar Nawaz Box 352020 Yes Bill Baseball 5431234 Boulder CO 80309
C104 Waheed Iqbal Box 351200 Yes Sue Softball 5434321 Boulder CO 80309
C105 Hashir Shahid 123 AnyStreet No Coach Bob 4441234 Louisville CO 80027
Employee
empno empname department email Salary phone
E100 Chuck Coordinator Administration [email protected] 5000 3-1111
E101 Mary Manager IT [email protected] 6000 5-1111
E102 Sally Supervisor Planning [email protected] 7000 3-2222
E103 Alan Administrator Administration [email protected] 5500 3-3333
EXPERIMENT 14 – APPLICATION DEVELOPMENT WITH SQL + FRONT END TOOL (JAVA)
OBJECTIVE
Develop the secure databse connection with Java to enable Java applications to interact with databases
effectively.
Tools
Netbeans (Front End)
Sql server (Back End)
THEORY
Steps
1. In sql server management studio login using
Server Name: DESKTOP-F2DHUN6
User name : sa
Password: 123
2. Now select database (Practice25A30Nov) and create new query for table as shown figure
12. From explorer right click on connection and select properties > click on view connection properties
13. Create new project in Netbeans.
17. Now add this code to your project. add username (sa) and password (123) to jdbcurl and pass it in
getconnection method
package dbconn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author kabeer
*/
public class DBConn {
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection("jdbc:sqlserver://DESKTOP-
F2DHUN6:1433;databaseName=Practice25A30Nov;userName=sa;password=123");
PreparedStatement statement = connection.prepareStatement("select * from user_info");
ResultSet result = statement.executeQuery();
while (result.next()) {
System.out.print(result.getString("id")+" ");
System.out.print(result.getString("name")+" ");
System.out.println(result.getString("city")+" ");
}
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
18. Final Run the Program to display the data from table.
Customer
custno custname address Internal contact phone city state zip
C100 Faisal Naseer Box 352200 Yes Mary Manager 6857100 Boulder CO 80309
C101 Mubashir Nazir Box 352400 Yes Sally Supervisor 5431700 Boulder CO 80309
C103 Babar Nawaz Box 352020 Yes Bill Baseball 5431234 Boulder CO 80309
C104 Waheed Iqbal Box 351200 Yes Sue Softball 5434321 Boulder CO 80309
C105 Hashir Shahid 123 AnyStreet No Coach Bob 4441234 Louisville CO 80027
Employee
empno empname department email phone
E100 Chuck Coordinator Administration [email protected] 3-1111
E101 Mary Manager Football [email protected] 5-1111
E102 Sally Supervisor Planning [email protected] 3-2222
E103 Alan Administrator Administration [email protected] 3-3333
EXPERIMENT 15– OPEN ENDED LAB (DATABASE SYSTEM)
Back Ground
Diversity in age has emerged as a strategic advantage that can provide organizations with a competitive edge. The
workforce of many organizations exhibits a rich spectrum of ages, making it one of the most diverse demographic
factors. It is widely acknowledged that organizational culture, human resource practices, the nature of work, and
the unique business strategies of individual firms set them apart from one another. These distinctions are likely to
influence the way various variables impact employee performance, with variations between firms.
In this laboratory experiment, students are tasked with exploring the correlation between employees' ages and
organizational performance, shedding light on the multifaceted relationship between these factors.
TASKS
Task 1: Data Retrieval Write an SQL query to retrieve the names and ages of all employees from the
"Employee" table in a database. Organize the result in ascending order of age.
Task 2: Age Group Analysis Extend the previous query to categorize employees into age groups (e.g., "Under
30," "30-40," "Over 40"). Calculate and display the count of employees in each age group.
Task 3: Organizational Performance Analysis Create an SQL query to retrieve data from an
"OrganizationalPerformance" table that contains performance metrics for different companies. Join this table with
the "Employee" table using a relevant key and filter the results for a specific company. Calculate the average
performance score for employees in different age groups within that company.
Task 4: Cross-Company Comparison Compare the average performance scores of employees in two different
companies from the "OrganizationalPerformance" table. Calculate and display the difference in average
performance scores between these two companies for each age group of employees.
Deliverables
1. Create a lab report detailing the SQL queries used to perform the four tasks.
2. Provide the result sets showing the outputs of each task.
3. Present your findings and analysis on how performance scores vary across companies and age groups.
Note: Each deliverable should be accompanied by clear explanations, SQL code, result sets, and any relevant
observations or insights. Students should ensure that their reports are well-organized and effectively communicate
their findings from the SQL tasks.
“I hear and I forget,
I see and I remember,
I do and I understand”
Confuciu
s