Dbms Lab Manual
Dbms Lab Manual
Dbms Lab Manual
LABORATORY MANUAL
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
Vision
To acknowledge quality education and instill high patterns of discipline
making the students technologically superior and ethically strong which
involves the improvement in the quality of life in human race.
Mission
To achieve and impart holistic technical education using the best of
infrastructure, outstanding technical and teaching expertise to establish
the students into competent and confident engineers.
Evolving the center of excellence through creative and innovative
teaching learning practices for promoting academic achievement to
produce internationally accepted competitive and world class
professionals.
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
1. 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.
2. 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.
3. 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.
To facilitate the graduates with the knowledge of professional and ethical responsibilities by
paying attention to grooming, being conservative with style, following dress codes, safety
codes,and adapting themselves to technological advancements.
PROGRAM SPECIFIC OUTCOMES (PSOs)
After the completion of the course, B. Tech Computer Science and Engineering, the
graduates will have the following Program Specific Outcomes:
1. LAB OBJECTIVE
2. LAB OUTCOME
4. Guidelines to students
A. STANDARD OPERATING PROCEDURE
a) Explanation on today’s experiment by the concerned faculty using PPT covering the
following aspects:
1) Name of the experiment
2) Aim
3) Software/Hardware requirements
4) Commands with suitable Options
5) Creating Database
1) Altering database
2) Querying
3) Dropping database
b) Writing of DDL and DML commands by the students
c) Querying and executing of the SQL queries
Students are required to carry their lab observation book and record book with
completed experiments while entering the lab.
Students must use the equipment with care. Any damage is caused student is
punishable
Students are not allowed to use their cell phones/pen drives/ CDs in labs.
Students need to be maintain proper dress code along with ID Card
Students are supposed to occupy the computers allotted to them and are not supposed
to talk or make noise in the lab.
Students, after completion of each experiment they need to be updated in observation
notes and same to be updated in the record.
Lab records need to be submitted after completion of experiment and get it corrected
with the concerned lab faculty.
If a student is absent for any lab, they need to be completed the same experiment in
the free time before attending next lab.
Step1: Students have to write the date, aim, Software & Hardware requirements for that
experiment in the observation book.
Step2: Students have to listen and understand the experiment explained by the faculty and
note down the important points in the observation book.
Step3: Students need to write procedure/algorithm in the observation book.
Step4: Analyze and Develop/implement the logic of the program by the student in respective
platform
Step5: after approval of logic of the experiment by the faculty then the experiment has to be
executed on the system.
Step6: After successful execution the results are to be shown to the faculty and noted the
same in the observation book.
Step7: Students need to attend the Viva-Voce on that experiment and write the same in the
observation book.
Step8: Update the completed experiment in the record and submit to the concerned faculty in-
charge.
Instructions to maintain the record
Before start of the first lab they have to buy the record and bring the record to the lab.
Regularly (Weekly) update the record after completion of the experiment and get it
corrected with concerned lab in-charge for continuous evaluation.
In case the record is lost inform the same day to the faculty in charge and get the new
record within 2 days the record has to be submitted and get it corrected by the faculty.
If record is not submitted in time or record is not written properly, the evaluation
marks (5M) will be deducted.
Record 5 Marks
Total marks for lab internal are 25 Marks as per Autonomous (JNTUH.)
These 25 Marks are distributed as:
Average of day to day evaluation marks: 15 Marks
Lab Mid exam: 10 Marks
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
the form of nodes and branches. The data elements present in the structure have Parent-Child
relationship. Closely related information in the parent-child structure is stored together as a 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)
11
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
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.
3
E. F. Codd Rules
1. The Information Rule
All information must be store in table as data values.
2. The Rule of Guaranteed Access
Every item in a table must be logically addressable with the help of a table name.
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.
4
12. The Non-subversion Rule
If a RDBMS supports a lower level language then it should not bypass any
reused is the fundamental of the OOP’s concept. So we can say Oracle8 is supported Object
Relational model, Object - oriented model both. Oracle products are based on a concept known as
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:
Controlled availability
5
Compatibility
Connectivity
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.
The server executes the ORACLE software and handles the functions required for concurrent,
shared data access to ORACLE database.
6
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.
7
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
Bus No
Bus
Reservation (Entity)
Contact No Bus 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
8
Passenger:
Contact NO
Age
Sex
PNR NO
Name
Ticket No
Passenger
Cancellation (Entity)
Contact No
PNR NO
Cancellation
9
Concept design with E-R Model:
10
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.
WORKSHEET
Weekly Evaluation
12
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.
13
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 type of
information thattable will hold to the database. For example, the column Empno holds numeric
char(Size) Stores fixed-length character data of length size characters or bytes, depending
on the choice of national character set. Maximum size if determined by the number of bytes
required storing each character with an upper limit of 2000 bytes. Default and minimum size is 1
character or 1 byte, depending on the character set.
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
predefine format of Date data type is DD-MON-YYYY.
14
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.
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)
15
Reservation:
COLUMN NAME DATA TYPE CONSTRAINT
No-of-seats integer(8)
Address varchar2(50)
Ticket:
COLUMN NAME DATA TYPE CONSTRAINT
16
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
17
WEEK-2
Step1 1
Make sure you already downloaded the MySQL essential 5.0.45 win32.msi file. Double click
on the .msi file.
Step2 2
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.
18
Step3 3
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 4
19
Step5 5
The program features you selected are being installed. Please wait while the setup wizard
installs MySQL 5.0. This may take several minutes.
20
Step6
To continue, click next.
Step7 7
To continue, click next.
Step8 8
Wizard Completed. Setup has finished installing MySQL 5.0. Check the configure the MySQL
server now to continue. Click Finish to exit the wizard
21
d.
Step9 9
The configuration wizard will allow you to configure the MySQL Server 5.0 server instance.
Step10 10
Select a standard configuration and this will use a general purpose configuration for the
22
server that can be tuned manually. To continue, click next.
Step11
11
Check on the install as windows service and include bin directory in windows path. To
continue, click next.
Step12 12
23
Please set the security options by entering the root password and confirm retype the password.
continue, click next.
13
Step13
Ready to execute? Clicks execute to continue.
Step14 14
Processing configuration in progress.
24
Step15 15
Configuration file created. Windows service MySQL5 installed. Press finish to close the
wizard.
25
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:
26
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.
27
Example 2:Create a BOATS table with Fields(BID,BNAME,COLOR )and display using
DESCRIBE command
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 )
28
TEST OUTPUT
Example1:
SQL>ALTER TABLE SAILOR ADD (SNO NUMBER(10));
TEST OUTPUT
3. RENAME A TABLE
TEST OUTPUT
4. TRUNCATE A TABLE
TEST OUTPUT
5. DROP A TABLE
29
TEST OUTPUT
VIVA QUESTIONS
Weekly Evaluation
30
WEEK-4
DML COMMANDS
SYNTAX
Example:
TEST OUTPUT:
TEST OUTPUT
31
c. Elimination of duplicates from the select statement
TEST OUTPUT
WHERE searchcondition;
TEST OUTPUT
32
Example2: Display Data From BOATS 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:
33
TEST OUTPUT:
UPDATE
SQL>UPDATE tablename
WHERE somecolumn=somevalue;
TEST OUTPUT
34
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
TEST OUTPUT
VIVA QUESTIONS
Weekly Evaluation
35
WEEK-5
KEY CONSTRAINTS
Test Output:
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) );
36
Test Output
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
37
VIVA QUESTIONS
1) Difference between UNIQUE and PRIMARY KEY
2) When do you use Composite Primary key?
3) Difference between Candidate Key & Primary Key
4) What is the Prerequisite for a key to be used as a Foreign Key
5) What is a Referential Integrity?
6) Give Two practical examples for Referential Integrity?
Weekly Evaluation
38
WEEK-6
2. SUM:
SYNTAX:
Select SUM ([<distinct>/<ALL]<n>)
INPUT SQL>
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>)
INPUT SQL>
Find average of rating of all sailors?
39
Select avg(S.rating )from sailors S;
TEST RESULT:
4. MINIMUM(MIN):
SYNTAX:
Select MIN ([<distinct>/<ALL]<expr>)
INPUT SQL>
5. MAXIMUM(MAX):
SYNTAX:
Select MAX ([<distinct>/<ALL]<expr>)
INPUT SQL>
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
40
2) SYNTAX :Floor()
Ex: Select floor(10.5);
test output
3) SYNTAX mod()
Ex: select mod(17,5);
test output
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
41
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:
:
AND Operator:
SQL> select * from emp_master where salary > 5000 and comm < 750 ;
Test Output:
42
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:
43
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:
Example:
SQL>select rtrim(‘azuretrim’,’trim’) from dual;
Test Output:
44
6) Translate:
7) Replace:
Syntax:Replace(string, searchstring, replacestring)
Example:
SQL> select replace(‘jack and jue’,’j’,’bl’) from dual;
Test Output:
8) Substr:
Example:
SQL>select substr (‘azuretechnology’,4,6) from dual;
Test Output:
9) Char:
Syntax: Char(number)
45
Test Output:
Example:
SQL>select char(65) from dual;
Test Output:
Syntax: Lpad(String,length,pattern)
Example:
Sql > select lpad(‘Welcome’,15,’*’) from dual;
Test Output
12) Length:
Syntax:Length(string)
Example:
SQL>select length(‘azure’) from dual;
Test Output:
46
13) Concatenation ( || ) Operator:
Syntax: Concat(string1,string2)
SQL> select concat(‘Azure’,’ Technology’) from dual;
Test Output.
VIVA QUESTIONS
1) What are the different Aggregate Function?
2) Can we use Multiple Aggregate Functions in a Single Query?
3) Can we use Aggregate Functions in Mathematical Calculations?
4) Name any Five String Functions and explain their operations?
5) What do the % & Underscore symbols represent in a LIKE Operator.
Weekly Evaluation
47
WEEK-7
NESTED QUERIES
Nested Query is a query that has another query embedded within it.
I) IN- is an operator which allows us to check whether a value is present in a given
set of elements
Example1: Find the Names of Sailors who have reserved boats no:103
Select S.name
From Sailors S
Where S.sid IN (select R.sid
from reserves R
where R.bid= 103);
Test Output
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
48
where B.color=’red’))
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’);
Test Output
49
Example3: Practice with your own Query:
Test Output
SYNTAX
Test Output
Test Output
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:
51
Viva Questions
1) Explain the flow of execution for a Nested query
2) Differentiate between flow of execution in Nested Query and Correlated Query?
3) What happens if we eliminate HAVING clause in a query which is having both
GROUP BY and HAVING clauses.
4) What are the different types of Nested Queries?
5) What are the different types of Correlated Queries?
Weekly Evaluation
52
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.
53
Example:
SQL>Create View EmpView As Select * from Employee;
View created.
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);
SQL>Update Emp_vw set Deptno=30 where Empno=1125;
1 row updated.
Test Output:
Test Output:
54
DESTROYING A VIEW:
Syntax: Drop View <View_Name>;
Example:
SQL>Drop View Emp_Vw;
Test Output:
VIVA QUESTIONS
1. Define view.
2. What is the need of a view?
3. List out the advantages of views.
4. What is the syntax for creating a view?
5. How can you insert data into a view?
6. How can you update data into from a view?
7. What is the syntax for deleting a view?
8. List out the criteria for updatable views.
9. What is the syntax for renaming the columns of a view?
10. List reasons for implementing views.
Weekly Evaluation
55
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
The INNER JOIN keyword return rows when there is at
least one match in both tables.
Test Output
56
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.
FROM Orders
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;
57
TEST OUTPUT
OUTER JOIN
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
TEST OUTPUT
UNION
Syntax
Select attribute from table_name union select attribute from table_name;
Example: Select name from sailors union select bname from boats;
TEST OUTPUT
TEST OUTPUT
58
UNION ALL
Select rsid from reserve union all select sid from sailors;
TEST OUTPUT
Viva Questions
1) What is Join?
2) What is the difference between Inner Join & Outer Join.
3) What are the prerequisites for any two tables to apply a Join?
4) Give any two practical examples where we use joins?
5) Differentiate between UNION and UNIONALL
Weekly Evaluation
59
WEEK-10
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.
Show triggers;
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.
60
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 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
Sample:
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)
Write a Query:
61
TEST OUTPUT
Note:when ever there is insert operation that value in the sal variable increases
62
VIVA QUESTIONS
Weekly Evaluation
63
WEEK-11
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 //
64
with in out parameter:
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;
//
update account set sal=5000 where name='raju';
//
select * from account;
commit;
65
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
66
WEEK-12
PL/SQL
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.
67
TEST OUTPUT
TEST OUTPUT
TEST OUTPUT
69
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
70
WEEK-13
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 command
*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;
TEST OUTPUT
* 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”
VIVA QUESTIONS
Weekly Evaluation
72
CASESTUDY 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
73
74
Weekly Evaluation
75
CASESTUDY 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.)
76
WORK SHEET
77
Weekly Evaluation
78
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.
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
79
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
80
81
Weekly Evaluation
82
83
84
85
86
87