0% found this document useful (0 votes)
60 views10 pages

DBMS Scheme CIE 2 5th Sem

dbms

Uploaded by

Vivek Naik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views10 pages

DBMS Scheme CIE 2 5th Sem

dbms

Uploaded by

Vivek Naik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

®

RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


&
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Test – 2 set2-Scheme

Sem IV (CSE/ISE) Subject Title Database Management and


System
Sub Code 18CS53 Name of the Faculties Mr. Deepak D J , Mrs. Rachana M
S

Date: 22-12-2021 Time: 9:30 to 11:00 AM Max. Marks: 50

Q. Question Marks
No
1. a. Explain the steps to convert basic ER model to relational database schema 05
● Entity Sets to Tables
● Relationship Sets (without Constraints) to Tables
● Translating Relationship Sets with Key Constraints
● Translating Relationship Sets with Participation Constraints
● Translating Weak Entity Sets
● Translating Class Hierarchies
● Translating ER Diagrams with Aggregation

b. Discuss equijoin and natural join with suitable examples using relational algebra 05
notations
EQUIJOIN Operation
■ The most common use of join involves join conditions with equality
comparisons only
■ Such a join, where the only comparison operator used is =, is called an
EQUIJOIN.
■ In the result of an EQUIJOIN we always have one or more pairs of
attributes (whose names need not be identical) that have identical values
in every tuple.

Example: To get the manager’s name, we need to combine each DEPARTMENT tuple
with the EMPLOYEE tuple whose SSN value matches the MGRSSN value in the
department tuple.
NATURAL JOIN Operation
■ Another variation of JOIN called NATURAL JOIN — denoted by * — was
created to get rid of the second (superfluous) attribute in an EQUIJOIN
condition.
■ because one of each pair of attributes with identical values is superfluous
■ The standard definition of natural join requires that the two join attributes, or
each pair of corresponding join attributes, have the same name in both relations

Example: To apply a natural join on the DNUMBER attributes of DEPARTMENT


and DEPT_LOCATIONS, it is sufficient to write:
■ DEPT_LOCS ← DEPARTMENT * DEPT_LOCATIONS
■ Only attribute with the same name is DNUMBER

2. Consider the following COMPANY database 05


EMP(Name,SSN,Salary,SuperSSN,Gender,Dno)
DEPT(DNum,Dname,MgrSSN,Dno)
DEPT_LOC(Dnum,Dlocation)
DEPENDENT(ESSN,Dep_name,Sex)
WORKS_ON(ESSN,Pno,Hours)
PROJECT(Pname,Pnumber,Plocation,Dnum)
Write the “Relational Algebra Expressions” for the following
(i)Retrieve the name, address, salary of employees who work for the Research department.
(ii) find the names of employees who work on all projects controlled by department number
4.
iii) Retrieve the SSN of all employees who either in department no :4 or directly supervise an
employee who work in department number :4
(iv) Retrieve the names of employees who have no dependents
(v) Retrieve each department number, the number of employees in the department and their 10
average salary.

Solution :
i)

ii)

iii)
iv)

v)

3. Explain the following constructs used in SQL with example: 10


(i)Nested queries ii)Assertions iii) Triggers iv)Views v) Schema change statements

Nested Queries:
Some queries require that existing values in the database be fetched and then used in a
comparison condition. Such queries can be conveniently formulated by using nested
queries, which are complete select-from-where blocks within another SQL query. That
other query is called the outer query. These nested queries can also appear in the
WHERE clause or the FROM clause or the SELECT clause or other SQL clauses as
needed.
Example : To Retrieve the name of each employee who has a dependent with the same
first name and is the same sex as the employee
SELECT E.Fname, E.Lname
FROM EMPLOYEE AS E
WHERE E.Ssn IN
( SELECT D.Essn FROM DEPENDENT AS D WHERE E.Fname =
D.Dependent_name AND E.Sex = D.Sex );

Assertions
which can be used to specify additional types of constraints that are outside the scope
of the built-in relational model constraints (primary and unique keys, entity integrity,
and referential integrity)
These built-in constraints can be specified within the CREATE TABLE statement of
SQL
users can specify general constraints
Each assertion is given a constraint name and is specified via a condition similar to the
WHERE clause of an SQL queryMechanism:
CREATE ASSERTION
Components include:
a constraint name,
followed by CHECK,
followed by a condition
CREATE ASSERTION SALARY_CONSTRAINT
CHECK (NOT EXISTS (SELECT *
FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D
WHERE E.SALARY > M.SALARY AND
E.DNO=D.NUMBER AND D.MGRSSN=M.SSN))

Triggers
In many cases it is convenient to specify the type of action to be taken when certain events
occur and when certain conditions are satisfied.
to monitor a database and take initiate action when a condition occurs
Event
Condition :The condition that determines whether the rule action should be executed
Action : To be taken when the condition is satisfied
CREATE TRIGGER INFORM_SUPERVISOR
BEFORE INSERT OR UPDATE OF
SALARY, SUPERVISOR_SSN ON EMPLOYEE
FOR EACH ROW
WHEN
(NEW.SALARY> (SELECT SALARY FROM EMPLOYEE
WHERE SSN=NEW.SUPERVISOR_SSN))
INFORM_SUPERVISOR (NEW.SUPERVISOR_SSN,NEW.SSN);

Views in SQL
A view is a “virtual” table that is derived from other tables
• SQL command: CREATE VIEW
• a table (view) name
• a possible list of attribute names (for example, when arithmetic operations are
specified or when we want the names to be different from the attributes in the
base relations)
• a query to specify the table contents
CREATE VIEW WORKS_ON_NEW AS
SELECT FNAME, LNAME, PNAME, HOURS
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE SSN=ESSN AND PNO=PNUMBER
GROUP BY PNAME;
Schema change statements
DROP and ALTER
The DROP command can be used to drop named schema elements, such as tables, domains,
types, or constraints.
DROP SCHEMA COMPANY CASCADE;
DROP TABLE DEPENDENT CASCADE;
The definition of a base table or of other named schema elements can be changed by using the
ALTER command.
ALTER TABLE COMPANY.EMPLOYEE ADD COLUMN Job VARCHAR(12);
ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN Address CASCADE;
4. Consider the following schema for Order Database:
SALESMAN(Salesman_id, Name, City, Commission) 10
CUSTOMER(Customer_id, Cust_Name, City, GrADe, Salesman_id)
ORDERS(Ord_No, Purchase_Amt, Ord_Date, Customer_id, Salesman_id)
Write SQL queries to
1. Count the customers with grades above Bangalore’s average.
SELECT GRADE, COUNT (CUSTOMER_ID) FROM CUSTOMER GROUP BY GRADE
HAVING GRADE > (SELECT AVG (GRADE) FROM CUSTOMER WHERE
CITY='BANGALORE');
2. Find the name and numbers of all salesman who had more than one customer.

SELECT S.SALESMAN_ID,NAME FROM CUSTOMER C,SALESMAN S WHERE


S.SALESMAN_ID=C.SALESMAN_ID GROUP BY C.SALESMAN_ID HAVING
COUNT(*)>1

3. List all the salesman and indicate those who have and don’t have customers in their cities
(Use UNION operation.)
SELECT S.SALESMAN_ID,NAME,CUST_NAME FROM SALESMAN S,CUSTOMER C
WHERE S.CITY = C.CITY UNION SELECT SALESMAN_ID,NAME,'NO MATCH'
FROM SALESMAN WHERE NOT CITY = ANY (SELECT CITY FROM CUSTOMER);

4. Create a view that finds the salesman who has the customer with the highest order of a
day.
CREATE VIEW VW_HIGHEST_ORDER AS SELECT
B.ORD_DATE,A.SALESMAN_ID,A.NAME FROM SALESMAN A, ORDERS B WHERE
A.SALESMAN_ID = B.SALESMAN_ID AND B.PURCHASE_AMT=(SELECT
MAX(PURCHASE_AMT) FROM ORDERS C WHERE C.ORD_DATE = B.ORD_DATE);
SELECT * FROM VW_HIGHEST_ORDER

5. Demonstrate the DELETE operation by removing salesman with id 1000. All his orders
must also be deleted.
DELETE FROM SALESMAN WHERE SALESMAN_ID=101;

5. What are the components of the JDBC architecture? Explain the steps required to connect to 10
DBMS through JDBC using an example program.

The architecture of JDBC has four main components: application, driver manager, drivers , and
data source
Steps to submit a database query:
􀂙 Load the JDBC driver
􀂙 Connect to the data source
􀂙 Execute SQL statements

import java. sql . *


Class.forName(“oracle/jdbc.driver.Oracledriver”);
Connection con = // connect
DriverManager.getConnection(url, ”login", ”pass");
Statement stmt = con.createStatement(); // set up stmt
String query = "SELECT name, rating FROM Sailors";
ResultSet rs = stmt.executeQuery(query);
try { // handle exceptions
// loop through result tuples
while (rs.next())
{
String s = rs.getString(“name");
Int n = rs.getFloat(“rating");
System.out.println(s + " " + n);
}
} catch(SQLException ex) {
System.out.println(ex.getMessage ()+ ex.getSQLState () + ex.getErrorCode ());
}

6 Define cursor and explain its properties in embedded SQL with an example program. 10
Cursors provide a mechanism that allows us to retrieve rows one at a time from a relation.
Cursors enable us to examine, in the host language program, a collection of rows computed by
an Embedded SQL statement:
We usually need to open a cursor if the embedded statement is a SELECT query. However, we
can avoid opening a cursor if the answer contains a single row. INSERT, DELETE, and
UPDATE staternents typically require no cursor, although some variants of DELETE and
UPDATE use a cursor.
Properties:
General form:
DECLARE cursomame [INSENSITIVE] [SCROLL] CURSOR
[WITH HOLD]
FOR some query
[ ORDER BY order-item-list ]
[ FOR READ ONLY I FOR UPDATE ]
• A cursor is updatable by default unless it is a scrollable or insensitive cursor , in which
case it is read-only by default.
• SCROLL - the cursor is scrollable, FETCH command can be used to position the cursor
INSENSITIVE - the update command has no effect on the rows fetched
WITH HOLD – cursor is not closed when the transaction is committed.
FETCH Order is unspecified, but the optional ORDER BY clause can be used

Cursor that gets names of sailors who have reserved a red boat, in alphabetical order
EXEC SQL
DECLARE sinfo CURSOR FOR
SELECT S.sname
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’
ORDER BY S.sname
if sinfo is an updatable cursor and open: modifies the rating value of the row currently pointed to
by cursor sinfa
UPDATE Sailors S
SET S.rating = S.rating - 1
WHERE CURRENT of sinfo;
Delete a row
DELETE Sailors S
WHERE CURRENT of sinfo;
Example:
EXEC SQL Connect
char SQLSTATE[6];
EXEC SQL BEGIN DECLARE SECTION
char c_sname[20]; short c_minrating; float c_age;
EXEC SQL END DECLARE SECTION
c_minrating = random();
EXEC SQL DECLARE sinfo CURSOR FOR
SELECT S.sname, S.age FROM Sailors S
WHERE S.rating > :c_minrating
ORDER BY S.sname;
do {
EXEC SQL FETCH sinfo INTO :c_sname, :c_age;
printf(“%s is %d years old\n”, c_sname, c_age);
} while (SQLSTATE != ‘02000’);
EXEC SQL CLOSE sinfo;
7 What is SQLJ? How it is different from JDBC. Explain with an example program. 10

'SQL-Java'
SQLJ having semi-static SQL queries allows the compiler to perform SQL syntax checks,
strong type checks

#sql books = { SELECT title, price INTO :title, :price FROM Books WHERE author = :author
};

SQLJ programs allow direct embedding of Java bind expressions within SQL statements. JDBC
requires separate get and/or set call statements for each bind variable and specifies the binding
by position number. SQLJ provides strong typing of query outputs and return parameters and
allows type-checking on calls

All arguments always bound to the same variable:


#sql = {
SELECT name, rating INTO :name, :rating
FROM Books WHERE sid = :sid;
􀂃 Compare to JDBC:
sid=rs.getInt(1);
if (sid==1)
{sname=rs.getString(2);
}
Else
{ sname2=rs.getString(2);
}
Program to explain SQLJ
Int sid; String name; Int rating;
// named iterator
#sql iterator Sailors(Int sid, String name, Int rating);
Sailors sailors;
// assume that the application sets rating
#sailors = {
SELECT sid, sname INTO :sid, :name
FROM Sailors WHERE rating = :rating
};
// retrieve results
while (sailors.next()) {
System.out.println(sailors.sid + “ “ + sailors.sname));
}
sailors.close();
8 What are stored procedures?. Explain the creating and calling of stored procedures with an 10
example.
● Program executed through a single SQL statement
● that can be locally executed and completed within the process space of the database
server.
● The results can be packaged into one big result and returned to the application
● Stored procedures are also beneficial for software engineering rea,sons.
● Once a stored procedure is registered with the database server, different users can re-use
the stored procedure

CREATE PROCEDURE ShowNumReservations


SELECT S.sid, S.sname, COUNT(*)
FROM Sailors S, Reserves R
WHERE S.sid = R.sid
GROUP BY S.sid, S.sname

EXEC SQL BEGIN DECLARE SECTION


Int sid;
Int rating;
EXEC SQL END DECLARE SECTION
// now increase the rating of this sailor
EXEC CALL IncreaseRating(:sid,:rating);
Or
#sql iterator
ShowSailors(…);
ShowSailors showsailors;
#sql showsailors={CALL ShowSailors};
while (showsailors.next()) {
…}

9 What is a three-tier architecture? What advantages does it offer over single tier and two-tier 10
architectures? Give a short overview of the functionality at each of the three tiers.
There are three different functional components:
1. Data management,
2. Application logic,
3. Presentation.
Presentation tier
▪ Primary interface to the user
▪ Needs to adapt to different display devices (PC, PDA, cell phone, voice access?)
Middle tier
▪ Implements business logic (implements complex actions, maintains state between
different steps of a workflow)
▪ Accesses different data management systems
Data management tier
▪ One or more standard database management systems
Advantages

• Heterogeneous Systems: Applications can utilize the strengths of different platforms


and different software components at the different tiers. It is easy to modify or replace
the code at any tier without affecting the other tiers.
• Thin Clients: Clients only need enough computation power for the presentation layer.
Typically, clients are Web browsers.
• Integrated Data Access: In many applications, the data must be accessed from several
sources. This can be handled transparently at the middle tier, where we can centrally
manage connections to all database systems involved.
• Scalability to Many Clients: Each client is lightweight and all access to the system is
through the middle tier.
• Software Development Benefits: By dividing the application cleanly into parts that
address presentation, data access, and business logic, we gain many advantages.
10 Explain the following with relevant examples and code snippets: 10
a)html forms b)Java scripts C)Servlets

a) html forms
Common way to communicate data from client to middle tier
General format of a form:
<FORM ACTION=“page.jsp” METHOD=“GET” NAME=“LoginForm”>

</FORM>
Components of an HTML FORM tag:
ACTION: Specifies URI that handles the content
METHOD: Specifies HTTP GET or POST method
NAME: Name of the form; can be used in client-side scripts to refer to the form
Example:
<html>
<form method="POST" action="TableOfContents.jsp">
<input type="text" name="userid">
<input type="password" name="password">
<input type="submit" value="Login“ name="submit">
<input type=“reset” value=“Clear”>
</form> </html>

b) Java scripts
Goal: Add functionality to the presentation tier.
Sample applications:
Detect browser type and load browser-specific page
Form validation: Validate form input fields
Browser control: Open new windows, close existing windows (example: pop-up ads)
Usually embedded directly inside the HTML with the
<SCRIPT> … </SCRIPT> tag.
<SCRIPT> tag has several attributes:
LANGUAGE: specifies language of the script (such as javascript)
SRC: external file with script code
Example:
<SCRIPT LANGUAGE=“JavaScript” SRC=“validate.js>
</SCRIPT>

c) Servlets
Java Servlets: Java code that runs on the middle tier . They are platform independent and
Complete Java API including JDBC are available.
Example:
import java.io.*;
import java.servlet.*;
import java.servlet.http.*;

public class ServetTemplate extends HttpServlet { public void doGet(HTTPServletRequest


request,
HTTPServletResponse response) throws SerletExpection, IOException {
PrintWriter out=response.getWriter();
out.println(“Hello World”);
}
}

******

You might also like