Lab Manual Ad Bms

download Lab Manual Ad Bms

of 24

Transcript of Lab Manual Ad Bms

CourseCodeCourseNameTeaching SchemeCredits Assigned

TheoryPracticalTutorialTheoryPractical/OralTutorialTotal

TEITC504AdvancedDatabase Management Systems04Hr/week02Hr/week---0401---05

Course Code

Course NameExamination Scheme

Theory Marks

TermWork

Practical

Oral

Total

Internal assessmentEnd Sem. Exam

Test1Test2Avg. of 2Tests

TEITC504AdvancedDatabase Management Systems

20

20

20

80

25

---

25

150

Course Objectives:1. To reinforce and strengthen the database concepts learned in the basic course in database technologies

2. To impart skills that can help design and implement advanced queries using StructuredQuery Language.

3. To equip students with knowledge to implement and integrate databases in actual applications.

4. To make students aware of how databases are actually stored and accessed.

5. To introduce advanced concepts of transaction management and recovery techniques.

6. To initiate awareness about the potential security threats that exist in database systems and how to tackle them

7. To introduce other database models like distributed and object based

8. To create awareness of how enterprise can organize and analyze large amounts of databy creating a Data Warehouse.

Course Outcomes: At the end of the course the student will be able to:

1. Construct complex queries using SQL to retrieve and manipulate information in a database.

2. Design and implement full-fledged real life applications integrated with database systems.

3. Clearly understand how databases are actually stored and accessed; How transactionACID properties are maintained and how a database recovers from failures.

4. Apply security controls to avoid any type of security incidents on vital database systems.

5. Design advanced data systems using Object based systems or Distributing databases for better resource management.

6. Understand the importance of enterprise data and be able to organize data to perform analysis on the data and take strategic decisions.

DETAILED SYLLABUS

Sr.No.ModuleDetailed ContentHoursWeightage

1

IntroductionReviewing basic concepts of a relationaldatabase, Basic SQL010%

2

AdvancedSQLComplex Retrieval Queries using Group By,Recursive Queries, nested Queries ; Specifying Constraints as Assertions; Event Condition Action (ECA) model (Triggers) in SQL; Creating and working with Views in SQL; Database Programming: Embedded SQL, Dynamic SQL and SQLJ, Database Programming with Function Calls: JDBC; Stored Procedures in SQL, Embedded SQL, Dynamic SQL.0610%

3

Advanced Transaction Processing & RecoveryReview of ACID properties and Serializability;Multiversion Concurrency Control Techniques; Granularity of Data Items and Multiple Granularity Locking ; Advanced Database Recovery techniques like Write Ahead Logging (WAL), ARIES, Checkpoints.0610%

4

Data SecurityIntroductiontoDatabaseSecurityIssues;DiscretionaryAccessControlBasedon Granting and Revoking Privileges; Mandatory Access Control and Role-Based Access Control forMultilevelSecurity;SQL Injection; Introduction to Statistical Database Security Introduction to Flow Control0410%

5

Storage andIndexingOperation on Files; hashing Techniques; Typesof Single-Level Ordered Indexes; Multilevel Indexes; Dynamic Multilevel Indexes Using B- Trees and B+-Trees; Indexes on Multiple Keys.0410%

6

DistributedDatabasesTypesofDistributedDatabaseSystems; DistributedDatabase Architectures; Data Fragmentation, ReplicationandAllocationTechniquesfor Distributed Database Design; Query Processing andOptimizationinDistributedDatabases; Overviewof TransactionManagement in DistributedDatabases; Overviewof ConcurrencyControland Recovery in Distributed Databases.0610%

7

Object BasedDatabasesOverviewofObjectDatabaseConcepts;Object-Relational Features; Object DatabaseExtensionstoSQL;TheObject Definition Language ODL; Object Database ConceptualDesign; TheObjectQuery Language OQL.0510%

8

Introduction to DataThe Need for Data Warehousing; IncreasingDemand for Strategic Information; Inability of Past Decision Support System; Operational Vs DecisionalSupportSystem;1.3Data025%

WarehousingWarehouseDefined;BenefitsofDataWarehousing ;

Features of a Data Warehouse; The Information FlowMechanism;Role ofMetadata; Classification of Metadata; Data Warehouse Architecture; Different Types ofArchitecture; DataWarehouseandDataMarts;Data Warehousing Design Strategies.

9

DimensionalModelingDataWarehouseModelingVsOperationalDatabase Modeling; Dimensional Model Vs ER Model; Features of a Good Dimensional Model; The Star Schema; How Does a Query Execute? TheSnowflakeSchema;FactTablesand Dimension Tables:; he Factless Fact Table; Updates To Dimension Tables: Slowly Changing Dimensions, Type 1 Changes, Type 2 Changes, Type 3 Changes, Large Dimension Tables, Rapidly Changing or Large Slowly Changing Dimensions, Junk Dimensions, Keys in the Data Warehouse Schema, Primary Keys, Surrogate Keys & Foreign Keys; Aggregate Tables; Fact Constellation Schema or Families of Star.0615%

10

ETL ProcessChallenges in ETL Functions; Data Extraction;Identification of Data Sources; Extracting Data: ImmediateDataExtraction, DeferredData Extraction; Data Transformation: Tasks Involved inDataTransformation,DataLoading: Techniques of Data Loading, Loading the Fact Tables and Dimension Tables Data Quality; Issues in Data Cleansing.0410%

11

Online Analytical Processing (OLAP)Need for Online Analytical Processing; OLTPvsOLAP;OLAPandMultidimensional Analysis;Hypercubes;OLAP Operations in Multidimensional Data Model; OLAP Models: MOLAP, ROLAP, HOLAP, DOLAP;0410%

Text Books:

1. Elmasri and Navathe, Fundamentals of Database Systems, 6th Edition, PEARSON Education.2. Korth, Slberchatz,Sudarshan, :Database System Concepts, 6th Edition, McGraw Hill

3. Theraja Reema, Data Warehousing, Oxford University Press, 2009

References:

1. Paulraj Ponniah, Data Warehousing: Fundamentals for IT Professionals, Wiley India.

2. C. J. Date, A. Kannan, S. Swamynathan An Introduction To Database Systems, 8th

Edition Pearson Education.

3. Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems 3rd

Edition - McGraw Hill

4. Ralph Kimball, Margy Ross, The Data Warehouse Toolkit: The Definitive Guide To

Dimensional Modeling, 3rd Edition. Wiley India.

Oral Exam:

An oral exam will be held based on the above syllabus.

Term work:

Assign a case study for group of 2/3 students and each group to perform the following experiments on their case-study:

Suggested Practical List

1. Problem Definition and draw ER /EER diagram

2. Creation of the database: using constrains and triggers

3. Advanced SQL must cover Views, nested and recursive queries.

4. Implementing an application and integrating with the database using JDBC, Dynamic and embedded SQL5. Any one Database Hashing technique

6. Implementing and index using B or B+ trees.7. Creating and querying an Object database. Use ODL and OQL ( Paper Exercise- Assignment)8. Implementing a Distributed Database.

9. Demonstration of database security techniques SQL injection, inference attacks etc.

10. Problem Definition for a Data Warehouse, Construction of Star Schema Model.

11. Creation of a DW and running OLAP operations on them ( Roll up, Drill down, Slice, Dice, pivot)

Tools used:1. Any Database software like Oracle, DB2, SQL Server, MY SQL or any other open source tools.

2. Programming to be done in JAVA.

Theory Examination:1. Question paper will comprise of 6 questions, each carrying 20 marks.

2. Total 4 questions need to be solved.

3. Q.1 will be compulsory, based on entire syllabus wherein sub questions of 2 to 3 marks will be asked.

4. Remaining question will be randomly selected from all the modules.

5. Weightage of marks should be proportional to number of hours assigned to each module.

1. Create a query to display the last name, salary, and commission for all employees who earn commissions. Sort the data in descending order of salary and commissions2. Create a query to display the last name of all employees where the third letter of the name is an a.3. Create a query to display the last name of all the employees who have an a and an e in their last names.4. Create a query to display the last name, job title, and salary for all employees whose job is sales representative or stock clerk and whose salary is not equal to $2500, $3500, or $7000.5. Single row queries6. Write a query to display the current date. Label the column Date7. Create a query to display the employee number, last name, salary, and salary increased by 15% and In the above query add a column that subtracts the old salary from the new salary. Label the column Increase.expressed as a whole number. Label the column New Salary8. Write a query that displays the employees last name with the first letters capitalized and all other letters lowercase, and the length of the names, for all employees whose name starts with J, A, or M. Give each column an appropriate label. Sort the result by the employees last names.

with emps as(select deptno empno -- the department nodes; the referenced key simulates the EMP key, dname ename, -1 mgr -- the reference to parent nodes; not applicable to DEPT nodesfrom deptunionselect empno -- the highest-level employee nodes, the link between DEPT and EMP nodes, ename, deptno mgr -- this interface layer, bridge between EMP and DEPT nodes, uses its DEPT references as a simulated MGR Parent-node referencefrom empwhere job ='MANAGER'or mgr is nullunionselect empno -- all EMP-nodes, ename, mgrfrom emp)select lpad(' ', level*3)||ename enamefrom empsconnectby prior empno = mgrstartwith mgr = -1/

Output ACCOUNTING CLARK MILLER KING JONES SCOTT ADAMS FORD SMITH TURNER MARTIN BLAKE ALLEN WARD JAMES CLARK MILLER RESEARCH SALES BLAKE ALLEN WARD JAMES OPERATIONS

24 rows selected.

with emps as(select deptno empno -- the department nodes; the referenced key simulates the EMP key, dname ename, -1 mgr -- the reference to parent nodes; not applicable to DEPT nodes, null markerfrom deptunionselect empno -- the highest-level employee nodes, the link between DEPT and EMP nodes, ename, deptno mgr -- this interface layer, bridge between EMP and DEPT nodes, uses its DEPT refe, case when ename like '%A%' then 'X' end markerfrom empwhere job ='MANAGER'or mgr is nullunionselect empno -- all EMP-nodes, ename, mgr, case when ename like '%A%' then 'X' end markerfrom emp), tree_nodes as(select distinct ename, empno, mgrfrom empsconnectby PRIOR mgr=empno -- note that the connect by condition is exactly the reverse of the onestartwith marker is not null)select lpad(' ' , level * 4)||enamefrom tree_nodesconnect by prior empno = mgrstart with mgr = -1/

LPAD('',LEVEL*4)||ENAME-------------------------------------------------------------------------------- ACCOUNTING CLARK KING BLAKE ALLEN JAMES WARD CLARK JONES FORD SMITH TURNER MARTIN SCOTT ADAMS SALES BLAKE ALLEN JAMES WARD

For internal exceptions, SQLCODE returns the number of the associated Oracle error. The number that SQLCODE returns is negative unless the Oracle error is no data found, in which case SQLCODE returns +100. For user-defined exceptions, SQLCODE returns +1, or a value you assign if the exception is associated with an Oracle error number through pragma EXCEPTION_INIT.The function SQLERRM returns the error message associated with its error-number argument. If the argument is omitted, it returns the error message associated with the current value of SQLCODE. SQLERRM with no argument is useful only in an exception handler. Outside a handler, SQLERRM with no argument always returns the normal, successful completion message. For internal exceptions, SQLERRM returns the message associated with the Oracle error that occurred. The message begins with the Oracle error code.

DECLARE name emp.ename%TYPE; v_code NUMBER; v_errm VARCHAR2(64);BEGIN SELECT ename INTO name FROM emp WHERE empno = 900; EXCEPTION WHEN OTHERS THEN v_code := SQLCODE; v_errm := SUBSTR(SQLERRM, 1 , 64); DBMS_OUTPUT.PUT_LINE('The error code is ' || v_code || '- ' || v_errm);END;

DECLARE emp_rec emp%rowtype; CURSOR emp_cur IS SELECT * FROM emp WHERE sal > 10; BEGIN OPEN emp_cur; FETCH emp_cur INTO emp_rec; dbms_output.put_line (emp_rec.empno || ' ' || emp_rec.ename); CLOSE emp_cur; END; Declare cursor c1 is select empno,sal from emp where deptno=10; eno emp.empno%type; salary emp.sal%type;begin open c1; loop fetch c1 into eno,salary; exit when c1%notfound; update emp set sal =salary +100 where eno=emp.empno; insert into raise values(eno,sysdate,salary) ; end loop; commit; close c1; end;---------------------------------------------------------------------------------------------------------------------------- Declare cursor c1 is select empno,sal from emp where deptno=10; eno emp.empno%type; salary emp.sal%type; begin open c1; loop fetch c1 into eno,salary; if c1%found then update emp set sal =salary -100 where eno=emp.empno; insert into raise values(eno,sysdate,salary) ; else exit; end if; end loop; commit; close c1; end;

DECLARE Cursor c1 is select empno,sal from emp where deptno=10; eno emp.empno%type; salary emp.sal%type;BEGIN open c1; If c1%isopen then Loop fetch c1 into eno,salary; exit when c1%notfound; update emp set sal =salary +100 where eno=emp.empno; insert into raise values(eno,sysdate,salary) ; End loop; commit; close c1; Else dbms_output.put_line('Cant open C1'); End if;END;_____________________________________________________________________________________

DECLARE Cursor c1 is select empno,sal from emp where deptno=10; BEGIN For emp_rec in c1 Loop Update emp set sal =emp_rec.sal +100 where empno=emp_rec.empno; Insert into raise values(emp_rec.empno,sysdate,emp_rec.sal+100) ; End loop; commit; END;

DECLARE var_salary number(6); var_emp_id number(6) := 7900; BEGIN SELECT sal INTO var_salary FROM emp WHERE empno = var_emp_id; dbms_output.put_line(var_salary); dbms_output.put_line('The employee ' || var_emp_id || ' has salary ' || var_salary); END;Scope of VariableDECLARE var_num1 number; var_num2 number; var_mult number:=123; BEGIN var_num1 := 100; var_num2 := 200; DECLARE var_mult number; BEGIN var_mult := var_num1 * var_num2; dbms_output.put_line(var_mult); END; dbms_output.put_line(var_mult); END;

Representing Hierarchical Information

Let's look at an example to understand how we can represent hierarchical information in a relational database. As a basis for the example, we'll use an organization chart showing how one employee reports to another within a large organization, as shown in Figure 8-1.

An organization chart

Figure 8-1 represents a hierarchy of employees. The information regarding an employee, his manager, and the reporting relationship need to be represented in one table, employee, as shown in the Entity Relationship Diagram in Figure 8-2.Figure 8-2. The reporting relationship

Here the employee table refers to itself. The column manager_emp_id refers to the emp_id column of the same table. To represent hierarchical data, you need to make use of a relationship such as when one column of a table references another column of the same table. When such a relationship is implemented using a database constraint, it is known as self-referential integrity constraint. The corresponding CREATE TABLE statement will look as follows:

CREATE TABLE employee (

emp_id NUMBER (4) CONSTRAINT emp_pk PRIMARY KEY,

fname VARCHAR2 (15) NOT NULL,

lname VARCHAR2 (15) NOT NULL,

dept_id NUMBER (2) NOT NULL,

manager_emp_id NUMBER (4) CONSTRAINT emp_fk REFERENCES employee(emp_id),

salary NUMBER (7,2) NOT NULL,

hire_date DATE NOT NULL,

job_id NUMBER (3));

As a basis for the examples in this chapter, we'll use the following sample data:SELECT emp_id, lname, dept_id, manager_emp_id, salary, hire_date

FROM employee;

EMP_ID LNAME DEPT_ID MANAGER_EMP_ID SALARY HIRE_DATE

--------- ---------- --------- -------------- --------- ---------

7369 SMITH 20 7902 800 17-DEC-80

7499 ALLEN 30 7698 1600 20-FEB-81

7521 WARD 30 7698 1250 22-FEB-81

7566 JONES 20 7839 2000 02-APR-81

7654 MARTIN 30 7698 1250 28-SEP-81

7698 BLAKE 30 7839 2850 01-MAY-80

7782 CLARK 10 7839 2450 09-JUN-81

7788 SCOTT 20 7566 3000 19-APR-87

7839 KING 10 5000 17-NOV-81

7844 TURNER 30 7698 1500 08-SEP-81

7876 ADAMS 20 7788 1100 23-MAY-87

7900 JAMES 30 7698 950 03-DEC-81

7902 FORD 20 7566 3000 03-DEC-81

7934 MILLER 10 7782 1300 23-JAN-82

The employee table has two important aspects: The column manager_emp_id The emp_fk constraintThe column manager_emp_id stores the emp_id of the employee's manager. For example, the manager_emp_id for Smith is 7902, which means that Ford is Smith's manager. The employee King doesn't have a manager_emp_id, which indicates that King is the uppermost employee. To be able to represent the uppermost employee, the manager_emp_id column must be nullable.There is a foreign key constraint on the manager_emp_id column. This enforces the rule that any value put in the manager_emp_id column must be the emp_id of a valid employee. Such a constraint is not mandatory when representing hierarchical information. However, it is a good practice to define database constraints to enforce such business rules.Before moving on to the following sections on manipulating hierarchies, we will introduce some hierarchy terminology. The following list defines terms that we'll use often when working with hierarchical data:

NodeA row in a table that represents a specific entry in a hierarchical tree structure. For example, in Figure 8-1 each employee is considered to be a node.

ParentA node that is one level up in a tree. In Figure 8-1, King is the parent of Blake, and Blake is the parent of Martin. The term parent node is sometimes used in place of just parent.

ChildA node that is one level down in a tree. In organization chart, Blake is a child of King. Blake, in turn, has five children: Allen, Ward, Martin, Turner, and James. The term child node is sometimes used in place of just child.

Root The uppermost node in a hierarchical structure. The definition of a root is that it has no parent. In Figure 8-1, King is the root. You can have only one root in any given tree, but it's worth noting that you can have multiple trees in a hierarchical table. If our employee table stored information on employees from multiple companies, we would have one root per company. The term root node is sometimes used in place of root.

LeafA node with no children, and sometimes called a leaf node. Leaf nodes are the antitheses of root nodes, and represent the lowest levels of a tree structure. The leaf nodes in Figure 8-1 are Adams, Smith, Allen, Ward, Martin, Turner, James, and Miller. Leaf nodes do not all need to be at the same level, but they do need to be without children.

LevelA layer of nodes. In organization chart , King constitutes one level. Jones, Blake, and Clark constitute the next level down, and so forth.

------------------------------------------------------------------------------------------------------------------------------------------Decode Example

SELECT employee_id, DECODE(manager_id, NULL, 'HEAD HONCHO', 'WORKER BEE') emp_type FROM employees

PL/SQ\\\

L allows using one loop inside another loop. Following section shows few examples to illustrate the concept.The syntax for a nested basic LOOP statement in PL/SQL is as follows:LOOP Sequence of statements1 LOOP Sequence of statements2 END LOOP;END LOOP;The syntax for a nested FOR LOOP statement in PL/SQL is as follows:FOR counter1 IN initial_value1 .. final_value1 LOOP sequence_of_statements1 FOR counter2 IN initial_value2 .. final_value2 LOOP sequence_of_statements2 END LOOP;END LOOP;The syntax for a nested WHILE LOOP statement in Pascal is as follows:WHILE condition1 LOOP sequence_of_statements1 WHILE condition2 LOOP sequence_of_statements2 END LOOP;END LOOP;DECLARE i number(3); j number(3);BEGIN i := 2; LOOP j:= 2; LOOP exit WHEN ((mod(i, j) = 0) or (j = i)); j := j +1; END LOOP; IF (j = i ) THEN dbms_output.put_line(i || ' is prime'); END IF; i := i + 1; exit WHEN i = 50; END LOOP;END;DECLARE i number(1); j number(1);BEGIN > FOR i IN 1..3 LOOP > FOR j IN 1..3 LOOP dbms_output.put_line('i is: '|| i || ' and j is: ' || j); END loop inner_loop; END loop outer_loop;END;DECLARE name varchar2(20); company varchar2(30); introduction clob; choice char(1); BEGIN name := 'John Smith'; company := 'Infotech'; introduction := ' Hello! I''m John Smith from Infotech.'; choice := 'y'; IF choice = 'y' THEN dbms_output.put_line(name); dbms_output.put_line(company); dbms_output.put_line(introduction); END IF; END;Write the PL/SQL code to input the emps no and increase the salary by 10% if his salary < 5000 otherwise delete the record.DECLAREENO NUMBER;SALARY NUMBER;BEGINENO := &EMPNO;SELECT SALARY INTO SAL FROM EMP WHERE EMPNO = ENO;IF SALARY < 5000 THENUPDATE EMP SET SAL = SAL + SAL *.1 WHERE EMPNO = ENO;DBMS_OUTPUT.PUT_LINE(SALARY UPDATE);ELSEDELETE FROM EMP WHERE EMPNO = ENO;DBMS_OUTPUT.PUT_LINE(RECORD DELETED); END IF;END;

Conditional Predicates for Detecting Triggering DML StatementThe triggering event of a DML trigger can be composed of multiple triggering statements. When one of them fires the trigger, the trigger can determine which one by using these conditional predicates:Conditional PredicateTRUE if and only if:

INSERTINGAn INSERT statement fired the trigger.

UPDATINGAn UPDATE statement fired the trigger.

UPDATING ('column_name')An UPDATE statement statement that affected the specified column fired the trigger.

DELETINGA DELETE statement fired the trigger.

A conditional predicate can appear wherever a BOOLEAN expression can appear.Creates a DML trigger that uses conditional predicates to determine which of its four possible triggering statements fired it. Trigger that Uses Conditional Predicates to Detect Triggering StatementCREATE OR REPLACE TRIGGER t BEFORE INSERT OR UPDATE OF salary OR UPDATE OF department_id OR DELETE ON employeesBEGIN CASE WHEN INSERTING THEN DBMS_OUTPUT.PUT_LINE('Inserting'); WHEN UPDATING('salary') THEN DBMS_OUTPUT.PUT_LINE('Updating salary'); WHEN UPDATING('department_id') THEN DBMS_OUTPUT.PUT_LINE('Updating department ID'); WHEN DELETING THEN DBMS_OUTPUT.PUT_LINE('Deleting'); END CASE;