Gudlavalleru Engineering College Gudlavalleru Department of Computer Science and Engineering DBMS Lab Manual For Students II B.Tech II Sem R-10
Gudlavalleru Engineering College Gudlavalleru Department of Computer Science and Engineering DBMS Lab Manual For Students II B.Tech II Sem R-10
Gudlavalleru Engineering College Gudlavalleru Department of Computer Science and Engineering DBMS Lab Manual For Students II B.Tech II Sem R-10
4
5 6 7 8 9 10 11 12 13 14 15 16 17 18
Exp No : 1
1. Execute a single line and group functions for a table.
Single-Row Functions
Single-row functions can be nested to any level. Single-row functions can manipulate the following: Character data: LOWER, UPPER, INITCAP, CONCAT, SUBSTR, INSTR, LENGTH Number data: ROUND, TRUNC, MOD Date data: MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND, TRUNC Date values can also use arithmetic operators. Conversion functions can convert character, date, and numeric values: TO_CHAR, TO_DATE, TO_NUMBER There are several functions that pertain to nulls, including NVL, NVL2, NULLIF, and COALESCE. SELECT 'The job id for '||UPPER(last_name)||' is ' ||LOWER(job_id) AS "EMPLOYEE DETAILS" FROM employees; SELECT employee_id, last_name, department_id FROM employees WHERE LOWER(last_name) = higgins; SELECT employee_id, UPPER(last_name), department_id FROM employees WHERE INITCAP(last_name) = Higgins; SELECT employee_id, CONCAT(first_name, last_name) NAME, job_id, LENGTH (last_name), INSTR(last_name, a) "Contains a?" FROM employees WHERE SUBSTR(job_id, 4) = REP; SELECT ROUND(45.923,2), ROUND(45.923,0), ROUND(45.923,-1) FROM DUAL; SELECT TRUNC(45.923,2), TRUNC(45.923), TRUNC(45.923,-2) FROM DUAL; SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS FROM employees WHERE department_id = 90; SELECT employee_id, hire_date, MONTHS_BETWEEN (SYSDATE, hire_date) TENURE,
ADD_MONTHS (hire_date, 6) REVIEW, NEXT_DAY (hire_date, FRIDAY), LAST_DAY(hire_date) FROM employees WHERE MONTHS_BETWEEN (SYSDATE, hire_date) < 36; Types of Group Functions AVG COUNT MAX MIN STDDEV SUM VARIANCE SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) FROM employees WHERE job_id LIKE %REP%; Ex: Write a query to convert null values to zero using NVL function for displaying annual salary. Write a query to display distinct values of DEPTNO and JOB. List the details of the employees in departments 10 and 20 in alphabetical order of names. Display sum of salaries group by job from emp table Display deptno and average salary of all departments having more than 3 employees. List all clerks who earn between 1000 and 2000. Display Name,Job,Annual salary and commission of all sales people whose monthly salary is greater than their commission. List the output order by salary. List the minimum and maximum salary for each job type. Convert the first letter of the ename into capital and remaining small letters Display the first three characters of the ename where job is salesman. Replace a present in the ename with e. Give the total number of people for each department. Display the 60 days before from the hiredate for employee number 7788.. Display each employee name with hiredate and salary review date. Display the system date in the format Wednesday 30 th July 2003. Display 30 th of July 2003 in the date format. List the employee name ,job and salary increased by 15% for employees whose job is Find the employees who earn lowest salary in each department Display employees who earn more than the lowest salary in department 30. Write a query to find employees who earn more than every employee in department 30. Display name, job, and hiredate for employees whose salary is greater than the highest salary in any sales department. Find the employees who earn a salary greater than the average salary for each department .
Exp No : 2
2. Execute DCL and TCL Commands.
DCL Data Control Language (DCL) statements is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it. DCL Commands: Grant, Revoke
GRANT - gives user's access privileges to database REVOKE - withdraw access privileges given with the GRANT command CREATE USER user IDENTIFIED BY password; GRANT privilege [, privilege...] TO user [, user| role, PUBLIC...]; GRANT create session, create table, create sequence, create view TO scott; Grant succeeded. CREATE ROLE manager; Role created. GRANT create table, create view TO manager; Grant succeeded. GRANT manager TO DEHAAN, KOCHHAR; Grant succeeded. GRANT object_priv[(columns)] ON object TO {user|role|PUBLIC} [WITH GRANT OPTION]; REVOKE {privilege [, privilege...]|ALL} ON object FROM {user[, user...]|role|PUBLIC} [CASCADE CONSTRAINTS]; REVOKE select, insert ON departments FROM scott; Revoke succeeded. TCL Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.
TCL Commands:
COMMIT - save work done SAVEPOINT - identify a point in a transaction to which you can later roll back ROLLBACK - restore database to original since the last COMMIT DELETE FROM test; 25,000 rows deleted. ROLLBACK; Rollback complete. DELETE FROM test WHERE id = 100; 1 row deleted. SELECT * FROM test WHERE id = 100; No rows selected. COMMIT; Commit complete. SAVEPOINT Save changes to a point (transactional). Syntax: SAVEPOINT text_identifier Example: UPDATE employees SET salary = 95000 WHERE last_name = 'Smith'; SAVEPOINT justsmith; UPDATE employees SET salary = 1000000; SAVEPOINT everyone; SELECT SUM(salary) FROM employees; ROLLBACK TO SAVEPOINT justsmith; COMMIT; UPDATE... SAVEPOINT update_done; Savepoint created. INSERT... ROLLBACK TO update_done; Rollback complete.
Exp No : 3
3. Create and manipulate various DB objects for a table.
Database Objects An Oracle database can contain multiple data structures. Each structure should be outlined in the database design so that it can be created during the build stage of database development.
Table: Stores data View: Subset of data from one or more tables Sequence: Numeric value generator Index: Improves the performance of some queries Synonym: Gives alternative names to objects CREATE TABLE [schema.]table (columndatatype[DEFAULT expr][, ...]); CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY [CONSTRAINT constraint]]; CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}]; CREATE INDEX index ON table (column[, column]...); CREATE [PUBLIC] SYNONYM synonym FOR object; Ex: 1. Create index vamsi on emp(eid); 2. Create index ramu on emp(eid,ename); 3. Create unique index srinu on emp(eid,ename,did); .
Exp No : 4
4. Create views, partitions and locks for a particular DB
Partitioning:
enables you to decompose very large tables and indexes into smaller and more manageable pieces called partitions. Each partition is an independent object with its own name and optionally its own storage characteristics. Partitioning is useful for many different types of database applications, particularly those that manage large volumes of data. Benefits include:
Increased availability The unavailability of a partition does not entail the unavailability of the object. The query optimizer automatically removes unreferenced partitions from the query plan so queries are not affected when the partitions are unavailable. Easier administration of schema objects A partitioned object has pieces that can be managed either collectively or individually. DDL statements can manipulate partitions rather than entire tables or indexes. Thus, you can break up resource-intensive tasks such as rebuilding an index or table. For example, you can move one table partition at a time. If a problem occurs, then only the partition move must be redone, not the table move. Also, dropping a partition avoids executing numerous DELETE statements. Reduced contention for shared resources in OLTP systems In some OLTP systems, partitions can decrease contention for a shared resource. For example, DML is distributed over many segments rather than one segment. Enhanced query performance in data warehouses In a data warehouse, partitioning can speed processing of ad hoc queries. For example, a sales table containing a million rows can be partitioned by quarter. Partition Characteristics Each partition of a table or index must have the same logical attributes, such as column names, data types, and constraints. For example, all partitions in a table share the same column and constraint definitions, and all partitions in an index share the same indexed columns. However, each partition can have separate physical attributes, such as the tablespace to which it belongs. Partition Key The partition key is a set of one or more columns that determines the partition in which each row in a partitioned table should go. Each row is unambiguously assigned to a single partition. In the sales table, you could specify the timid column as the key of a range partition. The database assigns rows to partitions based on whether the date in this column falls in a specified range. Oracle Database automatically directs insert, update, and delete operations to the appropriate partition by using the partition key. Partitioning Strategies Oracle Partitioning offers several partitioning strategies that control how the database places data into partitions. The basic strategies are range, list, and hash partitioning. A single-level partitioning strategy uses only one method of data distribution, for example, only list partitioning or only range partitioning. In composite partitioning, a table is partitioned by one data distribution method and then each partition is further divided into subpartitions using a second data distribution method. For example, you could use a list partition for channel_id and a range subpartition for time_id.
Range Partitioning In range partitioning, the database maps rows to partitions based on ranges of values of the partitioning key. Range partitioning is the most common type of partitioning and is often used with dates. Suppose that you want to populate a partitioned table with the sales rows shown in Example Sample Row Set for Partitioned Table
PROD_ID 116 40 118 133 36 125 30 24 35 45 CUST_ID TIME_ID CHANNEL_ID PROMO_ID QUANTITY_SOLD AMOUNT_SOLD 11393 100530 133 9450 4523 9417 170 11899 2606 9491 05-JUN-99 2 30-NOV-98 06-JUN-01 01-DEC-00 27-JAN-99 04-FEB-98 3 23-FEB-01 2 26-JUN-99 4 17-FEB-00 3 28-AUG-98 4 999 9 2 2 3 999 999 999 999 350 1 33 999 999 999 1 1 1 1 1 1 1 1 1 12.18 44.99 17.12 31.28 53.89 16.86 8.8 43.04 54.94 47.45
You create time_range_sales as a partitioned table using the statement in The time_id column is the partition key. Example 4-2 Range-Partitioned Table
CREATE TABLE time_range_sales ( prod_id NUMBER(6) , cust_id NUMBER, time_id DATE, channel_idCHAR(1), promo_idNUMBER(6) , quantity_sold NUMBER(3) , amount_soldNUMBER(10,2) ) PARTITION BY RANGE (time_id) (PARTITION SALES_1998 VALUES LESS THAN (TO_DATE('01-JAN-1999','DD-MON-YYYY')), PARTITION SALES_1999 VALUES LESS THAN (TO_DATE('01-JAN-2000','DD-MON-YYYY')), PARTITION SALES_2000 VALUES LESS THAN (TO_DATE('01-JAN-2001','DD-MON-YYYY')), PARTITION SALES_2001 VALUES LESS THAN (MAXVALUE) );
Afterward, you load time_range_sales with the rows from shows the row distributions in the four partitions. The database chooses the partition for each row based on the time_id value according to the rules specified in the PARTITION BY RANGE clause.
Lock Table:
Use the LOCK TABLE statement to lock one or more tables, table partitions, or table sub partitions in a specified mode. This lock manually overrides automatic locking and permits or denies access to a table or view by other users for the duration of your operation.
Some forms of locks can be placed on the same table at the same time. Other locks allow only one lock for a table. A locked table remains locked until you either commit your transaction or roll it back, either entirely or to a save point before you locked the table.
Locking Table:
AIM: To learn commands related to Table Locking LOCK TABLE Statement Manually lock one or more tables.
Syntax: LOCK TABLE [schema.] table [options] IN lockmode MODE [NOWAIT]
LOCK TABLE [schema.] view [options] IN lockmode MODE [NOWAIT] Options: PARTITION (partition) SUBPARTITION (subpartition) @dblink lockmodes: EXCLUSIVE SHARE ROW EXCLUSIVE SHARE ROW EXCLUSIVE ROW SHARE* | SHARE UPDATE* If NOWAIT is omitted Oracle will wait until the table is available. Several tables can be locked with a single command - separate with commas e.g. LOCK TABLE table1,table2,table3 IN ROW EXCLUSIVE MODE;
ROW EXCLUSIVE = Allow ROW EXCLUSIVE or ROW SHARE locks to be granted to the locked rows. SHARE ROW EXCLUSIVE = Allow ROW SHARE locks to be granted to the locked rows. SHARE = Allow ROW SHARE or SHARE locks to be granted to the locked rows. EXCLUSIVE = Allow SELECT queries only Ex:
1) Create view d10emp such that it contains only empno,ename,sal in department 10. 2) Update the view d10emp such that the sal is 8000 where the sal is 5000 observe the change in base table. 3) Create a view double from emp table and dept table containing the columns ename, job, deptno from emp table and dname,loc from dept table.
Exp No : 5
5. Write PL/SQL procedure for an application using exception handling
DECLARE huge_quantity EXCEPTION; CURSOR product_quantity is SELECT p.product_name as name, sum(o.total_units) as units FROM order_tems o, product p WHERE o.product_id = p.product_id; quantityorder_tems.total_units%type; up_limit CONSTANT order_tems.total_units%type := 20; message VARCHAR2(50); BEGIN FOR product_rec in product_quantity LOOP quantity := product_rec.units; IF quantity >up_limit THEN message := 'The number of units of product ' || product_rec.name || ' is more than 20. Special discounts should be provided. Rest of the records are skipped. ' RAISE huge_quantity; ELSIF quantity <up_limit THEN v_message:= 'The number of unit is below the discount limit.'; END IF; dbms_output.put_line (message); END LOOP; EXCEPTION WHEN huge_quantity THEN dbms_output.put_line (message); END;
QUERY:
1. Write a plsql program to handle built in exceptions 2. Write a PL/SQLprogram which includes declaration,executable
and exception handling section 3. Write a PL/SQL program to design user design exceptions 4. Write a PL/SQL block use raise_application_error
Exp No : 6
6. Write PL/SQL procedure for an application using cursors.
DECLARE CURSOR csr_ac (p_name VARCHAR2) IS SELECT empno, name, sal FROM employee WHERE name LIKE '%p_name%'; v_aemployee.empno%TYPE; v_bemployee.name%TYPE; v_cemployee.sal%TYPE; BEGIN OPEN csr_ac ('LE'); LOOP FETCH csr_ac INTO a, b, c; EXIT WHEN csr_ac%NOTFOUND; DBMS_OUTPUT.PUT_LINE(v_a || ' ' || v_b || ' '||v_c); END LOOP; CLOSE csr_ac; END;
Exp No : 7
7. Write a DBMS program to prepare reports for an application using functions.
CREATE OR REPLACE FUNCTION get_sal (p_id IN employees.employee_id%TYPE) RETURN NUMBER IS v_salaryemployees.salary%TYPE :=0; BEGIN SELECT salary INTO v_salary FROM employees
Exp No : 8
8. Write a PL/SQL block for transaction operations of a typical application using triggers.
Guidelines for Designing Triggers
Use triggers to guarantee that when a specific operation is performed, related actions Use database triggers only for centralized, global operations that should be fired for the triggeringstatement, regardless of which user or application issues the statement. Do not define triggers to duplicate or replace the functionality already built into the Oracledatabase. For example do not define triggers to implement integrity rules that can be done by usingdeclarative constraints. An easy way to remember the design order for a business rule is to:
Use built-in constraints in the Oracle server such as, primary key, foreign key and so on Develop a database trigger or develop an application such as a servlet or Enterprise JavaBean (EJB) on your middle tier Use a presentation interface such as Oracle Forms, dynamic HTML, JavaServerPages (JSP) and so on, if you cannot develop your business rule as mentioned above, which mightbe a presentation rule. The excessive use of triggers can result in complex interdependencies, which may be difficult tomaintain in large applications. Only use triggers when necessary, and beware of recursive andcascading effects. Trigger timing: When should the trigger fire? BEFORE: Execute the trigger body before the triggering DML event on a table. AFTER: Execute the trigger body after the triggering DML event on a table. INSTEAD OF: Execute the trigger body instead of the triggering statement. This is used for views that are not otherwise modifiable.
CREATE [OR REPLACE] TRIGGER trigger_name timing event1 [OR event2 OR event3] ON table_name trigger_body
CREATE OR REPLACE TRIGGER secure_emp BEFORE INSERT ON employees BEGIN IF (TO_CHAR(SYSDATE,'DY') IN ('SAT','SUN')) OR (TO_CHAR(SYSDATE,'HH24:MI') NOT BETWEEN '08:00' AND '18:00') THEN RAISE_APPLICATION_ERROR (-20500,'You may insert into EMPLOYEES table only during business hours.'); END IF; END; /
Trigger Created.. INSERT INTO employees (employee_id, last_name, first_name, email, hire_date, job_id, salary, department_id) VALUES (300, 'Smith', 'Rob', 'RSMITH', SYSDATE, 'IT_PROG', 4500, 60);
Ex:
1. Write a trigger for before delete on employee table. 2. Create a trigger for After insert on employee table. 3. Write a trigger in pl/sql that stores update,delete,insert operations on emp2 table;
Exp No : 9
9. Write a PL/SQL block for transaction operations of a typical application using package.
A package is a schema object that groups logically related PL/SQL types, items, and subprograms. Packages usually have two parts, a specification and a body, although sometimes the body is unnecessary. Thespecification (spec for short) is the interface to your applications; it declares the types, variables, constants, exceptions, cursors, and subprograms available for use. The body fully defines cursors and subprograms, and so implements the spec.
CREATE [OR REPLACE] PACKAGE package_name [AUTHID {CURRENT_USER | DEFINER}] {IS | AS} [PRAGMA SERIALLY_REUSABLE;] [collection_type_definition ...] [record_type_definition ...] [subtype_definition ...] [collection_declaration ...] [constant_declaration ...] [exception_declaration ...] [object_declaration ...] [record_declaration ...] [variable_declaration ...] [cursor_spec ...] [function_spec ...] [procedure_spec ...] [call_spec ...] [PRAGMA RESTRICT_REFERENCES(assertions) ...] END [package_name]; CREATE OR REPLACE PACKAGE emp_actionsAS -- spec TYPE EmpRecTyp IS RECORD (emp_id INT, salary REAL); CURSOR desc_salary RETURN EmpRecTyp; PROCEDURE hire_employee ( ename VARCHAR2, job VARCHAR2, mgr NUMBER, sal NUMBER, comm NUMBER, deptno NUMBER); PROCEDURE fire_employee (emp_id NUMBER); END emp_actions; CREATE OR REPLACE PACKAGE BODY emp_actionsAS -- body CURSOR desc_salary RETURN EmpRecTyp IS SELECT empno, sal FROM emp ORDER BY sal DESC; PROCEDURE hire_employee ( ename VARCHAR2, job VARCHAR2, mgr NUMBER, sal NUMBER, comm NUMBER, deptno NUMBER) IS BEGIN
INSERT INTO emp VALUES (empno_seq.NEXTVAL, ename, job, mgr, SYSDATE, sal, comm, deptno); END hire_employee; PROCEDURE fire_employee (emp_id NUMBER) IS BEGIN DELETE FROM emp WHERE empno = emp_id; END fire_employee; END emp_actions;
Exp No : 10
10. Design and develop an application using any front end and back end tool (make use of ER diagram and DFD).
Step 1: Let us take a very simple example and we try to reach a fully organized database from it. Let us look at thefollowing simple statement: A boy eats an ice cream. This is a description of a real word activity, and we may consider the above statement as a written document (very short, of course). Step 2: Now we have to prepare the ERD. Before doing that we have to process the statement a little. We can see that the sentence contains a subject (boy), an object (ice cream) and a verb (eats) that defines the relationship between the subject and the object. Consider the nouns as entities ( boy and icecream) and the verb (eats) as a relationship. To plot them in the diagram, put the nouns within rectangles and the relationship within a diamond. Also, show the relationship with a directed arrow, starting from the subject entity (boy) towards the object entity (ice cream).
Well, fine. Up to this point the ERD shows how boy and ice cream are related. Now, every boy must have a name, address, phone number etc. and every ice cream has a manufacturer, flavor, price etc. Without these the diagram is not complete. These items which we mentioned here are known as attributes, and they must be incorporated in the ERD as connected ovals.
But can only entities have attributes? Certainly not. If we want then the relationship must have their attributes too. These attribute do not inform anything more either about the boy or the ice cream, but they provide additional information about the relationships between the boy and the ice cream.
Step:3 We are almost complete now. If you look carefully, we now have defined structures for at least three tables like the following:
Boy Name
Address
Phone
Price
Eats Date
Time
However, this is still not a working database, because by definition, database should be collection of related tables. To make them connected, the tables must have some common attributes. If we chose the attribute Name of the Boy table to play the role of the common attribute, then the revised structure of the above tables become something like the following.
Boy Name
Address
Phone
Flavor
Price
Name
Eats Date
Time
Name
This is as complete as it can be. We now have information about the boy, about the ice cream he has eaten and about the date and time when the eating was done.
Cardinality of Relationship While creating relationship between two entities, we may often need to face the cardinality problem. This simply means that how many entities of the first set are related to how many entities of the second set. Cardinality can be of the following three types.
One-to-One Only one entity of the first set is related to only one entity of the second set. E.g. A teacher teaches a student. Only one teacher is teaching only one student. This can be expressed in the following diagram as:
One-to-Many Only one entity of the first set is related to multiple entities of the second set. E.g. A teacher teaches students. Only one teacher is teaching many students. This can be expressed in the following diagram as:
Many-to-One Multiple entities of the first set are related to multiple entities of the second set. E.g. Teachers teach a student. Many teachers are teaching only one student. This can be expressed in the following diagram as:
Many-to-Many Multiple entities of the first set is related to multiple entities of the second set. E.g. Teachers teach students. In any school or college many teachers are teaching many students. This can be considered as a two way one-to-many relationship. This can be expressed in the following diagram as:
In this discussion we have not included the attributes, but you can understand that they can be used without any problem if we want to.
The Concept of Keys
A key is an attribute of a table which helps to identify a row. There can be many different types of keys which are explained here. Super Key or Candidate Key: It is such an attribute of a table that can uniquely identify a row in a table. Generally they contain unique values and can never contain NULL values. There can be more than one super key or candidate key in a table e.g. within a STUDENT table Roll and Mobile No. can both serve to uniquely identify a student. Primary Key: It is one of the candidate keys that are chosen to be the identifying key for the entire table. E.g. although there are two candidate keys in the STUDENT table, the college would obviously use Roll as the primary key of the table. Alternate Key: This is the candidate key which is not chosen as the primary key of the table. They are named so because although not the primary key, they can still identify a row. Composite Key: Sometimes one key is not enough to uniquely identify a row. E.g. in a single class Roll is enough to find a student, but in the entire school, merely searching by the Roll is not enough, because there could be 10 classes in the school and each one of them may contain a certain roll no 5. To uniquely identify the student we have to say something like class VII, roll no 5. So, a combination of two or more attributes is combined to create a unique combination of values, such as Class + Roll. Foreign Key: Sometimes we may have to work with an attribute that does not have a primary key of its own. To identify its rows, we have to use the primary attribute of a related table. Such a copy of another related tables primary key is called foreign key. Strong and Weak Entity Based on the concept of foreign key, there may arise a situation when we have to relate an entity having a primary key of its own and an entity not having a primary key of its own. In such a case, the entity having its own primary key is called a strong entity and the entity not having its own primary key is called a weak entity. Whenever we need to relate a strong and a weak entity together, the ERD would change just a little.
Say, for example, we have a statement A Student lives in a Home. STUDENT is obviously a strong entity having a primary key Roll. But HOME may not have a unique primary key, as its only attribute Address may be shared by many homes (what if it is a housing estate?). HOME is a weak entity in this case. The ERD of this statement would be like the following
As you can see, the weak entity itself and the relationship linking a strong and weak entity must have double border. Different Types of Database There are three different types of data base. The difference lies in the organization of the database and the storage structure of the data. We shall briefly mention them here. RelationalDBMS This is our subject of study. A DBMS is relational if the data is organized into relations, that is, tables. In RDBMS, all data are stored in the well-known row-column format. HierarchicalDBMS In HDBMS, data is organized in a tree like manner. There is a parent-child relationship among data items and the data model is very suitable for representing one-to-many relationship. To access the data items, some kind of tree-traversal techniques are used, such as preorder traversal. Because HDBMS is built on the one-to-many model, we have to face a little bit of difficulty to organize a hierarchical database into row column format. For example, consider the following hierarchical database that shows four employees (E01, E02, E03, and E04) belonging to the same department D1.
There are two ways to represent the above one-to-many information into a relation that is built in one-to-one relationship. The first is called Replication, where the department id is replicated a number of times in the table like the following. Dept-Id Employee Code D1 E01 D1 E02 D1 E03 D1 E04
Replication makes the same data item redundant and is an inefficient way to store data. A better way is to use a technique called the Virtual Record. While using this, the repeating data item is not used in the table. It is kept at a separate place. The table, instead of containing the repeating information, contains a pointer to that place where the data item is stored.
Network DBMS The NDBMS is built primarily on a oneto-many relationship, but where a parent-child representation among the data items cannot be ensured. This may happen in any real world situation where any entity can be linked to any entity. The NDBMS was proposed by a group of theorists known as the Database Task Group (DBTG). What they said looks like this: In NDBMS, all entities are called Records and all relationships are called Sets. The record from where the relationship starts is called the Owner Record and where it ends is called Member Record. The relationship or set is strictly one-to-many.
In case we need to represent a many-to-many relationship, an interesting thing happens. In NDBMS, Owner and Member can only have one-to-many relationship. We have to introduce a third common record with which both the Owner and Member can have one-to-many relationship. Using this common record, the Owner and Member can be linked by a many-to-many relationship. Suppose we have to represent the statement Teachers teach students. We have to introduce a third record, suppose CLASS to which both teacher and the student can have a many-to-many relationship. Using the class in the middle, teacher and student can be linked to a virtual many-to-many relationship.
CREATE TABLE accounts( account_id INT NOT NULL AUTO_INCREMENT, customer_id INT( 4 ) NOT NULL , account_type ENUM( 'savings', 'credit' ) NOT NULL, balance FLOAT( 9 ) NOT NULL, PRIMARY KEY ( account_id ) )
and
CREATE TABLE customers( customer_id INT NOT NULL AUTO_INCREMENT, name VARCHAR(20) NOT NULL, address VARCHAR(20) NOT NULL, city VARCHAR(20) NOT NULL, state VARCHAR(20) NOT NULL, )
Now, how do i create a 'relationship' between the two tables. I want each account to be 'assigned' one customer_id
1. In Object Explorer, right-click the table that will be on the foreign-key side of the relationship and click Design. The table opens in Table Designer. 2. From the Table Designer menu, click Relationships. 3. In the Foreign-key Relationships dialog box, click Add. The relationship appears in the Selected Relationship list with a system-provided name in the format FK_<tablename>_<tablename>, where tablename is the name of the foreign key table. 4. Click the relationship in the Selected Relationship list. 5. Click Tables and Columns Specification in the grid to the right and click the ellipses ( ) to the right of the property. 6. In the Tables and Columns dialog box, in the Primary Key drop-down list, choose the table that will be on the primary-key side of the relationship. 7. In the grid beneath, choose the columns contributing to the table's primary key. In the adjacent grid cell to the left of each column, choose the corresponding foreign-key column of the foreign-key table. Table Designer suggests a name for the relationship. To change this name, edit the contents of the Relationship Name text box. 8. Choose OK to create the relationship.
1. In Object Explorer, connect to an instance of Database Engine. 2. On the Standard bar, click New Query. 3. Copy and paste the following example into the query window and click Execute. The example creates a table and defines a foreign key constraint on the column TempID that references the column SalesReasonID in the Sales.SalesReason table. The ON DELETE CASCADE and ON UPDATE CASCADE clauses are used to ensure that changes made to Sales.SalesReason table are automatically propagated to the Sales.TempSalesReason table. USE AdventureWorks2012; GO CREATE TABLE Sales.TempSalesReason (TempIDint NOT NULL, Name nvarchar(50), CONSTRAINT PK_TempSales PRIMARY KEY NONCLUSTERED (TempID), CONSTRAINT FK_TempSales_SalesReason FOREIGN KEY (TempID) REFERENCES Sales.SalesReason (SalesReasonID) ON DELETE CASCADE ON UPDATE CASCADE); GO To create a foreign key in an existing table 1. In Object Explorer, connect to an instance of Database Engine. 2. On the Standard bar, click New Query. 3. Copy and paste the following example into the query window and click Execute. The example creates a foreign key on the column TempID and references the column SalesReasonID in the Sales.SalesReason table.
USE AdventureWorks2012; GO ALTER TABLE Sales.TempSalesReason ADD CONSTRAINT FK_TempSales_SalesReason FOREIGN KEY (TempID) REFERENCES Sales.SalesReason (SalesReasonID) ON DELETE CASCADE ON UPDATE CASCADE; GO
I suggest to use always a separated file with SQL statements to create all database's tables and relationships between them. The code is very simple, easy to modify and to reuse. A relation is defined using the statement REFERENCES: CREATE TABLE CITY ( id_city_pk INT NOT NULL AUTO_INCREMENT, city VARCHAR(100), PRIMARY KEY (id_city_pk)) TYPE=INNODB; CREATE TABLE USER ( id_user_pk INT NOT NULL AUTO_INCREMENT, nick VARCHAR(40), email VARCHAR(40), password VARCHAR(20), id_city INT NOT NULL, PRIMARY KEY (id_user_pk)
FOREIGN KEY (id_city) REFERENCES CITY(id_city_pk) ON UPDATE CASCADE ON DELETE CASCADE) TYPE=INNODB;
Exp No : 12 12. Implement the query in sql for a) insertion b) retrieval c) updation d) deletion.
INSERT INSERT INTO table_name VALUES (value1, value2, value3,...); ( OR )
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...); UPDATE UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value;
DELETE DELETE FROM table_name WHERE some_column=some_value; SELECT SELECT column_name(s) FROM table_name;
SQL> create view emp22 as select * from emp2; OUTPUT:View created. SQL> select * from emp22; OUTPUT:ENAME STREET CITY -------------------- -------------------- -------------------coyotetoonhollywood rabbit tunnel carrot ville smith revolver death valley williams sea view sea attle
To write a TRIGGER to ensure that DEPT TABLE does not contain duplicate of null values in DEPTNO column. INPUT CREATE OR RELPLACE TRIGGER trig1 before insert on dept for each row DECLARE a number; BEGIN if(:new.deptno is Null) then raise_application_error(-20001,'error::deptno cannot be null'); else select count(*) into a from dept where deptno=:new.deptno; if(a=1) then raise_application_error(-20002,'error:: cannot have duplicate deptno'); end if; end if; END; RESULT: SQL> @trigger Trigger created. SQL> select * from dept; DEPTNO DNAME LOC --------- -------------- ------------10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON SQL> insert into deptvalues(&deptnp,'&dname','&loc'); Enter value for deptnp: null Enter value for dname: marketing Enter value for loc: hyd old 1: insert into dept values(&deptnp,'&dname','&loc') new 1: insert into dept values(null,'marketing','hyd') insert into dept values(null,'marketing','hyd')
* ERROR at line 1: ORA-20001: error::deptno cannot be null ORA-06512: at "SCOTT.TRIG1", line 5 ORA-04088: error during execution of trigger 'SCOTT.TRIG1' SQL> / Enter value for deptnp: 10 Enter value for dname: manager Enter value for loc: hyd old 1: insert into dept values(&deptnp,'&dname','&loc') new 1: insert into dept values(10,'manager','hyd') insert into dept values(10,'manager','hyd') * ERROR at line 1: ORA-20002: error:: cannot have duplicate deptno ORA-06512: at "SCOTT.TRIG1", line 9 ORA-04088: error during execution of trigger 'SCOTT.TRIG1' SQL> / Enter value for deptnp: 50 Enter value for dname: MARKETING Enter value for loc: HYDERABAD old 1: insert into dept values(&deptnp,'&dname','&loc') new 1: insert into dept values(50,'MARKETING','HYDERABAD') 1 row created. SQL> select * from dept; DEPTNO DNAME LOC --------- -------------- ------------10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON 50 MARKETING HYDE
1. Writing PL/SQL block for checking armstrong number 2. Writing a PL/SQL block for checking a number even or odd.
. Use Form Builder to simplify for the creation of data-entry screens, also known as Forms. Forms are the applications that connect to a database, retrieve information requested by the user, present it in a layout specified by Form designer, and allow the user to modify or add information. Form Builder allows you to build forms quickly and easily. In this Hands-On, you learn how to: Create a Data block for the _Customer_ table, Create a layout, Use _content_ canvas, Use _execute query_, Navigate a table, Use next, previous record, Enter query, Manipulate table_s record, Insert, Update, Delete and Save record. Form Builder Tool Open the "Form Builder" tool. Welcome window You will get the _Welcome to the Form Builder_ window. If you don_t want to get this window anymore uncheck the _Display at startup_ box. You can start your work with any of the following options: Use the data Block Wizard Build a new form manually Open an existing form Build a form based on a template The default is _Use the data Block Wizard._ If you want to build a new form manually, click on "Cancel_ or check _Build a new form manually_ and click _OK._ Connect to database In the _Object Navigator_ window, highlight "Database Objects." Go to the Main menu and choose "File," then "Connect." In the _Connect_ window, login in as _scott_ password _tiger,_ then click _CONNECT._ Notice that the box next to _Database Objects_ is not empty anymore and it has a _+_ sign in it. That will indicate that this item is expandable and you are able to see its entire objects. Click on the _+_ sign next to the _Database Objects_ to expand all database schemas.
Create a Module In the _Object Navigator_ window, highlight module1. This is a default name. Go to the Main menu and choose _File,_ select _Save as_ to store the new object in the _iself_ folder and save it as customer data entry. "c:_de." In this example the _DE_ abbreviation stands for Data Entry. Create a Data Block In the _Object Navigator_ window, highlight "Data Blocks,_ and click on the "create_ icon. The _Create_ icon is in the vertical tool bar in the _Object Navigator_ window. It is a green _+_ sign. If you drag your cursor on the icon a tooltip will show _Create._ New Data Block In the _New Data Block_ window, choose the default option _Data Block Wizard_ and click "OK." Welcome Data Block In the _Welcome Data Block Wizard_ window click on the _NEXT_ icon. Type of Data Block Select the type of data block you would like to create by clicking on a radio button. Select the default option _Table or View_ and then click _NEXT_ again. Selecting Tables Click on _browse._ In the _Tables_ window, highlight the "cust11_ table; then click "OK." Selecting columns for the Data Block Wizard To choose all columns, click on the two arrow signs in the _Data Block Wizard_ window. To choose selected columns, click on the one arrow sign. And then select all columns, and click _next._
Layout Wizard End of the Data Block Wizard and beginning of the Layout Wizard In the _Congratulations_ screen, use the default checkmark radio button (Create the data block, then call the Layout Wizard), and click "Finish." You can also use the Data Block Wizard to modify your existing data block. Simply select the data block in the Object Navigator and click the Data Block Wizard toolbar button, or choose _Data Block wizard_ from the _Tools_ menu. Welcome screen
In the _Welcome to the Layout Wizard_ window, click _Next._ Selecting canvas In the _Layout Wizard_ window, select the "new canvas" option. Canvas is a place that you will have your objects such as columns, titles, pictures, etc. If you have already had your canvas, select the canvas and then click on the next. The following are different types of canvases: Content, Stacked, Vertical Toolbar, Horizontal Toolbar, and Tab. Think of the _Content_ canvas as one flat place to have all your objects. In the stacked canvas, you can have multiple layers of objects and it is the same as the tab canvas. You use the vertical or horizontal toolbar canvases for your push buttons. Check the different types of canvases by clicking on the _down arrow_ box next to the _Type_ field. Select "content," then click _Next._ Selecting Columns for the Layout Wizard In the _Layout Wizard_ window, select all the columns. These are the columns that you want to be displayed on the canvas. Then click _Next._ Change your objects appearances Change size or prompt if needed. In this window, you can enter a prompt, width, and height for each item on the canvas. You can change the measurement units. As a default the default units for item width and height are points. You can change it to inch or centimeter. When you change size, click _Next._ Selecting a layout style Select a layout style for your frame by clicking a radio button. Select "Form," if you want one record at a time to be displayed. Select _Tabular,_ if you want more than one record at a time to be displayed. Select "Forms," and then click _next._ Record layout Type the "Frame Title" and click "next." Checkmark the _Display Scrollbar_ box when you use multiple records or the _Tabular_ option. Congratulation Screen In the _Congratulations_ window, click "Finish." You will see the output layout screen. Make some window adjustments and then run the form. To run the form, click on the _Run_ icon. The _Run_ icon is on the horizontal toolbar in the _CUSTOMER_DE_ canvas. The object module should be compiled successfully before executing the Form.
Execute Query Click on the "Execute Query" icon below the main menu. If you drag the cursor on the toolbar in the _Forms Runtime_ window, a tooltip will be displayed and you see _Execute Query._ So to know all your option, drag your cursor to view all the icon descriptions. Next Record Click on the "Next Record" icon to navigate to the next record. Previous Record Click on the "Previous Record" icon to navigate to the previous record. This is an easy way to navigate through the _Customer_ table. Enter Query Click on the "Enter Query" icon to query selected records. Insert Record Click "Insert Record" to add new customer. All items on the forms will be blanked. You can either type all the customer information or duplicate it from pervious record. Duplicate Record To duplicate the previous record, go to the main menu and select the _Record_ sub-menu. A drop down menu will be displayed. Select the _Duplicate_ option in the sub-menu. Apply the changes. Remember in this stage, your record was inserted but not committed yet. Next and Previous Record Click "next record" and "previous record" to navigate through the records and the one was added. Save transactions Click "Save" to commit the insert statement. Delete Record Click "Remove Record" to delete the record. Lock a Record You can also lock the record. Exit from Form Runtime
Exit the FORM Runtime. If you have not committed any transaction, you will be prompted to save changes. Click _YES_ to save changes. Click _OK_ for acknowledgement. Don_t forget to save the Form. RABAD
AIM: To design reports using Oracle Developer 2000 Introduction Tabular report shows data in a table format. It is similar in concept to the idea of an Oracle table. Oracle, by default, returns output from your select statement in tabular format. Hands-on In this Hands-On, your client is a stock broker that keeps track of its customer stock transactions. You have been assigned to write the reports based on their reports layout requirements. Your client wants you to create a simple listing report to show list of the stock trades by using stocks table for their brokerage company Your tasks are: 1- Write a tabular report. 2- Apply user layout Format mask. 3- Run the report. 4- Test the repot. You will learn how to: use report wizard, object navigator, report builder, _date model_, property palette, work on query and group box, see report style, use tabular style, navigating throughreport_s record, change the format mask for dollar, numeric and date items. Open Report Builder tool Open the "Report Builder" tool. Connect to database In the Object Navigator, highlight "Database Objects,_ choose "File," then select the "Connect" option. In the _Connect_ window, login as _iself_ password schooling, then click _CONNECT._ Save a report In the Object Navigator, highlight the "untitled" report, choose _File,_ and select the _Save as_ option. In the _Save as_ window, make sure to save the report in the ISELF folder and name it "rpt01_stock_history,_ report number 1 stock history. Data Model In the Object Navigator, double click on the "Data Model" icon. Create SQL box
In the Data Model window, click on the "SQL Query" icon. Then drag the plus sign cursor and click it anywhere in the _Data Model_ screen where you wish your object to be. In the _SQL Query Statement_ window, write a query to read all the stocks record sorted by their symbol. (SQL Query Statement) SELECT * FROM stocks ORDER BY symbol Click _OK._ Change SQL box_s name In the Data Model window, in the _SQL_ box, right click on the _Q_1_ and open its property palette. In its property palette, change the name to Q_STOCKS. Then close the window. Change GROUP box_s name In the Data Model, right click on the group box (G_SYMBOL) and open its property palette. In the Group property palette, change the name to _G_STOCKS,_ and close the window. Open Report Wizard In the Data Model, click on the _Report Wizard_ icon on the horizontal tool bar. In the Style tab, on the Report Wizard window, type _Stock History_ in the Title box and choose the report style as _Tabular._ Notice that when you change the report style a layout of that report will be displayed on the screen. Choose a different style to display its layout of its report style. Data, Fields, Totals, Labels and Template tabs Click _NEXT_ to go to the Data tab. In the _SQL Query Statement_ verify your query. Click _NEXT_ to navigate to the Fields tab, select the fields that you would like to be display in your report. Select all the columns to be display. Click _NEXT_ to navigate to Totals tab, select the fields for which you would like to calculate totals. We have none in this hands-on exercise. Click _NEXT_ to open the Labels tab, modify the labels and widths for your fields and totals as desired. Click _NEXT_ again to go to the Template tab, and choose a template for your report. Your report will inherit the template_s colors, fonts, line widths, and structure. Use the default template and click _finish._ Running a report Now, you should have your output report on the screen. Resize an object Maximize the output report and format the report layout. To resize an object , select it and drag its handler to the preferred size. Move an object
To move an object, select and drag it while the cursor is on the object. This is a simple report. Navigate throughTo know each icon functionalities, drag your cursor on it and a tooltip will display its the output function. To navigate through theChange Format Mask output report inTo change the "format mask" of a column, the column should be selected. Then go to the the Reporttoolbar and click on the _$_ icon, "add decimal place," and the _right justify_ format to the Editor - Livecurrency columns (Todays Low, Todays High, and current price) Pre-viewer, click on the Select the _traded today_ column, and click on the _,0_ icon (apply commas), and make it "next page" orright justify. "previous Also, you can change any attributes of field by opening its property palette. To open an page" icon onobject_s property palette, right click on it and select the Property Palette option. the horizontalRight click on the "trade date" column and open its "property palette." toolbar. Do the same with the "first page" or "last page" icon. Use the _zoom in_ and _zoom out_ icon to preview the report. Know report_s functions Change the date "Format Mask" property and make it _year 2000 complaint (MM-DD-RR)._
Additional Experiments :
1. To write a packages that use the overloading feature Overloading Enables you to use the same name for different subprograms inside a PL/SQL block, asubprogram, or a package Requires the formal parameters of the subprograms to differ in number, order, or datatype family Enables you to build more flexibility because a user or application is not restricted by the specific data type or number of formal parameters
Overloading: Example CREATE OR REPLACE PACKAGE over_packIS PROCEDURE add_dept (p_deptno IN departments.department_id%TYPE, p_name IN departments.department_name%TYPE DEFAULT 'unknown', p_loc IN departments.location_id%TYPE DEFAULT 0); PROCEDURE add_dept (p_name IN departments.department_name%TYPE DEFAULT 'unknown', p_loc IN departments.location_id%TYPE DEFAULT 0); END over_pack; Overloading Example (continued) If you call ADD_DEPT with an explicitly provided department ID, PL/SQL uses the first version of theprocedure. If you call ADD_DEPT with no department ID, PL/SQL uses the second version. EXECUTE over_pack.add_dept (980,'Education',2500) EXECUTE over_pack.add_dept ('Training', 2400) SELECT * FROM departments WHERE department_id = 980;
2. To Controlling the Persistent State of a Package Cursor CREATE OR REPLACE PACKAGE BODY pack_cur IS v_empno NUMBER; PROCEDURE proc1_3rows IS BEGIN
OPEN c1; LOOP FETCH c1 INTO v_empno; DBMS_OUTPUT.PUT_LINE('Id :' ||(v_empno)); EXIT WHEN c1%ROWCOUNT >= 3; END LOOP; END proc1_3rows; PROCEDURE proc4_6rows IS BEGIN LOOP FETCH c1 INTO v_empno; DBMS_OUTPUT.PUT_LINE('Id :' ||(v_empno)); EXIT WHEN c1%ROWCOUNT >= 6; END LOOP; CLOSE c1; END proc4_6rows; END pack_cur; The slide on this page shows the package body for PACK_CUR to support the package specification. In the package body: 1. Open the cursor and fetch successive rows from the cursor by using one packaged procedure, PROC1_3ROWS. 2. Continue to fetch successive rows from the cursor and close the cursor, using another packaged procedure, PROC4_6ROWS. SET SERVEROUTPUT ON EXECUTE pack_cur.proc1_3rows EXECUTE pack_cur.proc4_6rows
3. Create a table called PERSONNEL. The table contains the following attributes and data types:
CREATE TABLE personnel (id NUMBER(6) constraint personnel_id_pk PRIMARY KEY, last_nameVARCHAR2(35),
Insert two rows into the PERSONNEL table, one each for employees 2034 and 2035. Use the empty function for the CLOB, and provide NULL as the value for the BLOB. INSERT INTO personnel VALUES(2034, 'Allen', EMPTY_CLOB(), NULL);
a. Populate the CLOB for the first row, using the following query in a SQL UPDATE statement: SELECT ann_review FROM review_table WHERE employee_id = 2034; UPDATE personnel SET review = (SELECT ann_review FROM review_table WHERE employee_id = 2034) WHERE last_name = 'Allen'; Update the PERSONNEL table. a. Populate the CLOB for the first row, using the following query in a SQL UPDATE statement: SELECT ann_review FROM review_table WHERE employee_id = 2034; UPDATE personnel SET review = (SELECT ann_review FROM review_table WHERE employee_id = 2034) WHERE last_name = 'Allen'; b. Populate the CLOB for the second row, using PL/SQL and the DBMS_LOB package. Use the following SELECT statement to provide a value: SELECT ann_review FROM review_table WHERE employee_id = 2035; 4. Create a procedure called DROP_TABLE2 that drops the table specified in the inputparameter. Use the EXECUTE IMMEDIATE statement. Create another procedure called DROP_TABLE2 that drops the table specified in the input parameter. Use the EXECUTE IMMEDIATE statement. CREATE PROCEDURE DROP_TABLE2 (p_table_name IN VARCHAR2)
IS BEGIN EXECUTE IMMEDIATE 'DROP TABLE ' || p_table_name; END; / b. Repeat the test outlined in steps 1b and 1c. CREATE TABLE emp_dup AS SELECT * FROM employees; EXECUTE drop_table2('emp_dup') SELECT * FROM emp_dup;