Dbms Lab Manual - II B.tech It Semii (2017-18)
Dbms Lab Manual - II B.tech It Semii (2017-18)
LABORATORY MANUAL
B.TECH
(II YEAR – II SEM)
(2017-18)
Vision
Mission
IT and is playing a vital role in shaping the education of the 21st century
To facilitate the graduates with the ability to visualize, gather information, articulate,
analyze, solve complex problems, and make decisions. These are essential to
address the challenges of complex and computation intensive problems increasing
their productivity.
To facilitate the graduates with the technical skills that prepare them for immediate
employment and pursue certification providing a deeper understanding of the
technology in advanced areas of computer science and related fields, thus
encouraging to pursue higher education and research based on their interest.
To facilitate the graduates with the soft skills that include fulfilling the mission,
setting goals, showing self-confidence by communicating effectively, having a
positive attitude, get involved in team-work, being a leader, managing their career
and their life.
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting
time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab
with the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any)
needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation
note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the
lab sessions.Misuse of the equipment, misbehaviors with the staff and systems etc., will
attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out ; if
anybody found loitering outside the lab / class without permission during working hours
will be treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system /
seat is kept properly.
S. No Topic Page no
1 Introduction 1
3 MYSQL INSTALLATION 16
4 DDL commands 24
5 DML COMMANDS 29
6 KEY Constraints 34
9 Views 50
10 JOINS 53
11 Triggers 57
13 PL/SQL 64
15 Case Studies 70
INTRODUCTION
Hierarchical Model
This model is like a hierarchical tree structure, used to construct a hierarchy of records in
the form of nodes and branches. The data elements present in the structure have Parent-Child
logical unit. A parent unit may have many child units, but a child is restricted to have only one
parent.
It cannot demonstrate the overall data model for the enterprise because of the non-
availability of actual data at the time of designing the data model.
Network Model
It supports the One-To-One and One-To-Many types only. The basic objects in this model
are Data Items, Data Aggregates, Records and Sets.
Relational Model
Features of an RDBMS
The ability to create multiple relations and enter data into them
An attractive query language
An RDBMS product has to satisfy at least Seven of the 12 rules of Codd to be accepted
as a full- fledged RDBMS.
1
Relational Database Management System
RDBMS is acronym for Relation Database Management System. Dr. E. F. Codd first
introduced the Relational Database Model in 1970. The Relational model allows data to be
represented in a simple row- column. Each data field is considered as a column and each record
is considered as a row. Relational Database is more or less similar to Database Management S
ystem. In relational model there is relation between their data elements. Data is stored in tables.
Tables have columns, rows and names. Tables can be related to each other if each has a column
with a common type of information. The most famous RDBMS packages are Oracle, Sybase and
Informix.
1 Rahul Satelite
2 Sachin Ambawadi
3 Saurav Naranpura
1 78 89 94
2 54 65 77
3 23 78 46
Here, both tables are based on students details. Common field in both tables is Rollno. So we
can say both tables are related with each other through Rollno column.
Degree of Relationship
One to One (1:1)
The Degree of Relationship indicates the link between two entities for a specified occurrence
of each.
2
One to One Relationship: (1:1)
Student Has Roll No.
One student has only one Rollno. For one occurrence of the first entity, there can be, at the
most one related occurrence of the second entity, and vice-versa.
1M
Course Contains Students
As per the Institutions Norm, One student can enroll in one course at a time however, in one
course, there can be more than one student.
For one occurrence of the first entity there can exist many related occurrences of the second
entity and for every occurrence of the second entity there exists only one associated occurrence
of the first.
The major disadvantage of the relational model is that a clear-cut interface cannot be determined.
Reusability of a structure is not possible. The Relational Database now accepted model on which
major database system are built.
Some basic rules have to be followed for a DBMS to be relational. They are known as Codd’s
rules, designed in such a way that when the database is ready for use it encapsulates the
relational theory to its full potential. These twelve rules are as follows.
E. F. Codd Rules
3
3. The Systematic Treatment of Null Values
The RDBMS must be taken care of null values to represent missing or inapplicable information.
According to the rule the system must support data definition, view definition, data
manipulation, integrity constraints, authorization and transaction management
operations.
The changes that are made should not affect the user’s ability to work with the
data.The change can be splitting table into many more tables.
The system must be access or manipulate the data that is distributed in other systems.
Oracle8 and later versions are supported object-oriented concepts. A structure once created can
be reused is the fundamental of the OOP’s concept. So we can say Oracle8 is supports Object
4
Relational model, Object - oriented model both. Oracle products are based on a concept known
as a client-server technology. This concept involves segregating the processing of an application
between two systems. One performs all activities related to the database (server) and the other
performs activities that help the user to interact with the application (client). A client or front-end
database application also interacts with the database by requesting and receiving information
from database server. It acts as an interface between the user and the database.
The database server or back end is used to manage the database tables and also respond to client
requests.
Introduction to ORACLE
ORACLE is a powerful RDBMS product that provides efficient and effective solutions for major
database features. This includes:
An ORACLE database system can easily take advantage of distributed processing by using its
Client/ Server architecture. In this architecture, the database system is divided into two parts:
The client executes the database application that accesses database information and interacts with
the user.
A back-end or a server portion
The server executes the ORACLE software and handles the functions required for concurrent,
shared data access to ORACLE database.
5
ILLUSTRATION: ROADWAY TRAVELS
“Roadway Travels” is in business since 1977 with several buses connecting different places in
India. Its main office is located in Hyderabad.
Reservations
Ticketing
Cancellations
Reservations :
Cancellations are also directly handed at the booking office. Cancellation charges
will be charged.
Wait listed tickets that do not get confirmed are fully refunded.
6
WEEK-1
AIM: Analyze the problem and come with the entities in it. Identify what Data has to be
persisted in the databases.
The Following are the entities:
1 .Bus
2. Reservation
3. Ticket
4. Passenger
5. Cancellation
Destination
Source
Couch Type
Bus No
Bus
Reservation (Entity)
Bus No
Contact No
No-of-Seats
Journey date
Address
PNR NO
Reservation
Ticket :(Entity)
Dep- Time
Source
Age
Sex
Journey date
Destination
Ticket No
Bus No
Ticket
7
Passenger:
Contact NO
Age
Sex
PNR NO
Name
Ticket No
Passenger
Cancellation (Entity)
Contact No
PNR NO
Cancellation
8
Concept design with E-R Model:
9
CASE STUDY 1:
Consider the following information about a university database:
• Professors have an SSN, a name, an age, a rank, and a research specialty.
• Projects have a project number, a sponsor name (e.g., NSF), a starting date, an
ending date, and a budget.
• Graduate students have an SSN, a name, an age, and a degree program (e.g.,
M.S. or Ph.D.).
• Each project is managed by one professor (known as the project's principal
investigator).
• Each project is worked on by one or more professors (known as the project's co-
investigators).
• Professors can manage and/or work on multiple projects.
• Each project is worked on by one or more graduate students (known as the
project's research assistants).
• When graduate students work on a project, a professor must supervise their
work on the project. Graduate students can work on multiple projects, in which
case they will have a (potentially di_erent) supervisor for each one.
• Departments have a department number, a department name, and a main office.
• Departments have a professor (known as the chairman) who runs the
department.
• Professors work in one or more departments, and for each department that they
work in, a time percentage is associated with their job.
• Graduate students have one major department in which they are working on
their degree.
• Each graduate student has another, more senior graduate student (known as a
student advisor) who advises him or her on what courses to take.
WORK SHEET
WORK SHEET
Weekly Evaluation
11
What is SQL and SQL*Plus
Oracle was the first company to release a product that used the English-based Structured Query
Language or SQL. This language allows end users to manipulate information of table(primary
database object). To use SQL you need not to require any programming experience. SQL is a
standard language common to all relational databases. SQL is database language used for
storing and retrieving data from the database. Most Relational Database Management Systems
provide extension to SQL to make it easier for application developer. A table is a primary
object of database used to store data. It stores data in form of rows and columns.
SQL*Plus is an Oracle tool (specific program ) which accepts SQL commands and PL/SQL
blocks and executes them. SQL *Plus enables manipulations of SQL commands and PL/SQL
blocks. It also performs additional tasks such as calculations, store and print query results in the
form of reports, list column definitions of any table, access and copy data between SQL
databases and send messages to and accept responses from the user. SQL *Plus is a character
based interactive tool, that runs in a GUI environment. It is loaded on the client machine.
To communicate with Oracle, SQL supports the following categories of commands:
Before we take a look on above-mentioned commands we will see the data types available in
Oracle.
Oracle Internal Data types
When you create a table in Oracle, a few items should be important, not only do you have to
give each table a name(e.g. employee, customer), you must also list all the columns or fields
(e.g. First_name, Mname, Last_name) associated with the table. You also have to specify what
12
type of information thattable will hold to the database. For example, the column Empno holds
numeric information. An Oracle database can hold many different types of data.
characters or bytes, depending on the choice of national character set. Maximum size
is determined by the number of bytes required to store each character, with an upper
limit of 4000 bytes.
Number [p,s] Number having precision p and scale s. The precision p indicates total
number of digit varies from 1 to 38. The scale s indicates number of digit in fraction part
varies from -84 to 127.
Date Stores dates from January 1, 4712 B.C. to December 31, 4712 A.D. Oracle
Raw (Size) Stores binary data of length size. Maximum size is 2000 bytes. One must
have to specify size with RAW type data, because by default it does not specify any size.
LOB is use to store unstructured information such as sound and video clips, pictures upto 4 GB
size.
CLOB A Character Large Object containing fixed-width multi-byte characters.
Varying-width character sets are not supported. Maximum size is 4GB.
13
NCLOB A National Character Large Object containing fixed-width multi-byte
characters.
Varying-width character sets are not supported. Maximum size is 4GB. Stores
national character set data.
BLOB To store a Binary Large Object such a graphics, video clips and sound files.
Maximum size is 4GB.
BFILE Contains a locator to a large Binary File stored outside the database. Enables
byte stream I/O access to external LOBs residing on the database server. Maximum
size is 4GB.Apart from oracle internal data types, user can create their own data type, which is
used in database and other database object. We will discuss it in the later part.
The following are tabular representation of the above entities and relationships
BUS:
COLUMN NAME DATA TYPE CONSTRAINT
Source varchar2(20)
Destination varchar2(20)
RESERVATION:
COLUMN NAME DATA TYPE CONSTRAINT
No-of-seats integer(8)
Address varchar2(50)
14
TICKET:
COLUMN NAME DATA TYPE CONSTRAINT
PASSENGER:
Name varchar2(15)
Age integer(4)
Sex char(10) (Male/Female)
Contact no Number(9) Should be equal to 10 numbers
and not allow other than
numeric
CANCELLATION:
COLUMN NAME DATA TYPE CONSTRAINT
Journey-date Date
Seat no Integer(9)
Contact_No Number(9) Should be equal to 10 numbers
and not allow other than
numeric
15
WEEK-2
Step1
Make sure you already downloaded the MySQL essential 5.0.45 win32.msi file. Double click
on the .msi file.
Step2
This is MySQL Server 5.0 setup wizard. The setup wizard will install MySQL Server 5.0
release 5.0.45 on your computer. To continue, click next.
16
Step3
Choose the setup type that best suits your needs. For common program features select Typical
and it’s recommended for general use. To continue, click next.
Step4
17
Step5
The program features you selected are being installed. Please wait while the setup wizard
installs MySQL 5.0. This may take several minutes
Step6
To continue, click next.
18
Step7
To continue, click next.
Step8
Wizard Completed. Setup has finished installing MySQL 5.0. Check the configure the MySQL
server now to continue. Click Finish to exit the wizard
d.
19
Step9
The configuration wizard will allow you to configure the MySQL Server 5.0 server instance.
To continue, click next.
Step10
Select a standard configuration and this will use a general purpose configuration for the
server that can be tuned manually. To continue, click next.
20
Step11
Check on the install as windows service and include bin directory in windows path. To
continue, click next.
Step12
Please set the security options by entering the root password and confirm retype the password.
continue, click next.
21
Step13
Step14
Processing configuration in progress.
22
Step15
Configuration file created. Windows service MySQL5 installed. Press finish to close the
wizard.
23
PRACTISING DDL & DML COMMANDS
Data Definition Language
The data definition language is used to create an object, alter the structure of an object and also drop already
created object. The Data Definition Languages used for table definition can be classified into following:
24
WEEK-3
1. CREATION OF TABLES:
Table Created.
Desc command
The DESCRIBE command is used to view the structure of a table as follows.
SQL>DESC SAILORS;
TEST RESULT
Example 1: Create an RESERVES table with fields (SID , BID ,DAY ) and display using
DESCRIBE command.
Example 2:Create a BOATS table with Fields(BID,BNAME,COLOR )and display using DESCRIBE
command
25
2. ALTER TABLE :
To ADD a column:
TEST OUTPUT
To DROP a column:
SYNTAX: ALTER TABLE <TABLE NAME>DROP COLUMN <COLUMN NAME>;.
EX: (Write your own Query )
TEST OUTPUT
To MODIFY a column:
SYNTAX: ALTER TABLE <TABLE NAME>MODIFY( <COLUMN NAME>
<NEW DATATYPE>(<NEW SIZE>));
EX: (Write your own Query )
TEST OUTPUT
Example1:
SQL>ALTER TABLE SAILOR ADD (SNO NUMBER(10));
TEST OUTPUT
26
3. RENAME A TABLE
TEST OUTPUT
4. TRUNCATE A TABLE
TEST OUTPUT
5. DROP A TABLE
TEST OUTPUT
27
VIVA QUESTIONS
Weekly Evaluation
28
WEEK-4
DML COMMANDS
SYNTAX
Example:
TEST OUTPUT:
TEST OUTPUT
29
c. Elimination of duplicates from the select statement
TEST OUTPUT
WHERE searchcondition;
TEST OUTPUT
30
2. INSERTING DATA IN TO TABLE
SYNTAX:
INSERT INTO tablename (columnname1, columnname2,….columnname n)
Example:
SYNTAX
Example:
SQL>INSERT INTO SAILORS(SID,SNAME,RATING,AGE) VALUES
(31,’LUBBER’, 8, 55.5);
1 row created
TEST OUTPUT:
TEST OUTPUT:
31
UPDATE
SQL>UPDATE tablename
WHERE somecolumn=somevalue;
TEST OUTPUT
DELETE
Based on the condition specified the rows gets fetched from the table and gets
deleted in table. Here the WHERE clause is optional.
TEST OUTPUT
32
Example2: DELETE FROM SAILORS;
TEST OUTPUT
VIVA QUESTIONS
Weekly Evaluation
33
WEEK-5
KEY CONSTRAINTS
TEST OUTPUT
TEST OUTPUT
2. DEFAULT
CREATE TABLE sailors ( sid integer,
sname varchar(32) ,
rating integer NOT NULL,
age real DEFAULT 25,
PRIMARY KEY (sid) );
34
3. UNIQUE
TEST OUTPUT
4. FOREIGN KEY
CREATE TABLE reserves ( sid integer not null, bid integer not null, day datetime not null, PRIMARY KEY
(sid, bid, day), FOREIGN KEY (sid) REFERENCES sailors(sid) );
TEST OUTPUT
Test Output
35
VIVA QUESTIONS
Weekly Evaluation
36
WEEK-6
2. SUM:
SYNTAX:
Select SUM ([<distinct>/<ALL]<n>)
Example: Find the sum of ages of all sailors?
Select Sum(S.age)from sailors S;
TEST RESULT:
3. AVG:
SYNTAX:
Select AVG ([<distinct>/<ALL]<n>)
Example: Find average of rating of all sailors?
Select avg(S.rating )from sailors S;
TEST RESULT:
37
4. MINIMUM(MIN):
SYNTAX:
Select MIN ([<distinct>/<ALL]<expr>)
Example: Find youngest sailor from sailors?
Select min(S.age )from sailors S;
TEST RESULT:
5. MAXIMUM(MAX):
SYNTAX:
Select MAX ([<distinct>/<ALL]<expr>)
Example: Find sid of the oldest sailors?
Select max(s.sid)from sailor
TEST RESULT:
Select abs(-9);
1) SYNTAX: Ceil()
Ex: Select ceil(9.5);
TEST OUTPUT
2) SYNTAX :Floor()
Ex: Select floor(10.5);
TEST OUTPUT
3) SYNTAX mod()
Ex: select mod(17,5);
TEST OUTPUT
38
4) SYNTAX :power(n,m)
Ex: select power(2,2);
TEST OUTPUT
5) SYNTAX : round(n,m)
Ex: select round(10.586,2);
TEST OUTPUT
6) SYNTAX : truncate(n,m)
Ex: select truncate(1.223,1);
TEST OUTPUT
7) SYNTAX : sign()
Ex: select sign(-5);
TEST OUTPUT
8) SYNTAX : sqrt()
Ex: select sqrt(25);
TEST OUTPUT
Example:
SQL> select * from emp_master where salary BETWEEN 5000 AND 8000;
TEST OUTPUT:
39
IN Operator:
SQL>Select * from emp_master where deptno IN(10,30);
TEST OUTPUT:
LIKE Operator:
TEST OUTPUT:
Logical Operator:
SQL>select*From emp_master where job like ‘_lerk’;
TEST OUTPUT:
40
AND Operator:
SQL> select * from emp_master where salary > 5000 and comm < 750 ;
TEST OUTPUT:
OR Operator:
SQL>select * from emp_master where salary > 5000 or comm < 750;
TEST OUTPUT:
NOT Operator:
SQL>select*from emp_master where not salary=10000;
TEST OUTPUT:
41
2) Lower: This String function will convert input string in to lower case.
Syntax: Lower(string)
Example:
SQL> select lower(‘AZURE’) from dual;
TEST OUTPUT:
3) Upper: This string function will convert input string in to upper case.
Syntax:Upper(string)
Example:
SQL> select upper(‘azure’) from dual;
TEST OUTPUT:
Syntax: Rtrim(string,set)
Example:
SQL>select rtrim(‘azuretrim’,’trim’) from dual;
TEST OUTPUT:
6) Translate:
Syntax: Translate(string1, string2, string3)
Example:
SQL>select translate(‘abcde’,’xaybzcxdye’,’tanzmulrye’) from dual;
TEST OUTPUT:
42
7) Replace:
Syntax:Replace(string, searchstring, replacestring)
Example:
SQL> select replace(‘jack and jue’,’j’,’bl’) from dual;
TEST OUTPUT:
8) Substr:
Syntax: Substr (string, starts [, count])
Example:
SQL>select substr (‘azuretechnology’,4,6) from dual;
TEST OUTPUT:
9) Char:
Syntax: Char(number)
TEST OUTPUT:
Example:
SQL>select char(65) from dual;
TEST OUTPUT:
43
12) Length:
Syntax:Length(string)
Example:
SQL>select length(‘azure’) from dual;
TEST OUTPUT:
VIVA QUESTIONS:
Weekly Evaluation
44
WEEK-7
TEST OUTPUT
Example2: Find the names of Sailors who have reserved a red boat using a nested query.
Select S.name
From Sailors S
Where S.sid IN (select R.sid
from reserves R
where R.bid IN( select R.bid
from Boats B
where B.color=’red’))
45
TEST OUTPUT
TEST OUTPUT
CORRELATED QUERIES
I) EXISTS:
The EXISTS operator is another set comparison operator such as IN.It allows us to test whether the set
is non empty and will retrieve the Data.
Example1 :Find the names of Sailors who have reserved boat no.103
Select S.name
From Sailors
Where EXISTS(Select *
from Reserves R
where R.bid=103 AND R.sid=S.sid);
TEST OUTPUT
Example2: Find the sailors whose rating is better than some Sailor called ‘Horatio’
Select S.sid
From Sailors S
Where S.rating>ANY (select S2.rating
From Sailors.S2
Where S2.name=’Horatio’);
46
TEST OUTPUT
TEST OUTPUT
SYNTAX
47
HAVING CLAUSE
Example1: Find the Average age of all Sailors for each rating level that has atleast two Sailors
TEST OUTPUT
Example 2: Find the age of the youngest sailor who is eligible to vote.
TEST OUTPUT
Order By Clause
Select<column(s)>from<Table Name>where[condition(s)][order by<column name>[asc /] desc ];
Example:
SQL> select empno,ename,salary from emp_master order by salary;
TEST OUTPUT:
48
VIVA QUESTIONS:
3) What happens if we eliminate HAVING clause in a query which is having both GROUP BY
and HAVING clauses.
Weekly Evaluation
49
WEEK-8
VIEWS
After a table is created and populated with data, it may become necessary to prevent all users from
accessing all columns of a table, for data security reasons. This would mean creating several tables
having the appropriate number of columns and assigning specific users to each table as required. This
will achieve the security requirements but will rise to a great deal of redundant data being resident in
tables, in the database. To reduce redundant data to the minimum possible, oracle allows the creation of
an object called a view.
Views are essentially saved SELECT queries that can themselves be queried. They are used to
provide easier access to normalized data. For example, the Orders table has information about an order.
Although it references the employee and customer involved in each order, the Orders doesn't itself
contain any valuable information about the employee and customer. We have seen how to use joins to
output valuable data from different tables. Creating a view is a way of saving these types of more
complicated queries. Views offer the following advantages:
1. Ease of use: A view hides the complexity of the database tables from end users. Essentially we can
think of views as a layer of abstraction on top of the database tables.
2. Space savings: Views takes very little space to store, since they do not store actual data.
3. Additional data security: Views can include only certain columns in the table so that only the non-
sensitive columns are included and exposed to the end user. In addition, some databases allow views to
have different security settings, thus hiding sensitive data from prying eyes.
50
Example:
SQL>Select Empno,Ename,Salary from EmpView where Deptno in(10,30);
TEST OUTPUT:
UPDATABLE VIEWS:
Syntax for creating an Updatable View:
Create View Emp_vw As
Select Empno,Ename,Deptno from Employee; View created.
SQL>Insert into Emp_vw values(1126,’Brijesh’,20);
TEST OUTPUT:
TEST OUTPUT:
DESTROYING A VIEW:
Syntax: Drop View <View_Name>;
Example:
SQL>Drop View Emp_Vw;
TEST OUTPUT:
51
VIVA QUESTIONS:
1. Define view.
Weekly Evaluation
52
WEEK-9
JOINS
SQL joins are used to query data from two or more tables, based on a relationship
between certain columns in these tables.
ORDER TABLE
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
CUSTOMER TABLE
INNER JOIN
TEST OUTPUT
53
WEEK-10
2) SELECT
Customers.CustomerName, Orders.OrderID
FROM Customers INNER JOIN Orders ON Customers.
CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
TEST OUTPUT
LEFT JOIN
The LEFT JOIN keyword returns all rows from the left
table (table_name1), even if there are no matches in the right table (table_name2).
ORDER BY Customers.CustomerName;
TEST OUTPUT
RIGHT JOIN
The RIGHT JOIN keyword Return all rows from the right
table (table_name2), even if there are no matches in the left table (table_name1).
This is another table named employee.here they have to give field accordingly.
SELECT Orders.OrderID, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;
TEST OUTPUT
54
WEEK-11
OUTER JOIN
TEST OUTPUT
UNION
Syntax
Example 1: Select name from sailors UNION select bname from boats;
TEST OUTPUT
TEST OUTPUT
UNION ALL
Select rsid from reserve union all select sid from sailors;
TEST OUTPUT
55
VIVA QUESTIONS:
1) What is Join?
3) What are the prerequisites for any two tables to apply a Join?
Weekly Evaluation
56
TRIGGERS
In MySQL, a trigger is a set of SQL statements that is invoked automatically when a change is made to
the data on the associated table. A trigger can be defined to be invoked either before or after the data is
changed by INSERT, UPDATE or DELETE statement.
A database trigger is procedural code that is automatically executed in response to certain events on a
particular table or view in a database. The trigger is mostly used for maintaining the integrity of the
information on the database.
Types of Triggers:-
1.Row Triggers :-A row trigger is fired each time the table is affected by the triggering statement. For
example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each
row affected by the UPDATE statement. If a triggering statement affects no rows, a row trigger is not
executed at all.
Row triggers are useful if the code in the trigger action depends on data provided by the
triggering statement or rows that are affected. For example, Figure 15 - 3 illustrates a row trigger that
uses the values of each row affected by the triggering statement.
2.Statement Triggers :A statement trigger is fired once on behalf of the triggering statement,
regardless of the number of rows in the table that the triggering statement affects (even if no rows are
57
affected). For example, if a DELETE statement deletes several rows from a table, a statement-level
DELETE trigger is fired only once, regardless of how many rows are deleted from the table.
Statement triggers are useful if the code in the trigger action does not depend on the data
provided by the triggering statement or the rows affected. For example, if a trigger makes a complex
security check on the current time or user, or if a trigger generates a single audit record based on the
type of triggering statement, a statement trigger is used.
When defining a trigger, specify the trigger timing. That is, specify whether the trigger action is
to be executed before or after the triggering statement. BEFORE and AFTER apply to both statement
and row triggers
Example:
trigger_time=before/after
trigger_event=insert/delete/update
Example:
CREATE TRIGGER sal_sum after insert ON emp
FOR EACH ROW SET @sal = @sal + NEW.sal;
Firing a trigger:
Field Type
empid int(11)
ename varchar(50)
sal int(11)
TEST OUTPUT
58
3) now create trigger on emp
CREATE TRIGGER sal_sum after insert ON emp
FOR EACH ROW SET @sal = @sal + NEW.sal;
TESTOUTPUT
Note:when ever there is insert operation that value in the sal variable increases
59
VIVA QUESTIONS:
Weekly Evaluation
60
WEEK-12
PROCEDURES
TCL (TRANSACTION CONTROL): Transaction control statements are used to manage the changes
made by DML statements. It allows statements to be grouped together into logical transactions. TCL
Commands are Commit, Rollback and Save point.
Procedure
___________
By default, mysql recognizes the semicolon as a statement delimiter, so you must redefine the delimiter
temporarily to cause mysql to pass the entire stored program definition to the server. To redefine the
mysql delimiter, use the delimiter command.
syntax
delimiter //
create procedure procedure name(in parameter)
begin
select * from tablename;
end //
Example:
create table named emp with two fields name and salary;
Write a Query
TEST OUTPUT
delimiter //
create procedure emp(in name_p varchar(20))
begin
select * from emp where name=name_p;
end //
call sailor("smith");
with in/out parameter:
61
delimiter//
create procedure counterset(inout count in(4),in inc int(4))
begin
set count=count+inc;
end //
____________
set @counter=1;
________________
call counterset(@counter,4);
__________________
select @counter;
TEST OUTPUT
set autocommit=0;
//
start transaction;
//
update account set sal=30000 where name='mani';
//
select * from account;
TEST OUTPUT
rollback;
select * from account;
62
//
update account set sal=5000 where name='raju';
//
select * from account;
commit;
changes are now made permanent
rollback;
select * from account;
/same output will get/
TEST OUTPUT
Note: when autocommit=1 the the database commits every single update and rollback is not possible.
VIVA QUESTIONS:
1. What is a procedure?
2. What is a function?
3. Differentiate procedures and functions.
4. What is the syntax for defining a procedure?
5. List out the parameters and keywords which are used in procedures.
6. What are the advantages of procedure?
7. What is the syntax for defining a function?
8. List the advantages of functions.
9. What are the parts of procedures and functions?
10. List out the parameters and keywords which are used in functions
11. What are TCL commands and its uses?
12. List out the uses of various TCL commands?
Weekly Evaluation
63
WEEK-13
PL/SQL PROGRAMS
PL/SQL programs are written as lines of text using a specific set of characters:
PL/SQL keywords are not case-sensitive, so lower-case letters are equivalent to corresponding upper-
case letters except within string and character literals.
To improve readability, you can separate lexical units by spaces. In fact, you must separate adjacent
identifiers by a space or punctuation. The following line is not allowed because the reserved
words END andIF are joined:
You cannot embed spaces inside lexical units except for string literals and comments. For example, the
following line is not allowed because the compound symbol for assignment (:=) is split:
To show structure, you can split lines using carriage returns, and indent lines using spaces or tabs. This
formatting makes the first IF statement more readable.
TEST OUTPUT
64
2) WRITE A PROGRAM TO PRINT EVEN NUMBERS FROM 1 TO 10
DECLARE
N NUMBER(3) :=0;
BEGIN
WHILE N<=10
LOOP
N :=N+2;
DBMS_OUTPUT.PUT_LINE(N);
END LOOP;
END;
TEST OUTPUT
TEST OUTPUT
65
4) Write a program to accept a number and print it in reverse order
DECLARE
N NUMBER(5):=&N;
REV NUMBER(5):=0;
R NUMBER(5):=0;
BEGIN
WHILE N !=0
LOOP
R:=MOD(N,10);
REV:=REV*10+R;
N:=TRUNC(N/10);
END LOOP;
DBMS_OUTPUT.PUT_LINE('THE REVERSE OF A GIVEN NUMBER IS '||REV);
END;
TEST OUTPUT
TEST OUTPUT
66
VIVA QUESTIONS:
1) What is PL/SQL?
2) What is the basic structure of PL/SQL?
3) How is a process of PL/SQL compiled?
4) Mention what PL/SQL package consists of?
5) What are the benefits of PL/SQL packages?
6) What is the difference between FUNCTION, PROCEDURE AND PACKAGE in PL/SQL?
Weekly Evaluation
67
WEEK-14
DCL (DATA CONTROL LANGUAGE): Data Control Language statements are used to create roles,
permissions, and referential integrity as well it is used to control access to database by securing it. DCL
Commands are Grant and Revoke
GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the
GRANT command
TEST OUTPUT
*To check what are the grants that the location is having/
mysql> show grants;
TEST OUTPUT
*To Check what are the GRANTS having for created user
mysql> show grants for mrcet_cse;
mysql> show tables;
TEST OUTPUT
TEST OUTPUT
68
*To Flush (RE-FRESH) the privileges
mysql> flush privileges;
Query OK, 0 rows affected (0.08 sec)
* Explanation: To check where is the user i.e in case if we created user (Ex: mrcet_cse) it will be
displayed as “%”. Root user is by default so it will be available in “Localhost”
TEST OUTPUT
VIVA QUESTIONS
1. What are DCL commands?
2. List out the uses of various DCL commands?
3. What are the different types of Commands in SQL.
4. What is the difference between TCL & DCL commands.
5. Who has the privilegeto access the DCL commands.
Weekly Evaluation
69
CASE STUDY 1
1. Give an example of a foreign key constraint that involves the Dept relation. What are
the options for enforcing this constraint when a user attempts to delete a Dept tuple?
2. Write the SQL statements required to create the above relations, including appropriate
3. Define the Dept relation in SQL so that every department is guaranteed to have a
manager.
4. Write an SQL statement to add `John Doe' as an employee with eid = 101, age = 32
6. Write an SQL statement to delete the `Toy' department. Given the referential integrity
constraints you chose for this schema, explain what happens when this statement is
executed.
WORK SHEET
70
WORK SHEET
Weekly Evaluation
71
CASE STUDY 2
The key fields are underlined, and the domain of each field is listed after the field name.
Thus sid is the key for Suppliers, pid is the key for Parts, and sid and pid together form the
key for Catalog. The Catalog relation lists the prices charged for parts by Suppliers. Write
the following queries in relational algebra, tuple relational calculus, and domain relational
calculus:
2. Find the sids of suppliers who supply some red or green part.
7. Find the sids of suppliers who supply every red or green part.
8. Find the sids of suppliers who supply every red part or supply every green part.
9. Find pairs of sids such that the supplier with the first sid charges more for some part
10. Find the pids of parts that are supplied by at least two different suppliers.
12. Find the pids of parts supplied by every supplier at less than $200. (If any supplier either
does not supply the part or charges more than $200 for it, the part is not selected.)
72
WORK SHEET
Weekly Evaluation
73
CASESTUDY 3
Note that the Employees relation describes pilots and other kinds of employees as well; every pilot is
certified for some aircraft (otherwise, he or she would not qualify as a pilot), and only pilots are
certified to fly.
Write the following queries in relational algebra, tuple relational calculus, and domain relational
calculus.
3. Find the aids of all aircraft that can be used on non-stop flights from Bonn to Madras.
4. Identify the flights that can be piloted by every pilot whose salary is more than $100,000.
(Hint: The pilot must be certified for at least one plane with a sufficiently large cruising
range.)
5. Find the names of pilots who can operate some plane with a range greater than 3,000
7. Find the eids of employees who make the second highest salary.
8. Find the eids of pilots who are certified for the largest number of aircraft.
9. Find the eids of employees who are certified for exactly three aircraft.
74
11. Is there a sequence of flights from Madison to Timbuktu? Each flight in the sequence is required to
depart from the city that is the destination of the previous flight; the first
flight must leave Madison, the last flight must reach Timbuktu, and there is no restriction
on the number of intermediate flights. Your query must determine whether a sequence
WORK SHEET
Weekly Evaluation
75
76