DBMS Notes Unit-III - For Students
DBMS Notes Unit-III - For Students
T.E. Computer
Database Management Systems
Unit-III
By
Prof. Dr. K.P. Adhiya
SSBT’s COET, Bambhori-Jalgaon
Acknowledgment
1. Abraham Silberschatz, Henry F. Korth, S. Sudarshan, “Database System
Concepts”, 6th Edition, McGraw-Hill Hill Education.
2. Abraham Silberschatz, Henry F. Korth, S. Sudarshan, “Database System
Concepts”, 4th Edition, McGraw-Hill Hill Education.
3. Ramez Elmasri and Shamkant B. Navathe “Fundamentals of Database Systems”,
5th Edition, Pearson.
4. Express Learning, “Database Management Systems”, ITL Education Solutions
Limited.
5. Archana Verma, “Database Management Systems”, GenNext Publication.
6. Dr. Rajiv Chopra, “Database Management Systems (DBMS) – A Practical
Approach”, 5th Edition, S. Chand Technical
7. Tanmay Kasbe, “Database Management System Concepts – A Practical
Approach”, First Edition, Educreation Publishing.
8. Mahesh Mali, “Database Management Systems”, Edition 2019, TechKnowledge
Publications.
9. Rajendra Prasad Mahapatra, Govind Verma, “Database Management System”,
Khanna Publishing.
10. Malay K. Pakhira, “Database Management System”, Eastern Economy Edition,
PHI.
11. Sarika Gupta, Gaurav Gupta, “Database Management System”, Khanna Book
Publishing Edition.
12. Riktesh Srivastava, Rajita Srivastava, “Relational Database Management
System”, New Age International Publishers.
13. Peter Rob, Carlos Coronel, “Database System Concepts’, Cenage Learning, India
Edition
14. Bipin C. Desai, “An Introduction to Database Systems”, Galgotia Publications.
15. G.K. Gupta, “Database Management Systems”, McGraw Hill Education.
16. Shio Kumar Singh, “Database Systems – Concepts, Design and Applications”, 2nd
Edition, PEARSON.
17. S.D.Joshi, “Database Management System”, Tech-Max Publication.
18. R. Ramkrishnan , J. Gehrke, "Database Management Systems", 3rd Edition,
McGraw-Hill
19. C. J. Date, “Introduction to Database Management Systems”, 8th Edition, Pearson
20. Atul Kahate, “Introduction to Database Management System”, 3rd Edition,
Pearson.
21. Bharat Lohiya, “Database Systems”, Tenth Edition, Aditya Publication, Amravati.
22. Vijay Krishna Pallaw, “Database Management System”, 2nd, Asian Books Pvt.
Ltd.
23. Database Management Systems, Database Management Systems.
24. Mrs. Jyoti G. Mante (Khurpade), Mrs. Smita M. Dandge, “Database Mangement
System”, Nirali Prakashan.
25. Step by Step Database Systems (DBMS), Shiv Krupa Publications, Akola
26. Mrs. Sheetal Gujar –Takale, Mr. Sahil K. Shah, “Database Management System”,
Nirali Prakashan.
27. Mrs. Jyoti G. Mante (Khurpade), U.S. Shirshetti, M.V. Salvi, K.S. Sakure,
“Relational Database Management System”, Nirali Prakashan.
28. Seema Kedar, Rakesh Shirsath, “Database Management Systems”, Technical
Publications.
29. Pankaj B. Brahmankar, “Database Management Systems”, Tech-Max
Publications, Pune.
30. Imran Saeed, Tasleem Mustafa, Tariq Mahmood, Ahsan Raza Sattar, “A
Fundamental Study of Database Management Systems”, 3rd Edition, IT Series
Publication.
31. Database Management Systems Lecture Notes, Malla Reddy College of
Engineering and Technology, Secunderabad.
32. Dr. Satinder Bal Gupta, Aditya Mittal, “Introduction to Database Management
System, University Science Press.
33. E-Notes BCS 41/ BCA 41 on “Database Management System”, Thiruvalluvar
University.
34. Bighnaraj Naik, Digital Notes on “Relational Database Management System”,
VSSUT, Burla.
35. Viren Sir, Relational database Management System”, Adarsh Institute of
Technolgoyt (Poly), VITA.
36. Sitansu S. Mitra, “Principles of Relational Database Systems”, Prentice Hall.
37. Neeraj Sharma, Liviu Perniu, Raul F. Chong, Abhishek Iyer, Chaitali Nandan,
Adi-Cristina Mitea, Mallarswami Nonvinkere, Mirela Danubianu, “Database
Fundamentals”, First Edition, DB2 On Campus Book Series.
38. Database Management System, Vidyavahini First Grade College, Tumkur.
39. Bhavna Sangamnerkar, Revised by: Shiv Kishor Sharma, “Database Management
System”, Think Tanks Biyani Group of Colleges.
40. Tibor Radvanyi, “Database Management Systems”.
41. Ramon A. Mata-Toledo, Pauline K. Cushman, “Fundamentals of Relational
Databases”, Schaum’s Outlies.
Acknowledgment
Web Resources
https://www.sqlshack.com/sql-union-vs-union-all-in-sql-server/
https://www.sqltutorial.org/sql-intersect/
https://gokhanatil.com/2010/10/minus-and-intersect-in-mysql.html
https://www.sqltutorial.org/sql-minus/
https://www.w3schools.com/sql/sql_in.asp
https://www.geeksforgeeks.org/
https://www.w3resource.com/sql/joins/natural-join.php
https://www.guru99.com/joins-sql-left-right.html
https://www.w3schools.com/sql/sql_join.asp
https://www.guru99.com/joins-sql-left-right.html
http://www.sql-join.com/
https://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/
https://www.tutorialspoint.com/sql/sql-using-joins.htm
https://www.tutorialspoint.com/difference-between-views-and-materialized-views-in-sql
https://tutorialink.com/dbms/procedures-and-functions.dbms
https://docs.oracle.com/cd/E19078-01/mysql/mysql-refman-5.0/stored-programs-views.html
https://www.mysqltutorial.org/mysql-stored-procedure/mysql-while-loop/
https://www.mysqltutorial.org/mysql-if-statement
https://www.javatpoint.com/mysql-trigger
https://www.javatpoint.com/mysql-trigger
https://www.w3resource.com/mysql/mysql-triggers.php
https://link.springer.com/content/pdf/bbm%3A978-1-4302-0867-9%2F1.pdf
https://www.w3resource.com/sql/sql-basic/codd-12-rule-relation.php
Unit-III
(Introduction to the Relational Model)
Structure of Relational Databases
Nowadays, the relational model is the primary data model for
commercial processing applications, because of its simplicity, which
eases job of the programmer.
A relational database consists of a collection of tables. Each table is
assigned with a unique name.
Table is also called as relation. (In E-R terminology, it is entity).
For example, consider the instructor table, shown in figure 3.1. It
stores the information of various instructors.
Figure 3.2 shows the course table. It stores information such as-
course_id, title, dept_name and credit.
course_id prereq_id
IT-102 IT-101
Mech-102 Mech-101
Comp-103 Comp-102
ETC-103 ETC-102
Properties of relation:-
Generally, a relation has following properties-
o A relation is a table with columns and rows
o A relation has a name that is distinct from all other relation
names in the given database.
o Each cell of relation contains exactly one atomic (single) value.
o Each attribute has a distinct name.
o The values of an attribute are all from the same domain.
o Each tuple is distinct; i.e. there are no duplicate tuples.
o The order of attributes has no significance.
o The order of tuples has no significance, theoretically.
Database Schema
Database schema: - It is logical design of the database. The database
schema is the overall structure of the database, which specifies the
structure of each relation including its attributes (considering relational
model). It does not include the actual records of the relation.
Database instance: - It is a snapshot of the data in the database at a
given instant of time.
Relation schema: - It consists of list of attributes of the table. It
consists of relation name R and a set of attributes A1, A2, A3,…An. It is
represented by R (A1, A2,…An) and is used to describe a relation R.
Relation instance: - It is a snapshot of the data in a relation at a given
instant of time.
Consider the relation instructor from figure 3.1. The schema for this
relation is –
instructor (ID, name, dept_name, salary)
It can be also represented as –
instructor
ID name dept_name salary
Keys
There must be a way to specify how tuples within a given relations are
distinguished. This is expressed in terms of their attributes. No two tuples in
a relation are allowed to have exactly the same value for all attributes. There
are different types of keys –
Superkey :- A superkey is a set of one or more attributes that, taken
collectively, allow us to identify uniquely a tuple in the relation. For
example, the ID attribute of the relation instructor is sufficient to
distinguish one tuple from another. Thus, ID is a superkey.
The combination of ID and name is also a superkey for instructor
relation. But, the name attribute of instructor, is not a superkey, because
several instructors might have the same name.
Candidate key :- Generally all the attributes of a superkey are not
required to identify each tuple uniquely in a relation (i.e. a superkey may
contain extraneous attributes). Instead, only a subset of attributes of the
superkey is sufficient to uniquely identify each tuple. Such a minimal set
of attributes is a candidate key (also known as irreducible superkey).
Schema Diagrams
A database schema, along with primary key and foreign key
dependencies, can be shown by schema diagrams.
Some authors didn’t make any difference between the schema diagrams
and database schema.
Primary key attributes in a relation are underlined.
Foreign key dependencies appear as arrows from the foreign key
attributes of the referencing relation to the primary key of the
referenced relation.
Consider the College database schema as follow –
COURSE
C-ID C-Name
STUDENT
S-ID S-Name S-Address
STUDENT-PHONE
Stu-ID S-Phone
DEPARTMENT
D-ID D-NAME Prof-ID
PROFESSOR
P-ID P-Name Dept-ID P-Salary Head-ID
Figure 3.5
Note, in a relation STUDENT-PHONE, the combination of {Stu-ID,
S-Phone} is a primary key. (Note – Some SQL may not support the name
of attribute as Stu-ID, so use Stu_ID).
Foreign key Dept-ID of PROFESSOR table refers to the primary key
D-ID of DEPARTMENT table.
The schema diagram for above database schema can be as follow –
COURSE
C-ID C-Name
STUDENT
S-ID S-Name S-Address
STUDENT-PHONE
Stu-ID S-Phone
DEPARTMENT
D-ID D-NAME Prof-ID
PROFESSOR
P-ID P-Name Dept-ID P-Salary Head-ID
Figure 3.6
Codd’s Rules
Dr. Edgar F Codd formulated 13 rules including zero rule for relational
DBMS. Based on these rules, we can decide a DBMS to be an RDBMS
(Relational Database Management System) or not. The very limited number
of commercial product follows all rules. The Codd’s rules are stated as
follow:-
Rule Zero - Foundation Rule: - The system must qualify as
relational, as a database, and as a management system. The RDBMS
Unit-III
(Introduction to SQL)
Overview of the SQL Query language
SQL (Structured query Language) has established itself as the
standard relational database language.
It is a language that can be used for retrieval and management of data
stored in relational database.
It is a non-procedural language as it specifies what is to be retrieved
rather than how to retrieve it.
The SQL language has several parts:-
o Data-definition language (DDL). The DDL provides commands
for defining relation schemas, deleting relations, and modifying
relation schemas. E.g. Create table, Alter table, Drop table etc.
o Data-manipulation language (DML). The DML provides the
ability to query information from the database and to insert tuples,
delete tuples, modify tuples.
o Integrity. The DDL includes commands for specifying integrity
constraints that the data stored in the database must satisfy.
o View definition. The DDL includes commands for defining views.
o Transaction control. SQL includes commands for specifying the
beginning and ending of transactions.
o Embedded SQL and dynamic SQL. Embedded and dynamic
SQL define how SQL statements can be embedded within general-
purpose programming languages, such as C, C++, and Java.
o Authorization. The DDL includes commands for specifying
access rights to relations and views.
Features of SQL:-
o It is English like language. E.g. it uses words like select, insert,
delete etc.
o It is a non procedural language.
o SQL commands are not case sensitive.
delete command -
We can use the delete command to delete tuples (records) from a
relation. E.g. the command –
delete from student ;
This command will delete all tuples from the student relation.
name
Swapnil
Figure 3.13
o SQL allows the use of the logical connectives and, or, and not
in the where clause. The operands of the logical connectives can
be expressions involving the comparison operators <, <=, >,
>=, =, and <> (i.e. not equal to).
Old-name as new-name
The as clause can appear in both the select clause and from clause.
E.g. if we want attribute name dept_name to be replaced with the name
dname, we can write the query as –
select dept_name as dname from department_r;
Computer
ETC
IT
Computer
ETC
IT
String Operations
o SQL specifies strings by enclosing them in single quotes, for
example, ’Computer’. Some systems also allow double quotes.
o Some database systems distinguish the uppercase and lowercase
when matching the strings. But, some database systems such as
MySQL and SQL Server do not distinguish between uppercase
and lowercase.
o SQL also permits a variety of functions on character strings,
such as
Concatenating (using “_”)
extracting substrings,
finding the length of strings,
converting strings to uppercase using the function upper(s)
where s is a string.
converting to lowercase using the function lower(s),
removing spaces at the end of the string using trim(s) and so
on.
George
Krishna
George Computer
Krishna Computer
Uday IT
OR
select *
from instructor_r, department_r
where instructor_r.dept_name = department_r.dept_name
and department_r.building = ‘Building No. 1’;
name dept_name
George Computer
Uday IT
name dept_name
Krishna Computer
Set Operations
o The operations union, intersect, and except operate on relations.
o The union, intersect, and except: - correspond to mathematical set-
theory operations Ս, Ո, and ─.
o Assume we want to perform those operations on two queries – then
both the queries must be “union compatible”. It means that both
return the same number of columns, and that the corresponding
columns have same (compatible) data types.
The Union operation – say R1 Ս R2, then the result contains all
tuples (rows) from relation R1 and all rows from relation R2 and
duplicate rows are deleted. i.e. duplicate rows are put only once the
resultant relation.
o Consider the table of Figure 3.17:- instructor_r relation.
name
George
Krishna
Uday
Krishna
Uday
Swapnil
Soumitra
Null Values
o The null value is a special character value that signifies that the value
is unknown or does not exist.
o Null values present special problems in relational operations,
including arithmetic operations, comparison operations, and set
operations.
o The result of an arithmetic expression (involving, for example +, −, *,
or / ) is null, if any of the input values is null.
o Sometimes null values cannot be avoided.
E.g. consider the following relational schema:-
STUDENT-PHONE
Stu-ID S-Phone
Now here, the student may not have any phone number. So, he/she
will put a null value.
o Generally, database does not allow the primary key to contain null
values.
o Since the predicate in a where clause can involve Boolean operations
such as and, or, and not on the results of comparisons, the definitions
of the Boolean operations are extended to deal with the value
unknown.
and: The result of true and unknown is unknown, false
and unknown is false, while unknown and unknown is
unknown.
or: The result of true or unknown is true, false or
unknown is unknown, while unknown or unknown is
unknown.
not: The result of not unknown is unknown.
o SQL uses the special keyword null in a predicate to test for a null
value.
E.g. consider the following query –
select name
from instructor_r
where salary is null;
name
George
Krishna
Uday
Aggregate Functions
o Aggregate functions are functions that take a collection of values as
input, and return a single value. SQL offers five built-in aggregate
functions:
Average: avg
Minimum: min
Maximum: max
Total: sum
Count: count
Basic Aggregation
avg ( ) :-
o This avg ( ) function is used to calculate average of column values in
a table selected by the query.
o It returns the average of all the values in the specified column.
o E.g. consider the query – find out the average salary of instructor from
the table instructor_r.
select avg (salary)
from instructor_r;
count ( ) :-
o This function is used to calculate number of rows (tuples or records)
in a table selected by the query.
o Consider the query – find out the total number of instructors in the
table instructor.
select count (ID) as Total_Instructor
from instructor;
OR
select count (name) as Total_Instructor
from instructor;
OR
select count (*) as Total_Instructor
from instructor;
sum ( ) :-
o This function is used to calculate the sum of column values in a table
selected by the query.
o E.g. consider the query – find out total salary paid to all instructors,
from instructor table.
select sum(salary) as Total_Salary
from instructor;
min ( ) :-
o This function is used to find minimum value out of a column values in
a table selected by the query.
o E.g. consider the query – find out minimum salary paid to the
instructors, from instructor table.
select min(salary) as Min_Salary
from instructor;
max ( ) :-
o This function is used to find maximum value out of a column values
in a table selected by the query.
o E.g. consider the query – find out maximum salary paid to the
instructors, from instructor table.
select max(salary) as Max_Salary
from instructor;
Nested Subqueries
o A query within another query is called as subquery (or nested
query).
o It is normally a select statement inside select statement. It can be used
with INSERT, UPDATE and DELETE statements
o The subquery (i.e. inner query) executes before the main query. The
result of the inner query is used by the main query (i.e. outer query).
o A common use of subqueries is to perform tests for set membership,
make set comparisons, and determine set cardinality, by nesting
subqueries in the where clause.
o General Syntax :-
select select_list
from table
where Expr_Operator
(select select_list
from table);
o The various operators that can be used are :- <, >, <=, >=, < >, IN,
ANY, ALL, EXISTS etc.
o E.g. consider the query as – find out the instructors whose salary is
less than Uday’s salary.
select name, salary
from instructor
where salary <
(select salary
from instructor
where name = 'Uday');
Set Membership
o SQL allows testing tuples for membership in a relation.
o The IN operator is used for set membership. The set is a collection of
values produced by a select clause.
o The meaning of IN operator – Equal to any member in the list.
o The NOT IN operator tests for the absence of set membership.
o E.g. consider the query – find out the names of instructors (along with
their ID, their department and salary), who belong to Computer or IT
department.
The query can be given as follow –
select *
from instructor
where dept_name = 'computer' or dept_name ='IT';
Now other query can also be fired to get same output, using in
operator.
select *
from instructor
where dept_name in ('Computer', 'IT');
The output for both the queries will be same and follows-
ID name dept_name salary
100 George Computer 110000.000
101 Krishna Computer 95000.000
102 Uday IT 105000.000
110 Nilesh IT 70000.000
o This example shows that it is possible to write the same query several
ways in SQL. This flexibility is beneficial, since it allows a user to
think about the query in the way that seems most natural.
o Consider the query -- find out the names of instructors (along with
their ID, their department and salary), who don’t belong to Computer
or IT department.
select *
from instructor
where dept_name not in ('Computer', 'IT');
Set Comparison
o The ANY operator (or SOME operator) compares a value with any of
the values in a list or returned by the subquery. This operator returns a
false value if the subquery returns no tuple.
o E.g. The phrase “greater than at least one” is represented by >some or
>any.
o Consider the query – find out the names of all instructors whose salary
is greater than at least one instructor in the Electrical department.
select name from instructor
where salary >some
(select salary
from instructor
where dept_name='Electrical');
o The > some comparison in the where clause of the outer select is
true, if the salary of the tuple is greater than at least one member of
the set of all salary values for instructors in Electrical department.
o SQL also allows < some, <= some, >= some, = some, and <> some
comparisons.
o Now consider the query – find out the names of all instructors that
have a salary greater than that of each instructor in the Electrical
department. So we have to use “greater than all” construct. It is
represented by >all.
name
George
Swapnil
Soumitra
o SQL also allows < all, <= all, >= all, = all, and <> all comparisons.
and also consider the Figure 3.3:- The prereq relation as follow-
course_id prereq_id
IT-102 IT-101
Mech-102 Mech-101
Comp-103 Comp-102
ETC-103 ETC-102
Figure: The prereq relation
o Now consider the query as – find out the title of subject (course) and
the corresponding department name, if and only if the subject is
having any prerequisite subject.
o Now consider the query as – find out the title of subject (course) and
the corresponding department name, if and only if the subject belongs
to Electrical department and is having any prerequisite subject.
The query can be written as follow –
select title, dept_name
from course
where exists
(select *
from prereq
where course.course_id= ‘Elect%’);
o So, we can give the name to a relation resulted from the subquery,
and rename the attributes, using the as clause as shown below-
select dept_name, Average_Salary
from (select dept_name, avg(salary) as Average_Salary
from instructor
group by dept_name)
as dept_avg (dept_name, Average_Salary)
where Average_Salary > 100000;
Scalar Subqueries
select dept_name,
(select count(*)
from instructor
where department.dept_name = instructor.dept_name)
as Num_Of_Instructors
from department;
Insertion
o We have to see how to insert data into a relation.
o The simplest insert statement is a request to insert data into one tuple.
o The attribute values for inserted tuples must be members of the
corresponding attribute’s domain. Similarly, tuples inserted must
have the correct number of attributes.
o E.g. we have created a table instructor with following SQL
command:-
create table instructor
(ID int,
name varchar(25) not null,
dept_name varchar(15) not null,
salary numeric (10,3),
primary key (ID));
o In above both examples, the values are specified in the order in which
the corresponding attributes are listed in the relation schema.
o If you don’t remember the order of attributes, the attributes can be
specified in insert statement as follow –
insert into instructor (ID, name, dept_name, salary)
values (100,'George', 'Computer', 110000 );
Updates
o The UPDATE command is used to change the value of an attribute
in the existing records of a table.
o E.g. consider a table labs:-
Give the following MySQL command;
desc labs;
update labs
set NoOfComp= 25
where labno=1;
o E.g. consider table faculty. Now give the following command to see
the details of existing records in that table –
Now if the query is – increase the salary of faculty by 1000. Then the
following command will be used –
update faculty
set fsalary=fsalary+1000;
Unit-III
(Intermediate SQL)
Join Expressions
Refer natural join, page number 28.
SQL provides other forms of the join operation.
In General, following are the types of Joins :
Join Conditions
The on condition allows a general predicate over the relations being
joined. This predicate is written like a where clause predicate except
for the use of the keyword on rather than where.
E.g. consider the relations instructor and department in a reduced form
(i.e. less number of records), named as instructor_r and department_r.
(Refer figure 3.17 and figure 3.18) –
instructor_r relation
ID name dept_name salary
department_r relation
dept_name building budget
Computer Building No. 1 1000000
IT Building No. 2 500000
ETC Building No. 1 800000
Outer Joins
In an inner join, the rows from both the tables where the join gets
matched are selected. So some rows (tuples) in any of the tables may
be lost. It happens because the rows that do not satisfy the join
condition are rejected.
The outer join operations works in a manner similar to the inner join
operations, but preserve those tuples that would be lost in a join, by
creating tuples in the result containing null values.
In general, there are three forms of outer join:
Left join (left outer join):- This join returns all rows
from the left table and only those rows from right table
where join condition is met.
Right join (right outer join):- This join returns all rows
from the right table and only those rows from left table
where join condition is met.
Full join (full outer join):- It is a combination of the left
and right outer join types. The resultant relation contains
all rows from both the tables, with null values for the
missing rows where join condition is not met.
employee
EID Ename E_did
100 George 1
101 Krishna 1
102 Uday 2
200 Bhaskar 15
select *
from employee
left outer join department_all
on employee.E_did=department_all.d_id;
OR
select *
from employee
left join department_all
on employee.E_did=department_all.d_id;
Right join (right outer join):- The right outer join is symmetric to
the left outer join. Tuples from the right-hand side relation that do not
match any tuple in the left-hand side relation are padded with nulls
and are added to the result of the right outer join.
E.g. following query is issued –
select *
from employee
right join department_all
on employee.E_did=department_all.d_id;
OR
select *
from employee
right outer join department_all
on employee.E_did=department_all.d_id;
Full join (full outer join):- The full join clause is not supported by
MySQL. So the operation can be carried out by combination of left
join and right join as follows-
select *
from employee
left join department_all
on employee.E_did=department_all.d_id
union all
select *
from employee
right join department_all
on employee.E_did=department_all.d_id;
Views
Views are generally known as virtual tables or virtual relations.
When we use the CREATE TABLE command to create a table, then
physically the space is created for this table and is stored in database.
But it is not desirable for all users to see the entire logical model and
all relations. Security constraints may require that certain data must be
hidden from some users.
So, SQL allows a virtual relation to be defined by a query, and the
relation conceptually contains the result of the query. The virtual
relation is not precomputed and stored, but instead is computed by
executing the query whenever the virtual relation is used.
In simple words - In Views, the resulting records of the query
expression is not stored on the disk, but only the query expression is
stored on the disk. So query expression gets executed every time when
user tries to get the data from it, so that user will get the latest updated
value every time.
prereq relation
course_id prereq_id
IT-102 IT-101
Mech-102 Mech-101
Comp-103 Comp-102
ETC-103 ETC-102
Course relation
course_id title dept_name credits
Now, if we want to find out the courses IDs and title of the subjects
that have some prerequisite courses, along with department names to
which they belong. So first create the view using create view
command as follow –
create view course2 as
select prereq.course_id, title, dept_name
from course, prereq
where course.course_id = prereq.course_id;
So view i.e. virtual relation will be created. Now give the following
command to get the desired result –
select * from course2;
The output of this query will be as follow –
course_id title dept_name
Comp-103 Data Mining Computer
ETC-103 Advanced Microprocessor ETC
IT-102 Network Security IT
Mech-102 Machine Design Mechanical
Now if the query is -- to find out the courses IDs and title of the
subjects that have some prerequisite courses, in computer department.
Then the query can be issued as follow –
select * from course2
where dept_name = 'Computer';
Materialized Views
Certain database systems allow view relations to be stored, but they
make sure that, if the actual relations used in the view definition
change, the view is kept up-to-date. Such views are called as
materialized views.
The process of keeping the materialized view up-to-date is called
materialized view maintenance (or view maintenance).
View maintenance can be done immediately when any of the
relations on which the view is defined is updated. Some database
systems, however, perform view maintenance lazily, when the view
is accessed.
Applications that use a view frequently may benefit if the view is
materialized. Applications that demand fast response to certain
queries can benefit greatly by creating materialized views
corresponding to the queries.
The materialized view has the disadvantages also – e.g. storage costs
and the added overhead for updates.
MySQL does not support the materialized view by itself, but the
effect of it can be generated.
Update of a View
Views present serious problems if we express updates, insertions, or
deletions with them. The difficulty is that a modification to the
Integrity Constraints
Also refer the topic “Basic Schema Definition”, from Page No. 17.
The integrity constraints ensure that:- the changes made in the
database are by authorized users and consistency of data in the
database is maintained i.e. no loss of data consistency.
Integrity constraints guard against accidental damage to the database.
Examples of integrity constraints –
An instructor name in instructor relation, cannot be null.
No two instructors in instructor relation, can have the
same ID, etc
Integrity constraints are identified at –
database schema designing process – using create table
command
delimiter $$
create function dept_count3 (dept_name varchar(15))
returns integer
deterministic
begin
declare d_count3 integer;
select count(*) into d_count3
from instructor
where instructor.dept_name = dept_name;
return d_count3;
end $$
delimiter;
dept_name
ETC
delimiter $$
create function Hello1 (string_name varchar(15))
returns varchar(50)
deterministic
return concat('Hello students, ',string_name,', !!');
end $$
delimiter ;
Some SQL supports functions that can return table as a result. Such
functions are called table functions. (Note – MySQL does not
support this feature).
Consider the function defined as follow, which returns a table
containing all the instructors of a particular department.
SQL also supports procedures. The general syntax for the procedures
is as follow:
call GetInstName1();
# To define Procedures
delimiter $$
create procedure dept_count_proc(in dept_name varchar(15),
out d_count int)
begin
select count(*) into d_count
from instructor
where instructor.dept_name = dept_name;
end $$
delimiter ;
Now use the call statement to find out the required count, say for ETC
department -
SQL permits more than one procedure of the same name, so long
as the number of arguments of the procedures with the same name is
different. The name, along with the number of arguments, is used to
identify the procedure. SQL also permits more than one function
with the same name, so long as the different functions with the same
EvenNoString
0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,
If-then statement :-
The general syntax for if-then can be given as follow:
if Boolean expression (some condition)
then statements;
endif;
delimiter $$
create procedure count_proc_ifthenelse
(in dept_name varchar(15),
out d_count int,
out inst_count_level varchar(15))
begin
select count(*) into d_count
from instructor
where instructor.dept_name = dept_name;
if d_count >2 then
set inst_count_level = 'Excellent';
Triggers
A trigger is a statement (or type of stored procedure) that is executed
automatically when some modification to the database is done.
Modification means – some events like insert, update, delete etc
occurs.
Triggers are also called s event-condition-action rules or ECA rules.
The main aim of triggers is to maintain data integrity and also one
can design a trigger for recording information, which can be used for
auditing purposes.
To design a trigger, we must meet two requirements:
Specify when a trigger is to be executed.
Specify the action to be taken when the trigger executes.
Triggers in SQL
We will consider how to implement triggers in MySQL. The syntax
for implementing the triggers may change from one DBMS to
another.
The triggers can be- Row level trigger or statement level trigger.
Row level trigger – An event is triggered for each row
updated, inserted or deleted.
Statement level trigger – An event is triggered for each
SQL statement executed.
There are six types of triggers that can be made:
Before insert
After insert
Before update
After update
Before delete
After delete
After/Before Insert Trigger:
The general syntax will be as follow:
cretate trigger trigger_name
after/before
insert/delete/update [OF column_name]
on table_name [use of OLD/NEW clause]
for each row
begin
statements
end
OLD and NEW qualifiers: - These qualifiers are related to row
triggers and represent old and new values of a column before and
after the operation. The functionality of the prefix qualifiers OLD and
NEW are given in following table-
DML statement OLD value NEW value
DELETE value before deleted NULL
INSERT NULL Value inserted
UPDATE value before update Value after update
# Triggers…
create table staff_salary
(ID int,
name varchar(25) not null,
salary numeric (10,3),
net_salary numeric (10,3),
primary key (ID));
Bibliography
1. Abraham Silberschatz, Henry F. Korth, S. Sudarshan, “Database System
Concepts”, 6th Edition, McGraw-Hill Hill Education.
2. Abraham Silberschatz, Henry F. Korth, S. Sudarshan, “Database System
Concepts”, 4th Edition, McGraw-Hill Hill Education.
3. Ramez Elmasri and Shamkant B. Navathe “Fundamentals of Database Systems”,
5th Edition, Pearson.
4. Express Learning, “Database Management Systems”, ITL Education Solutions
Limited.
5. Archana Verma, “Database Management Systems”, GenNext Publication.
6. Dr. Rajiv Chopra, “Database Management Systems (DBMS) – A Practical
Approach”, 5th Edition, S. Chand Technical
7. Tanmay Kasbe, “Database Management System Concepts – A Practical
Approach”, First Edition, Educreation Publishing.
8. Mahesh Mali, “Database Management Systems”, Edition 2019, TechKnowledge
Publications.
9. Rajendra Prasad Mahapatra, Govind Verma, “Database Management System”,
Khanna Publishing.
10. Malay K. Pakhira, “Database Management System”, Eastern Economy Edition,
PHI.
11. Sarika Gupta, Gaurav Gupta, “Database Management System”, Khanna Book
Publishing Edition.
12. Riktesh Srivastava, Rajita Srivastava, “Relational Database Management
System”, New Age International Publishers.
13. Peter Rob, Carlos Coronel, “Database System Concepts’, Cenage Learning, India
Edition
14. Bipin C. Desai, “An Introduction to Database Systems”, Galgotia Publications.
15. G.K. Gupta, “Database Management Systems”, McGraw Hill Education.
16. Shio Kumar Singh, “Database Systems – Concepts, Design and Applications”, 2nd
Edition, PEARSON.
17. S.D.Joshi, “Database Management System”, Tech-Max Publication.
18. R. Ramkrishnan , J. Gehrke, "Database Management Systems", 3rd Edition,
McGraw-Hill
19. C. J. Date, “Introduction to Database Management Systems”, 8th Edition, Pearson
20. Atul Kahate, “Introduction to Database Management System”, 3rd Edition,
Pearson.
21. Bharat Lohiya, “Database Systems”, Tenth Edition, Aditya Publication, Amravati.
22. Vijay Krishna Pallaw, “Database Management System”, 2nd, Asian Books Pvt.
Ltd.
23. Database Management Systems, Database Management Systems.
24. Mrs. Jyoti G. Mante (Khurpade), Mrs. Smita M. Dandge, “Database Mangement
System”, Nirali Prakashan.
25. Step by Step Database Systems (DBMS), Shiv Krupa Publications, Akola
26. Mrs. Sheetal Gujar –Takale, Mr. Sahil K. Shah, “Database Management System”,
Nirali Prakashan.
27. Mrs. Jyoti G. Mante (Khurpade), U.S. Shirshetti, M.V. Salvi, K.S. Sakure,
“Relational Database Management System”, Nirali Prakashan.
28. Seema Kedar, Rakesh Shirsath, “Database Management Systems”, Technical
Publications.
29. Pankaj B. Brahmankar, “Database Management Systems”, Tech-Max
Publications, Pune.
30. Imran Saeed, Tasleem Mustafa, Tariq Mahmood, Ahsan Raza Sattar, “A
Fundamental Study of Database Management Systems”, 3rd Edition, IT Series
Publication.
31. Database Management Systems Lecture Notes, Malla Reddy College of
Engineering and Technology, Secunderabad.
32. Dr. Satinder Bal Gupta, Aditya Mittal, “Introduction to Database Management
System, University Science Press.
33. E-Notes BCS 41/ BCA 41 on “Database Management System”, Thiruvalluvar
University.
34. Bighnaraj Naik, Digital Notes on “Relational Database Management System”,
VSSUT, Burla.
35. Viren Sir, Relational database Management System”, Adarsh Institute of
Technolgoyt (Poly), VITA.
36. Sitansu S. Mitra, “Principles of Relational Database Systems”, Prentice Hall.
37. Neeraj Sharma, Liviu Perniu, Raul F. Chong, Abhishek Iyer, Chaitali Nandan,
Adi-Cristina Mitea, Mallarswami Nonvinkere, Mirela Danubianu, “Database
Fundamentals”, First Edition, DB2 On Campus Book Series.
38. Database Management System, Vidyavahini First Grade College, Tumkur.
39. Bhavna Sangamnerkar, Revised by: Shiv Kishor Sharma, “Database Management
System”, Think Tanks Biyani Group of Colleges.
40. Tibor Radvanyi, “Database Management Systems”.
41. Ramon A. Mata-Toledo, Pauline K. Cushman, “Fundamentals of Relational
Databases”, Schaum’s Outlies.
Bibliography
Web Resources
https://www.sqlshack.com/sql-union-vs-union-all-in-sql-server/
https://www.sqltutorial.org/sql-intersect/
https://gokhanatil.com/2010/10/minus-and-intersect-in-mysql.html
https://www.sqltutorial.org/sql-minus/
https://www.w3schools.com/sql/sql_in.asp
https://www.geeksforgeeks.org/
https://www.w3resource.com/sql/joins/natural-join.php
https://www.guru99.com/joins-sql-left-right.html
https://www.w3schools.com/sql/sql_join.asp
https://www.guru99.com/joins-sql-left-right.html
http://www.sql-join.com/
https://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/
https://www.tutorialspoint.com/sql/sql-using-joins.htm
https://www.tutorialspoint.com/difference-between-views-and-materialized-views-in-sql
https://tutorialink.com/dbms/procedures-and-functions.dbms
https://docs.oracle.com/cd/E19078-01/mysql/mysql-refman-5.0/stored-programs-views.html
https://www.mysqltutorial.org/mysql-stored-procedure/mysql-while-loop/
https://www.mysqltutorial.org/mysql-if-statement
https://www.javatpoint.com/mysql-trigger
https://www.javatpoint.com/mysql-trigger
https://www.w3resource.com/mysql/mysql-triggers.php