6th Sem-DBMS-Reference Up To Unit 5
6th Sem-DBMS-Reference Up To Unit 5
Data:
Data is commonly defined as raw facts or observation, typically about physical phenomena or
business transactions. For example of data would be the marks obtained by students in
different subjects. Data can be in any form-numerical, textual, graphical, image, sound, video
etc.
The following figure shows the hierarchy of data storage.
Bit
Character
Field
Record
File
Database
Fig:- Data storage hierarchy
Information:
Information is defined as refined or processed data that has been transformed into
meaningful and useful form for specific users. For example, after processing the marks
obtained by student it transformed into information, which is meaningful and from which
we can decide which student stood first, second and so forth. Information comes from data
and takes the form of table, graphs, diagrams etc.
1
By: Abhimanu Yadav
Database:
A database is an organized collection of data and contains information relevant to an
enterprise. The database is also called the repository or container for a collection of data files.
For example, university database for maintaining information about students, courses and
grades in university.
For example, in a computer system, the checking account processing system, the auto loan
system and the saving accounts would have a common database. This database based
approach to data processing is shown in fig below:
A Checking Account
Ss Organizational Program
Database Management
database
system (DBMS) A Auto Loan Program
F Saving Account
Fig: Database approach to data processing
Program
2
By: Abhimanu Yadav
Objective of DBMS
The DBMS is able
To provide large space or storage for relevant data.
To provide easy access to the data for the users.
To provide quick response to user request for any data.
To remove duplicate (redundant) data.
To update the database latest modification immediately.
To allow the multiple users to be active at one time.
As the organization grows, DBMS allows the growth of the database system.
To provide maximum protection to data from any physical damage and unauthorized
access.
Database system:
A database system consists of database, database Management system, and application
program. A database system is just a computerized record keeping system. Database is a
repository for a collection of computerized data files. Users of database system can perform a
variety of operation on such file.
Some common examples of the DBMS software are Oracle, Sybase, Microsoft SQL Server,
DB2, MySQL, Postgres, Dbase, Ms-Access etc.
Applications of DBMS:
Databases form an essential part of almost all enterprises. Some database applications are
given below:
Banking: For customer information and all transactions
Airlines: For reservations and schedules information
Universities: For the student information , course registration and grades
Credit and transaction: For purchase credit cards and generates monthly statement
Telecommunication: Keeping records of all the telephone calls, generating monthly
bills etc.
Finance: For storing financial information
Sales :For customers, products and purchases information
Manufacturing: For tacking production, inventory, orders, supply chain management
Human resources: For storing the information about employee records, salaries, tax
deductions
Flat-file Systems:
A flat file system stores data in a plain text file. A flat file is a file that contains records, and in
which each record is specified in a single line. Fields from each record may simply have a fixed
width with padding, or may be delimited by whitespace, tabs, commas or other characters.
Extra formatting may be needed to avoid delimiter collision. There are no structural
3
By: Abhimanu Yadav
relationships. The data are "flat" as in a sheet of paper, in contrast to more complex models such
as a relational database.
For example, in a computer system, the checking account processing system would have its own
data files. This file based approach to data processing is shown in fig below:
SfChecking Account
Checking Account Programs
Data Files
not need access to information about customer accounts. But, since application
programs are added to the system in an ad hoc manner, enforcing such security
constraints is difficult in flat file system.
Disadvantages of DBMS
Problem associated with centralization: Centralization increases the security problems.
Cost of software: Today’s there are several softwares which are very costly. Hence from
economic point of view it is the drawback.
5
By: Abhimanu Yadav
6
By: Abhimanu Yadav
Stored database
Physical level
It is the lowest level of abstractions describes how the data are actually stored.
The physical level describes complex low level data structure in details.
At this level records such as customer, account can be described as a block of consecutive
storage location (e.g. byte, word)
The database system hides many of the lowest level storage details from database
programmer. Database administrator may be aware of certain details of the physical
organization of the data.
Logical level
It is the next higher level of data abstraction which describes what data are stored in the
database, and what relationships exist among those data.
At the logical level , each record is described by a type definition
Programmers and database administrator works at this level of abstraction.
View level
It is the highest level of abstraction describes only a part of the database and hides some
information to the user.
At view level, computer users see a set of application programs that hide details of data
types. Similarly at the view level several views of the database are defined and database
user see only these views.
Views also provides the security mechanism to prevent users from accessing certain parts
of the database (that is views can also hide information (such as an employee‘s salary) for
security purposes.)
7
By: Abhimanu Yadav
Valid State
A state that satisfies the structure and constraints of the database.
Schema:
The overall design of the database which is not expected to change frequently is called
database schema. Simply, the database schema is the logical structure of the database.
The concept of database schema and instances can be understood by analogy to a
program written in a programming language
A database schema corresponds to the variable declaration and the values of the variables
in a program at a point in time correspond to an instance of a database.
The database systems have several schemas and partitioned according to the level of
abstraction such as physical and logical schema.
STUDENT
Name Student-number Class Major
Fig: Schema diagram for Student
Note:
The database schema changes very infrequently.
The database state changes every time the database is updated.
Data Independence:
The three schema architecture further explains the concept of data independence, the capacity to
change the schema at one level without having to change the schema at the next higher level.
Logical Data Independence
Physical Data Independence
8
By: Abhimanu Yadav
Database Languages:
DBMS provides two languages: Data-Definition Language (DDL) and Data-Manipulation
Language (DML).
Data dictionary: DDL compiler generates a set of tables stored in a data dictionary. Simply,
Data dictionary is a special set of tables that contain the information about tables. Data
dictionary contains metadata (i.e., data about data)
• Metadata: data that describes the database or one of its parts is called metadata. The
schema of a table is an example of metadata
Query: A query is a statement requesting the retrieval of information. SQL is the most widely
used query language Select, insert, update, delete etc are the SQL DML statement
Transaction Management:
Collections of operations that form a single logical unit of work are called transactions. For
example, a transfer of funds from a checking account to a savings account is a single
operation from the customer’s standpoint; within the database system, however, it consists of
several operations. A database system must ensure proper execution of transactions despite
failures—either the entire transaction executes, or none of it does.
Consider the transaction,
10
By: Abhimanu Yadav
A = A – 50;
Write (A);
Read (B);
B = B+50;
Write (B);
To ensure integrity of the data, we require that the database system maintain the following
properties of the transactions:
Atomicity: Either all operations of the transaction are reflected properly in the database
or none are. Suppose during the execution of above transaction a failure occurred after
the write (A) operation but before write (B) operation. Then the values of amount
reflected in database will be 950 and 2000. The system destroyed 50 as a result of failure.
Consistency: Database must be in correct state before and after execution of the
transaction. The consistency requirement here is that sum of A and B be unchanged by
the execution of transaction. Without the consistency requirement, money could be
created or destroyed by a transaction.
Isolation: Even though multiple transactions may execute concurrently, the system
guarantees that, for every pair of transactions Ti and Tj it appears to Ti that either Tj
finished execution before Ti started, or Tj started execution after Ti finished. Thus, each
transaction is unaware of other transactions executing concurrently in the system.
Durability: After a transaction completes successfully, the changes it has made to the
database persist, even if there are system failures.
These properties are called ACID properties, with acronym derived from the first letters of
the above four properties.
11
By: Abhimanu Yadav
Database Administrator:
The person who has such central control over the system is called the database administrator
(DBA). The function of the DBA includes the following:
Schema definition: The DBA creates the original database schema by writing a set of
definitions that is translated by the DDL compiler to a set of tables that is stored
permanently in the data dictionary.
Schema and physical-organization modification: The DBA carries out changes to
the schema and physical organization to reflect the changing needs to the organization,
or to alter the physical organization to improve performance.
Granting the authorization of data access: The granting of different types of
privileges to the database users so that all the users are not able to all data.
Integrity-constraint specifications: The data values stored in the database must
satisfy certain consistency constraints. The database administrator must specify such a
constraint explicitly.
Routine maintenance: Routine maintenance includes periodic backing up the
database, either onto tapes or onto remote servers, to prevent loss of data in case of
disasters such as flooding, Ensuring that enough free disk space is available for normal
operations, and upgrading disk space as required etc.
Database Models:
Data model is a collection of tools for describing data, data relationships, data semantics and data
constraints. The database model refers the way for organizing and structuring the data in the
database. Traditionally, there are different database models which are used to design and develop
the database of the organization.
12
By: Abhimanu Yadav
2. Relational Model:
It is the current favorite model. The relational model is a lower level model that uses a collection
of tables to represent both data and relationships among those data. Each table has multiple
columns, and each column has a unique name. Each table corresponds to an entity set or
relationship set, and each row represents an instance of that entity set or relationship set.
Structured query language (SQL) is used to manipulate data stored in tables.
Customer
Customer_id Customer_name Customer_street Customer_city
1 Bhupi Chandani Kanchanpur
2 Arjun Balkhu Kathmandu
3 Abin Pulchoak Lalitpur
13
By: Abhimanu Yadav
Organization
A parent segment
Personnel Technical
Department Department
14
By: Abhimanu Yadav
The main limitation of this structure is that it does not support flexible data access, because data
can be accessed only by following the path down the tree structure.
Advantages of hierarchical database model
It is the easiest model of database.
It is secure model as nobody can modify the child without consulting to its parent.
Searching is fast.
Very efficient in handling one- to- many relationship.
Disadvantages hierarchical database model
It is old fashion, outdated database model
Modification and addition of child without consulting its parent is impossible.
Cannot handle many- to- many relationships.
Increase redundancy.
It does not support flexible data access, because data can be accessed only by
following the path down the tree structure.
College
15
By: Abhimanu Yadav
16
By: Abhimanu Yadav
Storage Manager:
The storage manager translates the various DML statements into low-level file-system
commands. Storage manager is responsible for storing, retrieving, and updating data in the
database. The storage manager components include:
Authorization and integrity manager: tests for the satisfaction of integrity
constraints and checks the authority of users to access data.
Transaction manager: ensures that the database remains in a consistent state despite
system failures, and the concurrent transaction executions proceed without
conflicting.
File manager: manages the allocation of space on disk storage and the data structures
used to represent information stored on disk.
Buffer manager: responsible for fetching data from disk storage into main memory,
and deciding what data to cache in main memory. The buffer manager is a critical
part of the database system, since it enables the database to handle data sizes that are
much larger than the size of main memory.
Disk Storage:
Data files: which store the database itself.
Data dictionary: which stores metadata about the structure of the database, in
particular the schema of the database.
Indices: which provides fast access to data items that hold particular values.
17
By: Abhimanu Yadav
Basic concepts
Mapping constraints
Key
Entity-relationship diagram
Weak entity set
Extended E-R features
Reduction of an E-R schema to tables
The E-R data models is based on a perception of real world that consist of a collection of
basic objects called entities and relationship among these objects. In an E-R model a database
can be modeled as a collection of entities, and relationship among entities.
18
By: Abhimanu Yadav
Entity:
An entity is an object that exists and is distinguishable from other objects. An entity may be has
a set of properties and the values for some set of properties may uniquely identifies an entity.
For example: specific person, specific company, event, a particular plant etc. The entities have
attributes, for example people have names and addresses.
Entity Set:
An entity set is a set of entities of the same type that share the same properties or attributes. For
example: set of all persons who are customers at a particular Bank can be defined as the entity
set customer.
Eg:
Customer
Customer_id Customer_name Customer_street Customer_city
1 Bhupi Chandani Kanchanpur
2 Arjun Balkhu Kathmandu Entity set
3 Abin Pulchoak Lalitpur
Entity
19
By: Abhimanu Yadav
Attributes:
The properties or characteristics of an entity are called attributes. For example, a customer
entity can have customer-id, customer-name, customer-street, and customer-city as attributes.
Name Address
Code
Customer
Attribute Types
An Attribute, as used in E-R model, can be characterized by the following attributes types:
Simple and composite attribute:
Simple: The attributes that cannot be divided into subparts (ie. Into attributes) are
called simple attributes. For example roll-number attribute of a student cannot be
further divided into sub parts thus roll-number attribute of a student entity acts as a
simple attribute.
Composite: The attributes that can be divided into subparts (ie into attributes) are
called composite attributes. For example name attribute of a particular student can be
further vided into subparts first-name, middle-name, and last-name thus name
attribute acts as a composite
.
First-name middle-name last-name
City
State
Name Roll-No
Address Street
Student
20
By: Abhimanu Yadav
Multi-valued: If an attribute has a set of value for a specific entity is called multi-valued
attributes. For example: multi-valued attribute: ‘phone_number’ of an employee may have
zero, one or several phone numbers.
;[ Phone_No
Name
Code
Customer
Derived attributes:
The attribute whose value derived from the values of other related attributes or entities is
called derived attribute. For example: age, given date_of_birth.
Name Address
Date-of-birth
Customer
Age
Note: All attributes take a null value when an entity does not have a value for it. The null
value may indicate “not applicable”, that is, the value does not exist for the entity.
21
By: Abhimanu Yadav
T-Name
T-address S-Name Roll-No
Address
Salary
A relationship set may also have attributes called descriptive attributes. For example, the teach
relationship set between entity sets teacher and students may have the attribute teaches-date.
Teacher Teaches Students
Arjun
R-11
F 2070-01-01
Bhupendra
2070-01-04 R-33
2069-09-22
Deepak
R-45
2070-01-22
Dilli 2070-02-02
R-121
2069-05-23
Kumar
R-42
22
By: Abhimanu Yadav
Degree of a relationship:
Degree of a relationship set refers to the number of entity sets that participate in a relationship
set. Relationship sets that involve two entity sets are called binary relationship sets. Most
relationship sets in a database system are binary.
Relationship sets may involve more than two entity sets called n-ary relationship sets but
are rarer. For example, suppose employees of a bank may have jobs (responsibilities) at multiple
branches, with different jobs at different branches. Then there is a ternary relationship set
between entity sets employee, job and branch.
When the entity sets of a relationship set are not distinct (ie. The same entity set participates in a
relationship set more than once, in different roles). This type of relationship set is sometimes
called a recursive relationship set.
Constraints:
An entity relationship model may define certain constraints to which the contents of a database
must conform. The most important constraints are: mapping cardinalities and participation
constraints.
1. Mapping Cardinality Constraints:
Mapping cardinality or cardinality ratio express the number of entities to which another entity
can be associated via a relationship set. The mapping cardinality is most useful in describing
binary relationship sets. (mapping cardinality also used for other relationship that is ternary etc.)
For a binary relationship set the mapping cardinality must be one of the following types:
One-to- one
One-to- many
Many-to-one
Many-to-many
23
By: Abhimanu Yadav
One-to-One:
An entity in A is associated with at most one entity in B, and an entity in B is associated with at
most one entity in A. The following fig shows one to one mapping cardinality of entity sets A
and B.
Pawan R-22
Raju R-53
Susma R-92
Fig: One-to-One
One-to-Many:
An entity in A is associated with any number (zero or more) of entities in B. An entity in B
however can be associated with at most one entity in A. The following fig shows one-to-many
mapping cardinality of entity sets A and B.
Person Phone No
9841144856
Pawan
9803348976
9851663244
Susma
014330227
Fig: One-to-Many
Many-to-One:
An entity in A is associated with at most one entity in B. An entity in B, however, can be
associated with any number ( zero or more) of entities in A. The following fig clearly shows the
many to one cardinality between entity sets A and B.
24
By: Abhimanu Yadav
Son Father
Fig: Many-to-One
Many-to-Many:
An entity in A is associated with any number (zero or more) of entities in B, and an entity in B is
associated with any number (zero or more) of entities in A. The following fig clearly shows the
many-to-many cardinality between entity sets A and B.
Fig: Many-to-Many
2. Participation Constraints:
The participation constraint specifies whether the existence of an entity depends on its being
related to another entity via the relationship type.
There are two types of participation constraints:
I. Total Participation Constraints
II. Partial Participation Constraints
25
By: Abhimanu Yadav
customer must have an account. Then there is total participation of entity set account in the
relationship set depositor.
Note: Double lines are used to indicate that the participation of an entity set in a
relationship set is total. And single lines are used to indicate that the participation of an
entity set in a relationship set is partial.
Keys:
Keys are used to distinguish the entities within a given entity set. Keys also help to uniquely
identify relationships.
There are different types of keys which are as
Super key
Candidate key
Primary key
Foreign key
Super Key:
A super key of an entity set is a set of one or more attributes whose values uniquely determine
each entity in the entity set. If K is a super key and any superset of K is also super key, thus the
concept of superset is not sufficient for our purpose.
For example Roll-No attribute of the entity set student is sufficient to distinguish one student
entity from another. Thus the Roll-No is a super key. Similarly the combination of Roll-No and
Name is a super key of the entity set student.
Candidate Key:
A candidate key of an entity set is a minimal super key. That is a super key which does not
have any proper subset is called candidate key. For example customer-id is candidate key of
26
By: Abhimanu Yadav
Note: Any candidate keys other than the one chosen as a primary key is known as alternate key.
Primary key:
A primary key is a candidate key that is chosen by the database designer as the principle
means of uniquely identifying entities within an entity set. There may exist several candidate
keys, one of the candidate keys is selected to be the primary key.
Any two individual entities in the set are prohibited from having the same value on the key
attributes at the same time ( i. e values of key attributes must be unique)
For examples- the candidate key { RollNumber} can be considered to be a primary key for the
entity set student. The candidate key {Customer-id} can be considered to be a primary key of
customer entity set.
Note: If a primary key contains more than one attribute then it is called composite Key
Foreign key:
A foreign key (FK) is an attribute or combination of attributes that is used to establish and
enforce a link between the data in two tables. You can create a foreign key by defining a
FOREIGN KEY constraint when you create or modify a table.
In a foreign key reference, a link is created between two tables when the column or columns that
hold the primary key value for one table are referenced by the column or columns in another
table. This column becomes a foreign key in the second table.
Student
S-ID Name Address Course-ID
S-12 Pawan Joshi C002 Foreign Keys
S-14 Yamman Karki C021
S-51 Abin Saud C321
S-11 Binak Singh C112 Course
Course-ID Course-Name
Relationships S-12 C++
S-14 DBMS
S-51 Account
S-11 Banking
Primary Keys
Fig: Primary key and foreign key
Note: A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
27
By: Abhimanu Yadav
Example: E-R diagram for hospital with a set of patients and medical doctors.
First
Middle
P-No
P-Age P-Name Last
D-Name
Specialization
Phone-No
Patient
Treats
Doctors
Admit- H-Name
H-Address D-ID
in
have
Hospital
28
By: Abhimanu Yadav
An entity type may have additional meaningful sub-groupings of its entities. Example:
EMPLOYEE may be further grouped into {SECRETARY, ENGINEER, TECHNICIAN,
MANAGER, MANAGER, SALARIED_EMPLOYEE, HOURLY_EMPLOYEE …}
EER diagrams extend ER diagrams to represent these additional sub-groupings, called
subclasses or subtypes. Each of these subgroups is called a subclass of the EMPLOYEE
entity type.
The EMPLOYEE entity type is called the superclass of each of these subclasses.
The relationship between a superclass and any one of its subclasses is called a
superclass/subclass or class/subclass or IS-A (IS-AN) relationship (e.g. EMPLOYEE/
SECRETARY EMPLOYEE/MANAGER).
Subclass entities have their own specific attributes. They also inherit all attributes and
relationships of its superclass (subclasses can be considered as separate entity types).
Ss superclass: EMPLOYEE
Susubclasses: SECRETARY, ENGINEER,
TECHNICIAN,
SALARIED_EMPLOYEE,
HOURLY_EMPLOYEE
29
By: Abhimanu Yadav
Specialization:
The process of defining a set of subclasses from a superclass is known as specialization.
The set of subclasses is based upon some distinguishing characteristics of the entities in the
superclass. It is a top-down design process.
Example: {SECRETARY, ENGINEER, TECHNICIAN} is a specialization of EMPLOYEE
based upon job type.
Note: There may have several specializations of the same superclass.
Generalization:
It is a bottom-up design process. Here, we combine a number of entity sets that share the
same features into a higher-level entity set. The original classes become the subclass of the
newly formed generalized superclass. The reason, a designer applies generalization is to
emphasize the similarities among the entity sets and hide their differences. Specialization and
generalization are simple inversions of each other; they are represented in an E-R diagram in the
same way. The terms specialization and generalization are used interchangeably.
Person
ISA Credit-rating
Salary
Employee Customer
30
By: Abhimanu Yadav
Note:
In EER disjoint-constraint is illustrated by placing the letter d inside the circle
In case overlap between subclasses is allowed, we place the letter o inside the circle.
Disjointness/Overlapping Constraints:
It specifies that the subclasses of the specialization must be disjoint. Here an entity can be
a member of at most one of the subclasses of the specialization and it is represented by d in EER
diagram.
If not disjoint, specialization is overlapping. That is the same entity may be a member of more
than one subclass of the specialization and it is represented by o in EER diagram.
Completeness Constraint:
Total participation constraint specifies that every entity in the superclass must be a
member of some subclass in the specialization/generalization. It is represented by double line in
EER diagram.
Partial participation constraint allows an entity not to belong to any of the subclasses and
shown in EER diagrams by a single line.
Aggregation:
One of the limitations of E-R model is that it cannot express relationship among
relationships. One of the solutions in such a situation is using aggregation. Aggregation is an
abstraction in which relationship sets (along with their associated entity sets) are treated as
higher-level entity sets and can participate in relationships.
31
By: Abhimanu Yadav
The tabular representation of the entity set loan of the given E-R diagram, This entity has two
attributes loan-number and amount. We represent this entity set by a table called loan, with two
columns named loan-number and amount as below:
Loan
32
By: Abhimanu Yadav
The table of entity ‘payment’ consist the column names loan-number, payment-number,
payment-data, and payment-amount as below:
Payment
Loan-No Payment-No Payment-Date Payment-amount
L-11 L-11 2069-02-22 50,000
L-22 L-22 2069-04-28 70,000
L-07 L-07 2069-01-19 45,000
L-32 L-32 2070-02-02 98,000
Borrower
Customer-id Loan-number
019-29-3746 L-11
019-28-3123 L-17
019-24-3144 L-76
33
By: Abhimanu Yadav
34
By: Abhimanu Yadav
35
By: Abhimanu Yadav
Example 3: Construct an E-R diagram for a hospital with a set of patients and a set of medical
doctors. Associate with each patient a log of the various tests and examinations conducted.
Or
patients (patient-id, name, insurance, date-admitted, date-checked-out)
doctors (doctor-id, name, specialization)
test (testid, testname, date, time, result)
doctor-patient (patient-id, doctor-id)
test-log (testid, patient-id) performed-by (testid, doctor-id)
Example 4 Construct an E-R diagram for a car-insurance company whose customers own one or
more cars each. Each car has associated with it zero to any number of recorded accidents.
36
By: Abhimanu Yadav
37
By: Abhimanu Yadav
Query languages:
A query language is a language in which a user requests information from the database.
Query languages can be categorized as either procedural or non-procedural. In a procedural
language the user instructs the system to perform a sequence of operations on the database to
compute the desired result. Example: Relational algebra.
In a non-procedural language, the user describes the desired information desired without
giving a specific procedure for obtaining that information. Example: tuple relational calculus,
domain relational calculus, SQL etc.
1. Fundamental operations:
38
By: Abhimanu Yadav
Select only those Employees with first name Solu who are associate professors:
Name = 'Solu' ˄ Rank = 'Assistant' (Employee)
Result:
Name Office Dept Rank
Solu 400 Finance Associate
Select only those Employees who are either Assistant Professors or in the Economics
department:
Result:
Name Office Dept Rank
Bipin 400 Computer Assistant
Rahul 160 Economics Assistant
Niky 220 Economics Adjunct
Select only those Employees who are not in the Computer department or Adjuncts:
(Rank = ‘Adjunct’ ˄ Dept = 'Computer') (Employee)
39
By: Abhimanu Yadav
Result:
Name Office Dept Rank
Rahul 160 Economics Assistant
Solu 500 Finance Associate
Exercises
Evaluate the following expressions:
1. (Rank = 'Adjunct' ˄Dept = 'Computer') (Employee)
2. Rank = 'Associate' ( Dept = 'Computer' (Employee ) )
3. Dept = 'Computer' ( Rank = 'Associate' Employee )
4. Rank = 'Associate' ˄Dept = 'Computer' (Employee)
5. Age > 26 (R U S)
1.2 Project operation:
Projection operation is used to extracts specified columns (arity) of a relation. With the help of
this operation, any number of columns can be omitted from a table or columns of table can
rearrange.
Syntax: - π<attribute-list> (Relation)
Projection Examples:
Assume the same Employee relation above is used.
Project only the names and departments of the employees:
π name, dept (Employee)
Results:
Name Dept
Bipin Computer
Niky Economics
Rahul Economics
Binita Computer
Solu Finance
40
By: Abhimanu Yadav
Show the name and rank of those Employees who are not in the ‘Computer’ department
or Adjuncts:
π name, rank ( (Rank = 'Adjunct' Dept = 'Computer') (Employee) )
Result:
Name Rank
Rahul Assistant
Solu Associate
Exercises
Evaluate the following expressions:
1. π name, rank ( (Rank = 'Adjunct' Dept = 'Computer') (Employee) )
2. π fname, age ( Age > 22 (R U S) )
41
By: Abhimanu Yadav
42
By: Abhimanu Yadav
2. Additional operations:
2.1 Set Intersection Operation ( ):
Set intersection is denoted by symbol and it returns a relation that contains tuples that are in
both of its argument relations.
Result: Relation with tuples that appear in both R and S.
R S
First Last Age
Maya singh 23
The Join operation is used to combine related tuples from two relations into single tuples.
Natural join operation ( ):
The natural join is a binary operation that allows us to combine certain selections and a
Cartesian product into one operation. It is denoted by the join symbol . The natural join
operation performs the Cartesian product of given relations together with remove the duplicate
attributes. The natural join thus performs a join by equating the attributes with the same name
and then eliminates the replicated attributes.
In brief the result of the natural join of two relations R and S is the set of all combinations of
tuples in R and S that are equal on their common attribute names.
43
By: Abhimanu Yadav
44
By: Abhimanu Yadav
Account
Account-number branch-name Balance
A-101 Newroad-branch 50000
A-102 Kirtipur-branch 60000
A-201 Balkhu-branch 90000
A-206 Pokhara-branch 20000
A-301 Kalanki-branch 12000
A-401 Banepa-branch 22000
A-503 Dodhara-branch 41000
45
By: Abhimanu Yadav
Suppose we want to find all the customers who have an account at all branches located in
Kathmandu.
Strategy: think of it as three steps.
We can obtain the names of all branches located in Kathmandu by
r1= bname( bcity=”Kathmandu” (branch))
branch-name
Newroad-branch
Kalanki-branch
Balkhu-ranch
We can also find all cname, bname pairs for which the customer has an account by
r2=cname, bname(depositor account)
customer-name branch-name
Pukar Newroad-branch
Shikha Kirtipur-branch
Anisha Balkhu-branch
Now we need to find all customers who have an account at all branches located in Kathmandu.
The divide operation provides exactly those customers:
cname, bname(depositor account) bname( bcity=”Kathmandu” (branch))
customer-name
Pukar
Shikha
Anisha
46
By: Abhimanu Yadav
47
By: Abhimanu Yadav
Problem: “Suppose we want to find the total salary of all the full time employees in branch
wise”
branch-name 𝒢sum(salary) (Fulltime-works)
The result of aggregate function with grouping specified above will be:
branch-name sum of salary
Patan-branch 55000
Tokha-branch 20000
Palpa-branch 40000
48
By: Abhimanu Yadav
Results: MIN(salary)
20000
Results: COUNT(employee-name)
2
Database Manipulation:
Until now we only did the extraction of information from the database. In this section we will
perform some modification on the database. We will namely use three types of operations for the
modification of the database; they are insertion, deletion and modification.
All these operations can be expressed using the assignment operator.
Insertion operation:
To insert data into a relation, we specify a tuple to be inserted.
Syntax: RR U E
Where R is a relation and E is a relational algebra expression.
Example: suppose we have a relation employee
Employee (Name, Salary, Address)
Suppose we wish to insert an employee “Bhupi” of salary 50,000 and live in Kathmandu then we
write,
EmployeeEmployee U {“Bhupi”, 50000, Kathmandu}
Deletion operation:
We can remove the selected tuples from the database. We cannot delete values of only
particular attributes.
Syntax: RR E -
Where R is a relation and E is a relational algebra expression.
Example: Delete all of Anju information from Employee relation
Employee
e-id e-name Salary Employee Employee - e-name=”Anju” (Employee)
11 Bhupi 3000
13 Anju 4000 Result:
43 Manju 5000 Employee
54 Nisha 6000 e-id e-name Salary
33 Anju 3400 11 Bhupi 3000
43 Manju 5000
54 Nisha 6000
49
By: Abhimanu Yadav
Updating Operation:
In some situation we may wish to change a value in tuple without changing all values in the
tuple. We can use the generalized-projection operator to do this task.
Syntax: <A1, A2,…..An> (Relation)
Where {A1, A2,........,An} are attributes.
Example: All employees working in department “Computer” has increased their salary by 15%.
Employee
e-id e-name department salary
11 Bhupi Computer 3000
13 Anju Math 4000
43 Manju Physics 5000
54 Nisha Computer 6000
33 Anisha Math 6400
Employee(e-id, e-name, department, salary + salary*0.15 (department=”Computer” (Employee)) U
e-id, e-name, department, salary (department ≠”Computer” (Employee)))
Result: Employee
e-id e-name department salary
11 Bhupi Computer 3450
13 Anju Math 4000
43 Manju Physics 5000
54 Nisha Computer 6900
33 Anisha Math 6400
50
By: Abhimanu Yadav
2. Find the names and cities of residence of all employees who work for “NIBL Bank”.
person-name, city (company-name=”NIBL Bank” (employee works))
3. Find the names, street address, and cities of residence of all employees who works for
“Software Company” and earn more than 50000 per month.
person-name, street, city (company-name=”Software company” ˄ salary > 50000(employee works))
4. Find the name of all employees in the database who live in the same city as the company for
which they work.
person-name (employee works company))
5. Find the name of all employees in the database who do not work for “SBI Bank”.
person-name (company-name ≠ ”SBI Bank”( works))
6. Find the names of all employees who earn more than every employee of “SBI bank”.
Temp 𝒢max(salary) (company-name=”SBI Bank” (works))
person-name (salary > Temp (works))
7. Assume the company may be located in several cities. Find all companies located in every city
in which “SBI Bank” is located.
company-name, city (company) city (company-name =”SBI Bank”(company))
9. Delete all tuples in the employee relation where employee’s city is “Kathmandu”.
employee employee - (city=”Kathmandu” (employee))
51
By: Abhimanu Yadav
52
By: Abhimanu Yadav
Introduction:
SQL is a computer language for organizing, managing, and retrieving data stored by a computer
database. In fact, SQL works with one specific type of database, called a relational database.
The name "SQL" is the short form for Structured Query Language.
SQL is used to control all of the functions that a DBMS provides for its users, including:
1. Data definition: SQL lets a user define the structure and organization of the stored data
and relationships among the stored data items.
2. Data retrieval: SQL allows a user or an application program to retrieve stored data from
the database and use it.
3. Data manipulation: SQL allows a user or an application program to update the database
by adding new data, removing old data, and modifying previously stored data.
4. Access control: SQL can be used to restrict a user's ability to retrieve, add, and modify
data, protecting stored data against unauthorized access.
5. Data sharing: SQL is used to coordinate data sharing by concurrent users, ensuring that
they do not interfere with one another.
6. Data integrity: SQL defines integrity constraints in the database, protecting it from
corruption due to inconsistent updates or system failures.
53
By: Abhimanu Yadav
The DDL part of SQL permits database tables to be created or deleted. It also defines indexes
(keys), specify links between tables, and impose constraints between tables.
The most important DDL statements in SQL are:
CREATE DATABASE- creates a new database
ALTER DATABASE- modifies a database
CREATE TABLE- creates a new table
ALTER TABLE- modifies a table
DROP TABLE- deletes a table
CREATE INDEX- creates an index (search key)
DROP INDEX- deletes an index
Basic structure:
The basic structure of an SQL expression consists of three clauses: SELECT, FROM
and WHERE.
The SELECT clause corresponds to the projection operation of relational algebra. It is
used to list the attributes desired in the result of a query.
The FROM clause corresponds to the Cartesian product operation of relational algebra. It
is used to list the relations to be used in the evaluation of the expression.
The WHERE clause corresponds to the selection predicate of relational algebra. It
consists of a predicate in the attributes of the relations that appear in the FROM clause.
A typical SQL query has the form
SELECT A1, A2, …..,An
FROM R1, R2, …… ,Rn
WHERE P
Where each Ai represents an attribute, each Ri is a relation and P is a predicate.
Its equivalent relational algebra expression is:
A1, A2, …..,An (p (R1 X R2 X ……X Rn))
54
By: Abhimanu Yadav
SELECT * Example
Now we want to select all the columns from the “Sailors " table. We use the following SELECT
statement:
SELECT * FROM Sailors
Tip: The asterisk (*) is a quick way of selecting all columns!
The result-set will look like this:
Sid sname Rating age
1 Ajaya 12 33
2 Robin 11 43
3 Ganga 32 28
4 Manoj 9 31
7 Rahul 7 22
9 Sanjaya 9 42
11 Raju 4 19
55
By: Abhimanu Yadav
56
By: Abhimanu Yadav
FROM Sailors
WHERE sname='Ajaya';
This is wrong: SELECT *
FROM Sailors
WHERE sname=Ajaya;
57
By: Abhimanu Yadav
OR Operator Example:
Now we want to select only the Sailors with the first name equal to "Rahul" OR the rating equal
to 9: We use the following SELECT statement:
SELECT *
FROM Sailors
WHERE sname='Rahul' OR rating=9;
The result-set will look like this:
sid Sname Rating Age
4 Manoj 9 31
7 Rahul 7 22
9 Sanjaya 9 42
SELECT *
FROM Sailors
WHERE rating=9 AND (age=31 OR age=42)
The result-set will look like this:
sid Sname Rating Age
4 Manoj 9 31
9 Sanjaya 9 42
58
By: Abhimanu Yadav
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC | DESC
ORDER BY Example:
Now we want to select all the Sailors from the table above, however, we want to sort the
Sailors by their name. We use the following SELECT statement:
SELECT *
FROM Sailors
ORDER BY sname;
The result-set will look like this:
Sid Sname Rating Age
1 Ajaya 12 33
3 Ganga 32 28
4 Manoj 9 31
7 Rahul 7 22
11 Raju 4 19
2 Robin 11 43
9 Sanjaya 9 42
59
By: Abhimanu Yadav
SELECT *
FROM Sailors
WHERE age BETWEEN 20 AND 40;
The result-set will look like this:
Sid Sname Rating Age
7 Rahul 7 22
4 Manoj 9 31
3 Ganga 32 28
1 Ajaya 12 33
NOT BETWEEN Operator Example:
To display the Sailors outside the range of the previous example, use NOT BETWEEN:
SELECT *
FROM Sailors
WHERE age NOT BETWEEN 20 AND 40;
The result-set will look like this:
Sid Sname Rating Age
9 Sanjaya 9 42
2 Robin 11 43
11 Raju 4 19
SQL IN Operator:
The IN operator allows us to specify multiple values in a WHERE clause.
SQL IN Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2...);
IN Operator Example:
The following SQL statement selects all Sailors with a rating of 9 or 11:
SELECT *
FROM Sailors Its equivalent query by using OR
WHERE Rating IN (9, 11); operator is as below:
The result-set will look like this:
SELECT *
Sid sname Rating Age FROM Sailors
2 Robin 11 43 WHERE Rating=9 OR Rating=11;
4 Manoj 9 31
9 Sanjaya 9 42
60
By: Abhimanu Yadav
String operations:
SQL specifies strings by enclosing them in single quotes, for example ‘Pokhara’. The most
commonly used operation on strings is pattern matching. It uses the operator LIKE. We describe
the patterns by using two special characters:
Percent (%): The % character matches any substring, even the empty string.
Underscore ( _ ): The underscore stands for exactly one character. It matches any
character.
Example:
SELECT *
FROM Sailors
WHERE sname LIKE ‘%ya’;
This SQL statement will match any Sailors first names that end with ‘ya’.
The result-set will look like this:
Set Operations:
Some time it is useful to combine query results from two or more queries into a single result.
SQL supports three set operators which are:
SQL Union
SQL Intersection and
SQL Except (Minus)
These operators have the pattern:
<query1> <set operator> <query2>
61
By: Abhimanu Yadav
INTERSECT Operation:
The SQL INTERSECT operator takes the results of two queries and returns only rows that
appear in both result sets. The INTERSECT operator removes duplicate rows from the final
result set. The INTERSECT ALL operator does not remove duplicate rows from the final result
set.
62
By: Abhimanu Yadav
Example: Find the names of sailors who have reserved a red and a green boat.
SELECT S.sname
FROM Sailors S, Reserves R1, Boats B1, Reserves R2, Boats B2
WHERE S.sid = R1.sid AND R1.bid = B1.bid AND S.sid = R2.sid AND R2.bid = B2.bid
AND B.color = `red' AND B.color = `green';
This query is difficult to understand (and also quite inefficient to execute, as it turns out). A
better solution for this query is to use INTERSECT as follows:
The result-set will look like this:
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = `red'
INTERSECT
SELECT S2.sname
FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color = `green';
The result-set will look like this:
Sname
Ajaya
Except Operation:
The SQL EXCEPT operator takes the distinct rows of one query and returns the rows that do not
appear in a second result set.
Example: Find the names of sailors who have reserved a red boats but not a green boat.
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = `red'
EXCEPT
SELECT S2.sname
FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color = `green'
The EXCEPT operation automatically eliminate duplicates. If we want to retain all duplicates,
we must write EXCEPT ALL in place of EXCEPT.
Example 6: Find the names of sailors who are older than the oldest sailor with a rating of 9.
SELECT S.sname
FROM Sailors S
WHERE S.age > (SELECT MAX (S2.age)
FROM Sailors S2
WHERE S2.rating =9);
The result-set will look like this: Sname
Robin
64
By: Abhimanu Yadav
UNION
SELECT S1.sname
FROM Sailors S1
WHERE S1.age=(SELECT min(age) FROM Sailors);
The result-set will look like this:
Sname
Robin
Raju
GROUP BY Clause:
The SQL GROUP BY clause is use to divide the rows in a table into groups. The GROUP BY
statement is used along with the SQL aggregate functions. In GROUP BY clause, the tuples with
same values are placed in one group.
Example: Find the age of the youngest sailor for each rating level.
SELECT rating, MIN(age)
FROM Sailors
GROUP BY rating;
The result-set will look like this: Rating Min(age)
4 19
7 22
9 31
11 43
12 33
32 28
This table display the minimum age of each group according to their rating.
SQL HAVING Clause:
The SQL HAVING clause allows us to specify conditions on the rows for each group. It is used
instead of the WHERE clause when Aggregate Functions are used. HAVING clause should
follow the GROUP BY clause if we are using it.
Example: let’s take an instance S3 of Sailors,
S3
Sid sname Rating age
1 Ajaya 12 33
2 Robin 11 43
3 Ganga 32 28
4 Manoj 9 31
7 Rahul 7 22
9 Sanjaya 9 42
11 Raju 4 19
22 Robin 11 54
32 Anish 7 21
Example: Find the age of the youngest sailor who is eligible to vote (i.e., is at least 18 years
old) for each rating level with at least two such sailors.
65
By: Abhimanu Yadav
NULL Values:
SQL allows the use of NULL values to indicate absence of information about the value of an
attribute. It has a special meaning in the database- the value of the column is not currently known
but its value may be known at a later time.
A special comparison operator IS NULL is used to test a column value for NULL. It has
following general format:
Value1 IS [NOT] NULL;
This comparison operator return true if value contains NULL, otherwise return false. The
optional NOT reverses the result.
Following syntax is illegal in SQL:
WHERE attribute=NULL;
Example: let’s take an instance S4 of Sailors,
S4
sid sname Rating Age
1 Ajaya 12 33
2 Robin 11 43
3 Ganga 32 28
4 Manoj 9 31
7 Rahul 7 22
9 Sanjaya NULL NULL
11 Raju 4 19
22 Robin NULL NULL
32 Anish NULL NULL
Find all sailors that appear in S4 relation with NULL values for rating and age:
66
By: Abhimanu Yadav
SELECT sname
FROM S4
WHERE rating IS NULL AND age IS NULL;
The result-set will look like this: sname
Sanjaya
Robin
Anish
Nested Sub-queries:
A nested query is a query that has another query embedded within it; the embedded query is
called a sub-query. The result of sub query is used by the main query (outer query). We can place
the sub-query in a number of SQL clauses including:
The WHERE clause
The HAVING clause
The FROM clause
A common use of sub-queries is to perform tasks for set membership and make set comparison.
Set Membership:
The IN connective is used to test a set membership, where set is a collection of values produced
by SELECT clause in sub-query. The NOT IN connective is used to test for absence of set
membership.
Example1: Find the names of sailors who have reserved boat 41.
SELECT sname
FROM Sailors
WHERE sid IN ( SELECT sid
FROM Reserves
WHERE bid=41);
The result-set will look like this:
Sname
Ajaya
Raju
Example 2: Find the names of sailors who have reserved a red boat.
SELECT sname
FROM sailors
WHERE sid IN (SELECT sid
FROM Reservs
WHERE bid IN ( SELECT bid
FROM Boats
WHERE color=’Red’));
The result-set will look like this:
sname
Ajaya
Robin
Sanjaya
67
By: Abhimanu Yadav
Example 3: Find the names of sailors who have not reserved a red boat.
SELECT sname
FROM sailors
WHERE sid NOT IN (SELECT sid
FROM Reservs
WHERE bid IN ( SELECT bid
FROM Boats
WHERE color=’Red’));
The result-set will look like this:
Sname
Ganga
Manoj
Rahul
Raju
Set Comparison:
The comparison operators are used to compare sets in nested sub-query. SQL allows following
set comparisons:
< SOME, <= SOME, > SOME, >= SOME, = SOME, < > SOME
<ALL, <=ALL, >ALL, >=ALL, = ALL, < >ALL
The keyword ANY is synonymous to SOME in SQL.
Example 1: let’s take an instance S4 of Sailors as:
S4
Sid Sname Rating Age
1 Ajaya 12 33
2 Robin 11 43
3 Ganga 32 28
4 Manoj 9 31
7 Rahul 7 22
9 Sanjaya 9 42
11 Raju 4 19
8 Rahul 6 76
Find the id and names of sailors whose rating is better than some sailor called “Rahul”.
SELECT sid, sname
FROM S4
WHERE rating >ANY (SELECT rating
FROM S4
WHERE sname=’Rahul’);
The result-set will look like this:
Sid Sname
1 Ajaya
2 Robin
3 Ganga
4 Manoj
7 Rahul
9 Sanjaya
68
By: Abhimanu Yadav
Example 2: Find the id and names of sailors whose rating is better than every sailor called
“Rahul”.
SELECT sid, sname
FROM S4
WHERE rating >ALL (SELECT rating
FROM S4
WHERE sname=’Rahul’);
The result-set will look like this:
Sid Sname
1 Ajaya
2 Robin
3 Ganga
4 Manoj
9 Sanjaya
Example 3: Find the id and name of sailor with height rating.
SELECT sid, sname
FROM S4
WHERE rating >=ALL (SELECT rating
FROM S4);
The result-set will look like this:
Sid Sname
3 Ganga
Note: IN and NOT IN are equivalent to =ANY and < > respectively.
Views:
A database view is a logical table. It does not physically store data like tables but
represent data stored in underlying tables in different formats. A view does not require desk
space and we can use view in most places where a table can be used.
Since the views are derived from other tables thus when the data in its source tables are updated,
the view reflects the updates as well. They also can be used by DBA to enforce database
security.
Advantages of Views:
Database security: view allows users to access only those sections of database that
directly concerns them.
View provides data independence.
Easier querying
Shielding from change
Views provide group of users to access the data according to their criteria.
Vies allow the same data to be seen by different users in different ways at the same time.
69
By: Abhimanu Yadav
1.Insertion:
To insert data into a relation, we either specify a tuple to be inserted or write a query
whose result is a set of tuples to be inserted.
Example 1: suppose we need to insert a new record of Sailors of id is11, name is “Rahul”, rating
is 9 and of age is 29 then we write following SQL query,
INSERT INTO Sailors
VALUES (11,’Rahul’, 9, 29);
OR
INSERT INTO Sailors (sid, sname, rating, age)
VALUES (11,’Rahul’, 9, 29);
More generally, we might want to insert tuples on the basis of the result of query.
Example 2: suppose we have already some tuples on the relation ‘Sailores’. Suppose we need to
insert those tuples of sailors into their own relation whose rating is less than 7, this can be write
as,
INSERT INTO Sailors
SELECT *
FROM Sailors
70
By: Abhimanu Yadav
WHERE rating<7;
2. Deletion:
It is used to remove whole records or rows from the table.
Syntax:
DELETE FROM table_name
WHERE <predicate>
Example 1: suppose we need to remove all tuples of Sailors whose age is 32,
DELETE FROM Sailors
WHERE age=32;
Example 2: Remove all tuples of Sailors whose age is less than 30 and rating greater than 7,
DELETE FROM Sailors
WHERE age<32 AND rating>7;
3. Updates:
If we need to change a particular value in a tuple without changing all values in the tuple, then
for this purpose we use update operation.
Syntax:
UPDATE table_name
SET <column i> = <expression i>;
Example: suppose we need to increase the rating of those sailors whose age is greater than 40 by
20%, this can be write as,
UPDATE sailors
SET rating=rating + rating*0.2
WHERE age>40;
Joined relations:
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field
between them.
The types the different SQL JOINs are:
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
INNER JOIN:
It is most common type of join. An SQL INNER JOIN return all rows from multiple tables
where the join condition is met.
SQL INNER JOIN Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
71
By: Abhimanu Yadav
Example 1: Find the sailor id, boat id, boat name, boat color of those sailors who have
reserved a red boat.
SELECT sailors.sid, boats.bid, boats.bid, boats.bname, boats.color
FROM sailors INNER JOIN reserver INNER JOIN boats
WHERE sailors.sid=reserver.sid AND reserver.bid=boats.bid;
The result-set will look like this:
Example 2: Find the name and age of those sailors who have reserved a Marine boat.
SELECT sailors.sname, sailors.age
FROM sailors INNER JOIN reserver INNER JOIN boats
WHERE sailors.sid=reserver.sid AND reserver.bid=boats.bid;
The result-set will look like this:
CREATE DATABASE:
The CREATE DATABASE statement is used to create a database.
Syntax:
CREATE DATABASE dbname;
Example:
73
By: Abhimanu Yadav
ALTER DATABASE:
Allow us to modify existing database name.
Syntax:
CREATE TABLE:
Allow us to create a new table within given database.
Syntax:
CREATE TABLE <table_name>
(
<column1> <data type> [not null] [unique][<integrity constraint>],
<column2> <data type> [not null] [unique][<integrity constraint>],
……………….
………………
<column n> <data type> [not null] [unique][<integrity constraint>]
)
Note: [ ]: optional
Example:
CREATE TABLE Sailors
(
Sid INTEGER NOT NULL,
Sname VARCHAR(12),
Rating INTEGER,
Age INTEGER,
PRIMARY KEY (sid)
)
ALTER TABLE:
Allow us to modify a given table.
The structure of given table can be changed either of the following:
By adding new column in existing table
By deleting some columns from an existing table and
By modifying some columns of given table
A new column can be added to the table as follows:
Syntax:
ALTER TABLE <table name>
ADD (<column_name> <datatype>);
Example: suppose we want to add a new column ‘addresses’ to an existing table Sailors,
ALTER TABLE Sailors
74
By: Abhimanu Yadav
Example: suppose we want to remove an existing column ‘addresses’ from the table sailors as,
ALTER TABLE Sailors
DROP (addresses);
DROP TABLE
It allows us to remove an existing table from the database.
Syntax:
DROP TABLE <table name>
Example: if we want to remove a table ‘Sailors’ from the database my_db as,
DROP TABLE Sailors;
Embedded SQL:
The programming language in which SQL queries are embedded is called host language.
And the SQL structures permitted in the host language is called embedded SQL. They are
compiled by the embedded SQL processor.
Writing queries in SQL is usually much easier than coding same query in a programming
language. However, a programmer must access to a database from a general purpose
programming language for following two reasons:
Not all queries can be expressed in SQL
Non-declarative actions such as printing a report, interacting with user, or sending the
result of query to a graphical user interface etc. cannot be done from the SQL.
Dynamic SQL:
The dynamic SQL component of SQL allows programs to construct and submit SQL
queries at run time. In contrast, embedded SQL statements must be completely present at
compile time; they are compiled by the embedded SQL preprocessor.
75
By: Abhimanu Yadav
1. Find the names of all Juniors (Level = JR) who are enrolled in a class taught by I. Teach.
2. Find the age of the oldest student who is either a History major or is enrolled in a course
taught by I. Teach.
3. Find the names of all classes that either meet in room R128 or have five or more students
enrolled.
4. Find the names of all students who are enrolled in two classes that meet at the same
time.
5. Find the names of faculty members who teach in every room in which some class is
taught.
6. Find the names of faculty members for whom the combined enrollment of the courses
that they teach is less than _ve.
7. Print the Level and the average age of students for that Level, for each Level.
8. Print the Level and the average age of students for that Level, for all Levels except JR.
9. Find the names of students who are enrolled in the maximum number of classes.
10. Find the names of students who are not enrolled in any class.
76
By: Abhimanu Yadav
2. Write SQL DML statement to insert any five tuples ( Five records) in each relation(table)
3. Find the Books of Database System title and price above 500.
4. List the books published by TaTa McGraw Hill publication
5. Find the Name of the member who made reserve book in 12-10-2011
Exercise 5: Consider the following insurance database, where primary keys are underlined:
Teacher (Tid, Tname, Address, Age)
Student (Sid,Sname, Age, sex)
Takes (sid, course-id)
Course (course-id,course_name, text_book)
Teaches(Tid, Cousrse-id)
Taught-by{Sid, Tid}
Construct the following RA expressions for this relational database
a. Fine name, age and sex of all students who takes course “DBMS”
b. Find total number of students who are taught by the teacher “T01”
c. List all course names text books taught by teaher “T16”
d. Find average age of teachers for each course.
e. Insert the record of new teacher “T06” named “Bhupi” of age 27 into database
who lives in “Balkhu” and takes course “DBMS”
Exercise 6: Consider the following employee database, where primary keys are underlined.
employee (employee-name, street, city, salary)
works (employee-name, company-name,)
company (company-name, city)
manages (employee-name, manager-name)
Give an expression in SQL for each of the following queries.
a. Find the names of all employees who work for Second Bank Corporation.
b. Find the names, street and cities of residence of all employees whose salary is
more than average salary.
c. Find the names, street addresses, and cities of residence of all employees to
whom company is not assigned yet.
d. Find the names of all employees who work under the manager “Devi Prasad”.
e. Increase the salary of employees by 10% if their salary is less than 10,000 and
by 8% otherwise.
77
By: Abhimanu Yadav
Integrity constraints ensure that changes made to the database by authorized users do not result
in a loss of data consistency. Thus, integrity constraints guard against accidental damage to the
database.
E-R model ensure two types of integrity constraints:
– Key declaration: Primary and candidate
– Form of relationship: many to many, one to many, one to one
Types of constraints:
Domain constraint:
Domain is a pool of values of the same type from which one or more attributes in one or
more tables take their values.
D1 D2 Dn
Student
A1 A2 …………………. An
In the above student table, the attribute A1 draws value from domain D1, A2 from D2 and so on.
Domain integrity means the definition of a valid set of values for an attribute. You define
data type
Length or size
Is null value allowed
Is the value unique or not for an attribute.
Domain constraints are the most elementary form of integrity constraint. They are tested
essentially by the system whenever a new data item is entered into the database.
78
By: Abhimanu Yadav
The CREATE DOMAIN clause can be used to define new domains. For example, to ensure that
rating must be an integer in the range 1 to 10, we could use:
CREATE DOMAIN RATINGVAL INTEGER DEFAULT 0
CHECK (VALUE >= 1 AND VALUE <= 10)
Entity Integrity
The entity integrity constraint ensures that the primary key of a relation must be unique and not
null.
Example: Employee
cid Cname caddress cphone
1 Abin Kathmandu 9849248488
2 Anish Lalitpur 9849245544
? Binek Kirtipur 9813334849
79
By: Abhimanu Yadav
Thus for referential integrity a foreign key can have only two possible values- either the relevant
primary key or a null value. No other values are allowed.
CHECK Constraints:
CHECK constraints allow users to prohibit an operation on a table that would violate the
constraint. It is a local constraint.
Example: To ensure that rating must be an integer in the range 1 to 10, we could use:
Assertions:
Table constraints are associated with a single table, although the conditional expression in the
CHECK clause can refer to other tables. Table constraints are required to hold only if the
80
By: Abhimanu Yadav
associated table is nonempty. Thus, when a constraint involves two or more tables, the table
constraint mechanism is sometimes cumbersome and not quite what is desired. To cover such
situations, SQL supports the creation of assertions, which are constraints, not associated with
any one table.
Assertion in the SQL takes the form
CREATE ASSERTION <assertion_name> CHECK<predicate>
Example, suppose that we wish to enforce the constraint that the number of boats plus the
number of sailors should be less than 100.
CREATE ASSERTION SailorCheck
CHECK ((SELECT COUNT (S.sid) FROM Sailors S)
+ (SELECT COUNT (B.bid) FROM Boats B) < 100);
Trigger:
A trigger is a procedure (statement) that is automatically invoked by the DBMS in response to
specified changes to the database, and is typically specified by the DBA. A database that has a
set of associated triggers is called an active database. To design a trigger mechanism, we must
meet following three requirements:
1. Event: A change to the database that activates the trigger.
2. Condition: A query or test that is run when the trigger is activated.
3. Action: A procedure that is executed when the trigger is activated and its condition is true.
Need for Triggers:
Triggers are useful mechanisms for alerting humans or for starting certain tasks automatically
when certain conditions are met. As an illustration, suppose that, instead of allowing negative
account balances, the bank deals with overdrafts by setting the account balance to zero, and
creating a loan in the amount of the overdraft. The bank gives this loan a loan number identical
to the account number of the overdrawn account. For this example, the condition for executing
the trigger is an update to the account relation that results in a negative balance value. Suppose
that Jones’ withdrawal of some money from an account made the account balance negative. Let t
denote the account tuple with a negative balance value. The actions to be taken are:
81