+ All Categories
Home > Documents > DBMS Lab Manual

DBMS Lab Manual

Date post: 03-Dec-2014
Category:
Upload: moulika-chowdary
View: 598 times
Download: 7 times
Share this document with a friend
Popular Tags:
264
SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT DATA BASE MANAGEMENT SYSTEMS LAB MANUAL Prepared By Mr.O.Obulesu, Asst.Professor Prepared by: Mr.O.Obulesu, Asst.professor [1]
Transcript
Page 1: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

DATA BASE MANAGEMENT SYSTEMSLAB MANUAL

Prepared By

Mr.O.Obulesu, Asst.Professor

Prepared by: Mr.O.Obulesu, Asst.professor [1]

Page 2: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

LIST OF PROGRAMS(I) SQL:

1. Performing DDL Operations.

2. Performing DML Operations.

3. SQL Functions.

4. Illustration of Constraints in SQL.

5. Illustration of Joins in SQL.

6. Creating Views.

7. Group Functions in SQL.

8. Implementation of Subqueries in SQL.

9. Group by clause and TOP-N Analysis in SQL.

10. Correlated Sub Queries and Set operations.

11. Indexes, Synonyms and Sequences.

(II) PL/SQL:

1. Program to accept a number from user and test whether it is divisible bya number.

2. Program to Check whether input is character, number or a special character.

3. Program to accept two numbers and display the larger one. 4. Program to Perform Arithmetic operations.

5. Program to illustrate usage of Cursors.

6. Program for Employee pay slip.

7. Program to display student marklist. 8. Program to display Student rank information.

9. Program for Electricity Bill Generation.

10. Program to illustrate the Concept of Procedures.

11. Program to illustrate usage of Functions.

Prepared by: Mr.O.Obulesu, Asst.professor [2]

Page 3: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

12. Program for Packages.

13. Database Trigger.

14. Creation of Forms.

15. Generation of Reports.

Prepared by: Mr.O.Obulesu, Asst.professor [3]

Page 4: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Steps to Enter into SQL*plus:

1. After installing Oracle, Go to Start-> Programs-> SQL*Plus

2. A Window is displayed which prompts for the User name , password,Host String.

3. Give the Appropriate Username, Password and Host String.

4. You can view the SQL Prompt.

5. You can type the SQLCommands in the prompt.

Database Languages:

Data Definition Language (DDL):

Used to Define the database Objects like Tables, Views etc.Eg: Create, Alter, Truncate, Drop.

Create: Used to Create Table, View etc.

Syntax: Create Table Tablename (Columnname1 Datatype (Size), Columnname2 Datatype (Size), …………. ColumnnameN Datatype (Size));

Eg: Create Table EMP (Empno Number (10), Ename Varchar2 (10));

Alter: Used to add or drop an Existing column or add new column to a Table.

Syntax to Add a Column: Alter table tablename add columnname datatype(size);

Eg: Alter Table EMP add Designation Varchar2 (10);Syntax to drop a Column from a Table:

Alter table tablename drop Column Columnname;Eg: Alter Table EMP Drop Column Ename;

Truncate: Used to drop/remove the Content (rows) of a table, but the Structure of a table exists.

Syntax to Truncate a Table: Truncate Table Tablename;

Eg: Truncate Table EMP;Drop:

Used to Drop a Table, View etc.Syntax:

Drop Table Tablename;Eg: Drop Table EMP;

Data Manipulation Language (DML)

Prepared by: Mr.O.Obulesu, Asst.professor [4]

Page 5: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• A DML statement is executed when you:– Add new rows to a table– Modify existing rows in a table– Remove existing rows from a table permanently

• A transaction consists of a collection of DML statements that form a logical unit of work.Eg: INSERT, UPDATE, and DELETE.

(a)INSERT:

Used to insert rows into the Existing Table. Syntax:

Insert into Tablename Values(Value1, Value2,…Value n); Eg: Insert into EMP Values (1, ‘Anil’);

Syntax to Insert Rows only into Specific Columns of a Table: Insert into Tablename(Columnname1, Columnname2) Values(Value1, Value2);

Eg: Insert Into EMP (Empno, Ename) values (1, ‘Sujatha’);

Syntax to Insert values During Run Time Insert into Tablename (&Column name1,&Columnname2) Values(&Value1,&value2);

Eg: Insert into EMP Values (&Empno, ‘&Ename’) values(1,’sunil’);

(b)UPDATE: Used to change the Data in a Table• Modify existing rows with the UPDATE statement.

Syntax: UPDATE tablename

SET [column1 = value, column2 = value] [WHERE condition];

• Update more than one row at a time, if required.• Specific row or rows are modified,if you specify the WHERE clause.

Eg: UPDATE copy_emp SET department_id = 110 WHERE ename=’Anil’;

• All rows in the table are modified, if you omit the WHERE clause.Eg: UPDATE employees

SET job_id = (SELECT job_id FROM employees WHERE employee_id = 205), Salary = (SELECT salary FROM employees WHERE employee_id = 205) WHERE employee_id = 114;

Updating Rows Based on Another Table:

Eg: UPDATE copy_empSET department_id = (SELECT department_id FROM employees WHERE employee_id = 100)WHERE job_id = (SELECT job_id FROM employees

WHERE employee_id = 200);(c)DELETE:

Prepared by: Mr.O.Obulesu, Asst.professor [5]

Page 6: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Used to remove the existing rows from a Table by using the DELETE statement. Syntax:

DELETE [FROM] tablename [WHERE condition];

Deleting Rows from a Table: Specific rows are deleted, if you specify the WHERE clause.

Eg: DELETE FROM departments WHERE department_name = 'Finance';

• All rows in a table are deleted,if you omit the WHERE clause. Eg: DELETE FROM copy_emp;

Deleting Rows Based on another Table: Use subqueries in DELETE statements to remove rows from a table based on values from

another table.Eg: DELETE FROM employees

WHERE department_id = (SELECT department_id FROM departments WHERE department_name LIKE '%Public %');

Database Transactions:A database transaction contains one of the following:• DML statements,which constitute one consistent change to the data• One DDL statement• One DCL statement• Begin when the first DML SQL statement is executed• End with one of the following events:

• A COMMIT or ROLLBACK statement is issued• A DDL or DCL statement executes (automatic commit)• The user exits iSQL*Plus• The system crashes

Advantages of COMMIT and ROLLBACK Statements: • To ensure data consistency• Preview data changes before making changes permanent• To group logically related operations

Rolling Back Changes to a Marker:• Create a marker in a current transaction by using the SAVEPOINT statement.• Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement.

UPDATE...SAVEPOINT update_done;

Savepoint created.INSERT...ROLLBACK TO update_done;

Rollback complete.Implicit Transaction Processing:

• An automatic commit occurs under the following circumstances:– DDL statement is issued– DCL statement is issued– Normal exit from iSQL*Plus, without explicitly issuing COMMIT or ROLLBACK

statements

Prepared by: Mr.O.Obulesu, Asst.professor [6]

Page 7: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• An automatic rollback occurs under an abnormal termination of iSQL*Plus or a system failure.

State of the Data before COMMIT or ROLLBACK:• The previous state of the data can be recovered.• The current user can review the results of the DML operations by using the SELECT

statement.• Other users cannot view the results of the DML statements by the current user.• The affected rows are locked; other users cannot change the data within the affected rows.

State of the Data after COMMIT• Data changes are made permanent in the database.• The previous state of the data is permanently lost.• All users can view the results.• Locks on the affected rows are released; those rows are available for other users to

manipulate.• All savepoints are erased.

Committing Data• Make the changes.

DELETE FROM employeesWHERE employee_id = 99999;

1 row deleted.

INSERT INTO departments VALUES (290, 'Corporate Tax', NULL, 1700);

1 row inserted.State of the Data after ROLLBACK:

Discard all pending changes by using the ROLLBACK statement:• Data changes are undone.• Previous state of the data is restored.• Locks on the affected rows are released.

DELETE FROM copy_emp;22 rows deleted.

ROLLBACK; Rollback complete.Statement-Level Rollback:

• If a single DML statement fails during execution, only that statement is rolled back.• The Oracle server implements an implicit savepoint.• All other changes are retained.• The user should terminate transactions explicitly by executing a COMMIT or

ROLLBACK statement.Read Consistency:

• Read consistency guarantees a consistent view of the data at all times.• Changes made by one user do not conflict with changes made by another user. • Read consistency ensures that on the same data:

– Readers do not wait for writers.– Writers do not wait for readers.Copying Rows from Another Table:

Prepared by: Mr.O.Obulesu, Asst.professor [7]

Page 8: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Write INSERT statement with a subquery.INSERT INTO sales_reps (id, name, salary, commission_pct)SELECT employee_id, last_name, salary, commission_pctFROM employeesWHERE job_id LIKE '%REP%';

Do not use the VALUES clause. Match the number of columns in the INSERT clause to those in the subquery.

Creating and Managing Tables:Table - Basic unit of storage; composed of rows and columnsView - Logically represents subsets of data from one or more tablesSequence - Numeric value generatorIndex - Improves the performance of some queriesSynonym - Gives alternative names to objects

Naming Rules:Table names and column names:

• Must begin with a letter• Must be 1–30 characters long• Must contain only A–Z, a–z, 0–9, _, $, and #• Must not duplicate the name of another object owned by the same user• Must not be an Oracle server reserved word

The CREATE TABLE Statement:• You must have:

– CREATE TABLE privilege– A storage area

Referencing another User’s Tables:• Tables belonging to other users are not in the user’s schema.• You should use the owner’s name as a prefix to those tables

The DEFAULT Option• Specify a default value for a column during an insert.

Eg: …hire_date DATE DEFAULT SYSDATE... • Literal values, expressions, or SQL functions are legal values.• Another column’s name or pseudocolumns are illegal values.• The default data type must match the column data type.

Creating TablesCREATE TABLE dept

(deptno NUMBER (2), Dname VARCHAR2 (14), Loc VARCHAR2 (13));

Querying the Data Dictionary: View the names of tables owned by the user.

Eg: SELECT table_name FROM user_tables;

View distinct object types owned by the user.Eg: SELECT DISTINCT object_type

FROM user_objects; View tables, views, synonyms, and sequences owned by the user.

Eg: SELECT * FROM user_catalog;

Prepared by: Mr.O.Obulesu, Asst.professor [8]

Page 9: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Data Types in Oracle:VARCHAR2 (size) - Variable-length character dataCHAR (size) - Fixed-length character dataNUMBER (P, S) - Variable-length numeric dataDATE - Date and time valuesLONG - Variable-length character data upto 2 giga bytes CLOB - Character data up to 4 gigabytesRAW and LONG RAW - Raw binary dataBLOB - Binary data up to 4 gigabytesBFILE - Binary data stored in an external file p to 4 gigabytesROWID - A 64 base number system representing the unique address

of a row in its table.

Creating a Table by Using Subquery Syntax:• Create a table and insert rows by combining the CREATE TABLE statement and the

AS subquery option.CREATE TABLE tablename [(column, column...)] AS subquery;

• Match the number of specified columns to the number of subquery columns.• Define columns with column names and default values.

Creating a Table by Using a Subquery: CREATE TABLE dept80 AS SELECT employee_id, last_name, salary*12 ANNSAL, hire_date FROM employees WHERE department_id = 80;

The ALTER TABLE Statement: Use ALTER TABLE statement to:

• Add a new column• Modify an existing column• Define a default value for the new column• Drop a column

Use the ALTER TABLE statement to add, modify, or drop columns.Syntax to add column to an Existing Table:

(1) ALTER TABLE tablename ADD (column datatype [DEFAULT expr], [column datatype]...);

(2) ALTER TABLE tablename MODIFY (column datatype [DEFAULT expr], [column datatype]...);

(3) ALTER TABLE tablename DROP (column);

You use the ADD clause to add columns.Eg: (1) ALTER TABLE dept80

ADD (job_id VARCHAR2 (9));Table altered.• You can change a column’s data type, size, and default value. Eg: (2) ALTER TABLE dept80

Prepared by: Mr.O.Obulesu, Asst.professor [9]

Page 10: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

MODIFY (last_name VARCHAR2 (30));Table altered.

The SET UNUSED Option• You use the SET UNUSED option to mark one or more columns as unused.• You use the DROP UNUSED COLUMNS option to remove the columns that are

marked as unused.Changing the Name of an Object:

• To change the name of a table, view, sequence, or synonym, you execute the RENAME statement.Eg: RENAME dept TO detail_dept;

Table renamed. You must be the owner of the object.

Truncating a Table:• The TRUNCATE TABLE statement:

– Removes all rows from a table– Releases the storage space used by that table

Eg: TRUNCATE TABLE detail_dept;Table truncated.

• You cannot roll back row removal when using TRUNCATE.• Alternatively, you can remove rows by using the DELETE statement.

Adding Comments to a Table: You can add comments to a table or column by using the COMMENT

statementEg: COMMENT ON TABLE employees IS 'Employee Information';

Comment created.• Comments can be viewed through the data dictionary views:

– ALL_COL_COMMENTS– USER_COL_COMMENTS– ALL_TAB_COMMENTS– USER_TAB_COMMENTS

What are Constraints?• Constraints enforce rules at the table level.• Constraints prevent the deletion of a table,if there are dependencies.• The following constraint types are valid:

– NOT NULL– UNIQUE – PRIMARY KEY– FOREIGN KEY– CHECK

Constraint Guidelines:• Name a constraint or the Oracle server generates a name by using the SYS_Cn format.• Create a constraint either:

– At the same time as the table is created, or– After the table has been created

• Define a constraint at the column or table level.• View a constraint in the data dictionary.

Prepared by: Mr.O.Obulesu, Asst.professor [10]

Page 11: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Defining Constraints:Eg: (1) CREATE TABLE [schema.] tablename

(Column datatype [DEFAULT expr] [column_constraint],...[table_constraint][,...]);

Eg: (2) CREATE TABLE employees (employee_id NUMBER (6), first_name VARCHAR2 (20), ... job_id VARCHAR2 (10) NOT NULL, CONSTRAINT emp_emp_id_pk

PRIMARY KEY (EMPLOYEE_ID));Defining Constraints:Column constraint level:

Column [CONSTRAINT constraint_name] constraint_type,• Table constraint level:

Column,... [CONSTRAINT constraint_name] constraint_type (Column, ...),

The NOT NULL Constraint: Ensures that null values are not permitted for the column:

NOT NULL constraint: (No rows can contain Absence of NOT NULL constraint

Absence of NOT NULL constraint(Any row can contain null for this column.)

The NOT NULL Constraint:Is defined at the column level:

CREATE TABLE employees (employee_id NUMBER (6), last_name VARCHAR2 (25) NOT NULL,---- --- Table Level Salary NUMBER (8, 2), Commission_pct NUMBER (2, 2), Hire_date DATE CONSTRAINT emp_hire_date_nn -------------- Column Level NOT NULL, ….)

The UNIQUE Constraint UNIQUE constraint

Prepared by: Mr.O.Obulesu, Asst.professor [11]

Page 12: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

The UNIQUE Constraint: Defined at either the table level or the column level:

Eg: CREATE TABLE employees (employee_id NUMBER (6), last_name VARCHAR2 (25) NOT NULL,

Email VARCHAR2 (25), Salary NUMBER (8, 2), Commission_pct NUMBER (2, 2), Hire_date DATE NOT NULL, CONSTRAINT emp_email_uk UNIQUE (email));

The PRIMARY KEY Constraint: Defined at either the table level or the column level:

Eg: CREATE TABLE departments (department_id NUMBER (4), department_name VARCHAR2 (30), CONSTRAINT dept_name_nn NOT NULL, Manager_id NUMBER (6), Location_id NUMBER (4), CONSTRAINT dept_id_pk PRIMARY KEY (department_id));

The FOREIGN KEY Constraint: Defined at either the table level or the column level:

Eg: CREATE TABLE employees (employee_id NUMBER (6), last_name VARCHAR2 (25) NOT NULL,

Email VARCHAR2 (25), Salary NUMBER (8, 2), Commission_pct NUMBER (2, 2), Hire_date DATE NOT NULL,

... Department_id NUMBER (4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id) REFERENCES departments (department_id), CONSTRAINT emp_email_uk UNIQUE (email));

FOREIGN KEY Constraint Keywords:

• FOREIGN KEY: Defines the column in the child table at the table constraint level• REFERENCES : Identifies the table and column in the parent table• ON DELETE CASCADE: Deletes the dependent rows in the child table when a row

in the parent table is deleted.

Prepared by: Mr.O.Obulesu, Asst.professor [12]

Page 13: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• ON DELETE SET NULL: Converts dependent foreign key values to nullThe CHECK Constraint:

• Defines a condition that each row must satisfy that condition.• The following expressions are not allowed:

– References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns

– Calls to SYSDATE, UID, USER, and USERENV functions– Queries that refer to other values in other rows–

Eg: ..., Salary NUMBER (2) CONSTRAINT emp_salary_min CHECK (salary > 0),...

Adding a Constraint Syntax: Use the ALTER TABLE statement to:

• Add or drop a constraint, but not modify its structure• Enable or disable constraints• Add a NOT NULL constraint by using the MODIFY clause

Eg: ALTER TABLE tablename ADD [CONSTRAINT constraint type] (column);

Add a FOREIGN KEY constraint to the EMPLOYEES table indicating that a manager must already exist as a valid employee in the EMPLOYEES table.

Eg: ALTER TABLE employees ADD CONSTRAINT emp_manager_fk

FOREIGN KEY (manager_id) REFERENCES employees (employee_id);

Table altered.Dropping a Constraint:

• Remove the manager constraint from the EMPLOYEES table.Eg: ALTER TABLE employees

DROP CONSTRAINT emp_manager_fk;• Remove the PRIMARY KEY constraint on the DEPARTMENTS table and drop the

associated FOREIGN KEY constraint on the EMPLOYEES.DEPARTMENT_ID column.Eg: ALTER TABLE departments

DROP PRIMARY KEY CASCADE;Disabling Constraints:

• Execute the DISABLE clause of the ALTER TABLE statement to deactivate an integrity constraint.

• Apply the CASCADE option to disable dependent integrity constraints.

Eg: ALTER TABLE employeesDISABLE CONSTRAINT emp_emp_id_pk CASCADE;

Prepared by: Mr.O.Obulesu, Asst.professor [13]

Page 14: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Enabling Constraints: Activate an integrity constraint currently disabled in the table definition by using the

ENABLE clause. Eg: ALTER TABLE employees

ENABLE CONSTRAINT emp_emp_id_pk;• A UNIQUE or PRIMARY KEY index is automatically created if you enable a UNIQUE

key or PRIMARY KEY constraint.Cascading Constraints:

• The CASCADE CONSTRAINTS clause is used along with the DROP COLUMN clause.

• The CASCADE CONSTRAINTS clause drops all referential integrity constraints that refer to the primary and unique keys defined on the dropped columns.

• The CASCADE CONSTRAINTS clause also drops all multicolumn constraints defined on the dropped columns.Eg: ALTER TABLE test1

DROP (pk) CASCADE CONSTRAINTS;Eg: ALTER TABLE test1

DROP (pk, fk, col1) CASCADE CONSTRAINTS;Viewing Constraints:

Query the USER_CONSTRAINTS table to view all constraint definitions and names.Eg: SELECT constraint_name, constraint_type, search_condition

FROM user_constraints WHERE table_name = 'EMPLOYEES';

Viewing the Columns Associated with Constraints: View the columns associated with the constraint names in the USER_CONS_COLUMNS

view.Eg: SELECT constraint_name, column_name

FROM user_cons_columns WHERE table_name = 'EMPLOYEES';

Basic SELECT Statement:

Eg: SELECT *| {[DISTINCT] column|expression [alias],...} FROM table;

SELECT identifies what columns FROM identifies which tableSelecting All Columns:

Eg: SELECT * FROM r_departments;

Selecting Specific Columns:

Eg: SELECT department_id, location_id FROM r_departments;

Writing SQL Statements:

Prepared by: Mr.O.Obulesu, Asst.professor [14]

Page 15: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• SQL statements are not case sensitive. • SQL statements can be on one or more lines.• Keywords cannot be abbreviated or split across lines.• Clauses are usually placed on separate lines.• Indents are used to enhance readability.•

Column Heading Defaults:

• iSQL*Plus:– Default heading justification: Center– Default heading display: Uppercase

• SQL*Plus:– Character and Date column headings are left- justified– Number column headings are right-justified– Default heading display: Uppercase

Arithmetic Expressions Create expressions with number and date data by using arithmetic operators.

Operator Description+ Addition- Subtraction* Multiplication/ Division

Using Arithmetic Operators in SQL:

Eg: SELECT last_name, salary, salary + 300 FROM r_employees;

Operator Precedence:*, /,+,-.

• Multiplication and division take priority over addition and subtraction.• Operators of the same priority are evaluated from left to right.• Parentheses are used to force prioritized evaluation and to clarify statements.

Eg: SELECT last_name, salary, 12*salary+100 FROM r_employees;

Defining a Null Value:

Prepared by: Mr.O.Obulesu, Asst.professor [15]

Page 16: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• A null is a value that is unavailable, unassigned, unknown, or inapplicable.• A null is not the same as zero or a blank space

Eg: SELECT last_name, job_id, salary, commission_pct FROM r_employees;

Null Values in Arithmetic Expressions: Arithmetic expressions containing a null value evaluate to null.

Eg: SELECT last_name, 12*salary*commission_pct FROM r_employees;

Defining a Column Alias:A column alias:

• Renames a column heading• Is useful with calculations• Immediately follows the column name - there can also be the optional AS keyword

between the column name and alias• Requires double quotation marks if it contains spaces or special characters or is case

sensitive Syntax Using Column Aliases:

Eg: SELECT last_name AS name, commission_pct AS commFROM r_employees;

Result:

Eg: SELECT last_name "Name", salary*12 "Annual Salary" FROM employees;

Result:

Concatenation Operator:A concatenation operator

Prepared by: Mr.O.Obulesu, Asst.professor [16]

Page 17: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• Concatenates columns or character strings to other columns • Is represented by two vertical bars (||)• Creates a resultant column that is a character expression

Using the Concatenation Operator:Eg: SELECT last_name || job_id AS "Employees"

FROM r_employees; Result:

Literal Character Strings:• A literal is a character, a number, or a date included in the SELECT list.• Date and character literal values must be enclosed within single quotation marks.• Each character string is output once for each

row returned.•

Using Literal Character Strings:Eg: SELECT last_name || ' is a ' || job_id AS "Employee Details"

FROM r_employees; Result:

Duplicate Rows: The default display of queries is all rows, including duplicate rows.

Eg: SELECT department_id FROM r_employees; Result:

Prepared by: Mr.O.Obulesu, Asst.professor [17]

Page 18: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Eliminating Duplicate Rows: Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause.

Eg: SELECT DISTINCT department_idFROM r_employees;

SQL Statements Versus i SQL*Plus Commands

SQL:• A language• ANSI standard• Keyword cannot be abbreviated• Statements manipulate data and table definitions in the database

SQL*Plus:• An environment• Oracle proprietary• Keywords can be abbreviated• Commands do not allow manipulation of values in the database• Runs on a browser

Prepared by: Mr.O.Obulesu, Asst.professor [18]

SQLSQLStatementsStatements

Page 19: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• Centrally loaded, does not have to be implemented on each machine

Overview of i SQL*Plus:

After you log into iSQL*Plus, you can:

• Describe the table structure• Edit your SQL statement• Execute SQL from iSQL*Plus• Save SQL statements to files and append SQL statements to files• Execute statements stored in saved files• Load commands from a text file into the iSQL*Plus Edit window

Displaying Table Structure:

Use the SQL*Plus DESCRIBE command to display the structure of a table.

Eg: DESC [RIBE] tablename;

Displaying Table Structure:

Restricting and Sorting Data In SQL:

Limiting Rows Using a Selection:

Prepared by: Mr.O.Obulesu, Asst.professor [19]

SQL*PlusSQL*Pluscommandscommands

Page 20: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

“Retrieve all Employees In department 90”

Limiting the Rows Selected:

• Restrict the rows returned by using the WHERE clause.Eg: SELECT *| {[DISTINCT] column|expression [alias],...}

FROM table [WHERE condition(s)];

• The WHERE clause follows the FROM clause.•

Using the WHERE Clause:

Eg: SELECT employee_id, last_name, job_id, department_idFROM r_employeesWHERE department_id = 90;

Character Strings and Dates:• Character strings and date values are enclosed in single quotation marks.• Character values are case sensitive, and date values are format sensitive.• The default date format is DD-MON-YY.Eg: SELECT last_name, job_id, department_id FROM r_employees WHERE last_name = 'Whalen';

Comparison Conditions:

Operator Description= Equal To

Prepared by: Mr.O.Obulesu, Asst.professor [20]

Page 21: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

> Greater Than< Less than

>= Greater Than or Equal to<= Less than or equal to

!= or <> Not Equal To

Using Comparison Conditions:Eg: SELECT last_name, salary

FROM r_employees WHERE salary <= 3000;

Other Comparison Conditions:Operator Description

BETWEEN …….. AND …..... Between two values (inclusive),

IN(set) Match any of a list of values

LIKE Match a character pattern

IS NULL Is a null value

Using the BETWEEN Condition:

Use the BETWEEN condition to display rows based on a range of values.Eg: SELECT last_name, salary

FROM r_employees WHERE salary BETWEEN 2500 AND 3500;

Using the IN Condition:

Use the IN membership condition to test for values in a list.

Eg: SELECT employee_id, last_name, salary, manager_idFROM r_employeesWHERE manager_id IN (100, 101, 201);

Using the LIKE Condition:• Use the LIKE condition to perform wildcard searches of valid search string values.• Search conditions can contain either literal characters or numbers:

% denotes zero or many characters. _ denotes one character.

Using the NULL Conditions:

Test for nulls with the IS NULL operator

Prepared by: Mr.O.Obulesu, Asst.professor [21]

Page 22: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Eg: SELECT last_name, manager_id FROM r_employees

WHERE manager_id IS NULL;

Logical Conditions:

AND Returns TRUE if both component conditions are true

OR Returns TRUE if either any component condition is true

NOT Returns TRUE if the following condition is false

Using the AND Operator:

AND requires both conditions to be true

Eg: SELECT employee_id, last_name, job_id, salaryFROM r_employeesWHERE salary >=10000

AND job_id LIKE '%MAN%';

Using the OR Operator:

OR requires either any one condition is to be true.

Eg: SELECT employee_id, last_name, job_id, salaryFROM r_employeesWHERE salary >= 10000OR job_id LIKE '%MAN%';

Using the NOT Operator:

Eg: SELECT last_name, job_idFROM r_employees WHERE job_id

NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP');

Prepared by: Mr.O.Obulesu, Asst.professor [22]

Page 23: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Result:

Rules of Precedence:

Order Evaluated Operator1 Arithmetic operators2 Concatenation operator3 Comparison conditions4 IS [NOT] NULL, LIKE, [NOT] IN5 [NOT] BETWEEN6 NOT logical condition7 AND logical condition8 OR logical condition

Override rules of precedence by using parentheses.

Eg: SELECT last_name, job_id, salaryFROM r_employeesWHERE job_id = 'SA_REP'OR job_id = 'AD_PRES'AND salary > 15000;

Result:

Use parentheses to force priority.

Eg: SELECT last_name, job_id, salaryFROM r_employeesWHERE (job_id = 'SA_REP'OR job_id = 'AD_PRES')AND salary > 15000;

Prepared by: Mr.O.Obulesu, Asst.professor [23]

Page 24: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

ORDER BY Clause:• Sort rows with the ORDER BY clause

– ASC: ascending order, default– DESC: descending order

• The ORDER BY clause comes last in the SELECT statement.•

Eg: SELECT last_name, job_id, department_id, hire_date FROM r_employees ORDER BY hire_date; Result:

Sorting in Descending Order:

Eg: SELECT last_name, job_id, department_id, hire_dateFROM r_employeesORDER BY hire_date DESC ;

Result:

Sorting by Column Alias:

Eg: SELECT employee_id, last_name, salary*12 as annsalFROM r_employeesORDER BY annsal;

Prepared by: Mr.O.Obulesu, Asst.professor [24]

Page 25: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Result:

Sorting by Multiple Columns:

The order of “ORDER BY” list is the order of sortEg: SELECT last_name, department_id, salary

FROM r_employeesORDER BY department_id, salary DESC;

Result:

• You can sort by a column that is not in the SELECT list.

SQL Functions:

FunctionInput

arg 1

arg 2

arg n

Function performs action

Output

Resultvalue

Prepared by: Mr.O.Obulesu, Asst.professor [25]

Page 26: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

FunctionInput

arg 1

arg 2

arg n

Function performs action

Output

Resultvalue

Two Types of SQL Functions:

Functions

Single-row functions

Multiple-rowfunctions

Single-Row Functions:• Manipulate data items• Accept arguments and return one value• Act on each row returned• Return one result per row• May modify the data type• Can be nested• Accept arguments which can be a column or an expression

function_name [( arg1, arg2,... )]

Prepared by: Mr.O.Obulesu, Asst.professor [26]

Page 27: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Conversion

Character

Number

Date

GeneralSingle-row functions

Character FunctionsCharacterfunctions

LOWERUPPERINITCAP

CONCATSUBSTRLENGTHINSTRLPAD | RPADTRIMREPLACE

Case-manipulation functions

Character-manipulationfunctions

LOWER CONCATUPPER SUBSTRINITCAP LENGTH

INSTR LPAD TRIM REPLACE

Case Manipulation Functions:

These functions convert case for character strings.Function Result

LOWER('SQL Course') UPPER('SQL Course')

INITCAP('SQL Course')

sql course SQL COURSE Sql Course

Prepared by: Mr.O.Obulesu, Asst.professor [27]

Page 28: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Using Case Manipulation Functions:

Display the employee number, name, and department number for employee Higgins:

Eg: SELECT employee_id, last_name, department_idFROM employeesWHERE last_name = 'higgins';

No rows selected

Eg: SELECT employee_id, last_name, department_idFROM employeesWHERE LOWER (last_name) = 'higgins';

Character-Manipulation Functions: These functions manipulate character strings:

CONCAT('Hello', 'World') SUBSTR('HelloWorld',1,5) LENGTH('HelloWorld') INSTR('HelloWorld', 'W') LPAD(salary,10,'*') RPAD(salary, 10, '*') TRIM('H' FROM 'HelloWorld')

Result: HelloWorld Hello 10 6 *****24000 24000***** elloWorld

Using the Character-Manipulation Functions:Eg: 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';

Prepared by: Mr.O.Obulesu, Asst.professor [28]

Page 29: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Number Functions:

ROUND: Rounds value to specified decimalROUND (45.926, 2) output: 45.93

TRUNC: Truncates value to specified decimalTRUNC (45.926, 2) output: 45.92

MOD: Returns remainder of divisionMOD (1600, 300) output: 100

Using the ROUND Function:

Eg: SELECT ROUND (45.923, 2), ROUND (45.923, 0), ROUND (45.923,-1) FROM DUAL;

Using the TRUNC Function:Eg: SELECT TRUNC (45.923, 2), TRUNC (45.923), TRUNC (45.923,-2)

FROM DUAL;Using the MOD Function:

Calculate the remainder of a salary after it is divided by 5000 for all employees whose job title is sales representative.Eg: SELECT last_name, salary, MOD (salary, 5000)

FROM employeesWHERE job_id = 'SA_REP';

Result:

Working with Dates:

• Oracle database stores dates in an internal numeric format: century, year, month, day, hours, minutes, and seconds.

• The default date display format is DD-MON-RR.– Allows you to store 21st century dates in the 20th century by specifying only the last

two digits of the year. – Allows you to store 20th century dates in the 21st century in the same way.

Eg: SELECT last_name, hire_date FROM employeesWHERE last_name like 'G%';

Prepared by: Mr.O.Obulesu, Asst.professor [29]

Page 30: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Result:

Working with Dates: SYSDATE is a function that returns:

• Date • Time

Arithmetic with Dates:• Add or subtract a number to or from a date for a resultant date value.• Subtract two dates to find the number of days between those dates.• Add hours to a date by dividing the number of hours by 24.

Using Arithmetic Operators with Dates:Eg: SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS

FROM employeesWHERE department_id = 90;

Result:

Date Functions:

MONTHS_BETWEEN Number of months between two dates

ADD_MONTHS Add calendar months to date

NEXT_DAY Next day of the date specifiedLAST_DAY Last day of the monthROUND Round dateTRUNC Truncate date

Using Date Functions:

• MONTHS_BETWEEN ('01-SEP-95','11-JAN-94') Output: 19.6774194• ADD_MONTHS ('11-JAN-94',6) ; Output: '11-JUL-94'• NEXT_DAY ('01-SEP-95','FRIDAY') ; Output: '08-SEP-95'• LAST_DAY('01-FEB-95'); Output: '28-FEB-95'

Conversion Functions: Conversion Functions are of two types.

1. Implicit Conversion2. Explicit Conversion.

Implicit Data Type Conversion:

Prepared by: Mr.O.Obulesu, Asst.professor [30]

Page 31: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

For assignments, the Oracle server can automaticallyConvert the following:

Varchar2 - Number Number - Varchar2 Varchar2 - Date Date - Varchar2

Explicit Data Type Conversions: Number to Character - To_Char Character to Number - To_Char Character to Date - To_Date Date to Character - To_Char.

Using the TO_CHAR Function with Dates:

TO_CHAR (date, 'format_model')The format model:

• Must be enclosed in single quotation marks and is case sensitive• Can include any valid date format element• Has an fm element to remove padded blanks or suppress leading zeros• Is separated from the date value by a comma

Elements of the Date Format Model:

YYYY-Full year in numbers YY- last two numbers in a year

Using the TO_CHAR Function with Dates:

Eg: SELECT last_name, TO_CHAR (hire_date, 'fmDD Month YYYY') AS HIREDATE

FROM employees;

Using the TO_CHAR Function with Numbers: TO_CHAR(number, 'format_model')

9

Prepared by: Mr.O.Obulesu, Asst.professor [31]

Page 32: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

0$L

Eg: SELECT TO_CHAR(salary, '$99,999.00') SALARYFROM employeesWHERE last_name = 'Ernst';

Using the TO_NUMBER and TO_DATE Functions:

• Convert a character string to a number format using the TO_NUMBER function:

• Convert a character string to a date format using the TO_DATE function:

• These functions have an fx modifier. This modifier specifies the exact matching for the character argument and date format model of a TO_DATE function

• Convert a character string to a number format using the TO_NUMBER function:

• Convert a character string to a date format using the TO_DATE function:

• These functions have an fx modifier. This modifier specifies the exact matching for the character argument and date format model of a TO_DATE function

Nesting Functions

• Single-row functions can be nested to any level.• Nested functions are evaluated from deepest level to the least deep level.

F3 (F2 (F1 (col, arg1), arg2), arg3)Eg: SELECT last_name, NVL (TO_CHAR (manager_id), 'No Manager') FROM employees WHERE manager_id IS NULL;

Result:

General Functions: These functions work with any data type and pertain to using nulls.

Prepared by: Mr.O.Obulesu, Asst.professor [32]

Page 33: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• NVL (expr1, expr2)• NVL2 (expr1, expr2, expr3)• NULLIF (expr1, expr2)• COALESCE (expr1, expr2, ..., exprn)

NVL Function: Converts a null to an actual value.

• Data types that can be used are date, character, and number.• Data types must match:

– NVL(commission_pct,0)– NVL(hire_date,'01-JAN-97')– NVL(job_id,'No Job Yet')

Using the NVL Function:Eg: SELECT last_name, salary, NVL (commission_pct, 0), (Salary*12) + (salary*12*NVL (commission_pct, 0)) AN_SAL FROM employees;

Using the NVL2 Function:Eg: SELECT last_name, salary, commission_pct, NVL2 (commission_pct, 'SAL+COMM', 'SAL') income

FROM employees WHERE department_id IN (50, 80);

Using the NULLIF Function:Eg: SELECT first_name, LENGTH(first_name) "expr1", last_name, LENGTH(last_name) "expr2", NULLIF(LENGTH(first_name), LENGTH(last_name)) result

FROM employees;

Result:

Using the COALESCE Function:

Prepared by: Mr.O.Obulesu, Asst.professor [33]

Page 34: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• The advantage of the COALESCE function over the NVL function is that the COALESCE function can take multiple alternate values.

• If the first expression is not null, it returns that expression; otherwise, it does a COALESCE of the remaining expressions.

Eg: SELECT last_name, COALESCE (commission_pct, salary, 10) comm

FROM employees ORDER BY commission_pct;

Conditional Expressions:• Provide the use of IF-THEN-ELSE logic within a SQL statement• Use two methods:

– CASE expression– DECODE function

The CASE Expression: Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE statement:

CASE expr WHEN comparison_expr1 THEN return_expr1 [WHEN comparison_expr2 THEN return_expr2 WHEN comparison_exprn THEN return_exprn ELSE else_expr]END

Using the CASE Expression: Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE statement:

Eg: SELECT last_name, job_id, salary, CASE job_id WHEN 'IT_PROG’ THEN 1.10*salary WHEN 'ST_CLERK' THEN 1.15*salary WHEN 'SA_REP' THEN 1.20*salary ELSE salary END "REVISED_SALARY"

FROM employees;

Prepared by: Mr.O.Obulesu, Asst.professor [34]

Page 35: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

The DECODE Function: Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement:

DECODE (col|expression, search1, result1 [, search2, result2,...,] [, default])

Using the DECODE Function:Eg: SELECT last_name, job_id, salary, DECODE (job_id, 'IT_PROG', 1.10*salary, 'ST_CLERK', 1.15*salary, 'SA_REP', 1.20*salary, salary) REVISED_SALARY

FROM employees;

Using the DECODE Function: Display the applicable tax rate for each employee in department 80.

SELECT last_name, salary, DECODE (TRUNC(salary/2000, 0), 0, 0.00, 1, 0.09, 2, 0.20, 3, 0.30, 4, 0.40, 5, 0.42, 6, 0.44, 0.45) TAX_RATE FROM employees WHERE department_id = 80;

Obtaining Data from Multiple Tables:Using Cartesian Products:

• A Cartesian product is formed when:– A join condition is omitted– A join condition is invalid– All rows in the first table are joined to all rows in the second table

• To avoid a Cartesian product, always include a valid join condition in a WHERE clause.Generating a Cartesian product: (20 rows)

(8 rows)

Prepared by: Mr.O.Obulesu, Asst.professor [35]

Page 36: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

(20*8=160 rows)

Types of Joins: Oracle Proprietary Joins (8i and prior):

• Equijoin• Non-equijoin• Outer join• Self join

SQL: 1999 Compliant Joins:

• Cross joins• Natural joins• Using clause• Full or two sided outer joins• Arbitrary join conditions for outer joins

Joining Tables Using Oracle Syntax: Use a join to query data from more than one table.

Eg: SELECT table1.column, table2.columnFROM table1, table2

WHERE table1.column1 = table2.column2;• Write the join condition in the WHERE clause.• Prefix the column name with the table name when the same column name appears in more

than one table.

Prepared by: Mr.O.Obulesu, Asst.professor [36]

Page 37: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

What is an Equijoin?

Retrieving Records with Equijoins:

Prepared by: Mr.O.Obulesu, Asst.professor [37]

Page 38: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Eg: SELECT employees.employee_id, employees.last_name, employees.department_id, departments.department_id, departments.location_id

FROM employees, departmentsWHERE employees.department_id = departments.department_id;

Qualifying Ambiguous Column Names

• Use table prefixes to qualify column names that are in multiple tables.• Improve performance by using table prefixes.• Distinguish columns that have identical names but reside in different tables by using

column aliases.

Using Table Aliases

• Simplify queries by using table aliases.• Improve performance by using table prefixes.

Eg: SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e, departments d WHERE e.department_id = d.department_id;

Joining More than Two Tables: To join n tables together, you need a minimum of n-1 join conditions. For example, to join

three tables, a minimum of two joins is required.

To join n tables together, you need a minimum of n-1 join conditions. For example, to join three tables, a minimum of two joins is required

Non-Equijoins: Salary in the EMPLOYEES table must be between Lowest salary and highest salary in the JOB_GRADES table.

Retrieving Records with Non-Equijoins:

Eg: SELECT e.last_name, e.salary, j.grade_levelFROM employees e, job_grades jWHERE e.salary BETWEEN j.lowest_sal AND j.highest_sal;

Outer Joins:

Prepared by: Mr.O.Obulesu, Asst.professor [38]

Page 39: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• You use an outer join to also see rows that do not meet the join condition.• The Outer join operator is the plus sign (+).

Eg: (1) SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column (+) = table2.column;

Eg: (2) SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column = table2.column (+);

Using Outer Joins:

Eg: SELECT e.last_name, e.department_id, d.department_nameFROM employees e, departments dWHERE e.department_id(+) = d.department_id ;

Self Joins:

Joining a Table to Itself:

Eg: SELECT worker.last_name || ' works for ' || manager.last_nameFROM employees worker, employees managerWHERE worker.manager_id = manager.employee_id;

Prepared by: Mr.O.Obulesu, Asst.professor [39]

Page 40: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Joining Tables Using SQL: 1999 Syntax

Eg: SELECT table1.column, table2.columnFROM table1[CROSS JOIN table2] |[NATURAL JOIN table2] |[JOIN table2 USING (column_name)] |[JOIN table2 ON(table1.column_name = table2.column_name)] |[LEFT|RIGHT|FULL OUTER JOIN table2 ON (table1.column_name = table2.column_name)];

Creating Cross Joins:

• The CROSS JOIN clause produces the cross-product of two tables. • This is the same as a Cartesian product between the two tables.

Eg: SELECT last_name, department_nameFROM employeesCROSS JOIN departments;

Creating Natural Joins:

• The NATURAL JOIN clause is based on all columns in the two tables that have the same name.

• It selects rows from the two tables that have equal values in all matched columns.• If the columns having the same names have different data types, an error is returned.

Retrieving Records with Natural Joins:

Eg: SELECT department_id, department_name, location_id, city

FROM departmentsNATURAL JOIN locations ;

Prepared by: Mr.O.Obulesu, Asst.professor [40]

Page 41: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Creating Joins with the USING Clause:

• If several columns have the same names but the data types do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an equijoin.

• Use the USING clause to match only one column when more than one column matches.• Do not use a table name or alias in the referenced columns.• The NATURAL JOIN and USING clauses are mutually exclusive.

Retrieving Records with the USING Clause:

Eg: SELECT e.employee_id, e.last_name, d.location_idFROM employees e JOIN departments dUSING (department_id);

Result:

Creating Joins with the ON Clause:

• The join condition for the natural join is basically an equijoin of all columns with the same name.

• To specify arbitrary conditions or specify columns to join, the ON clause is used.

Prepared by: Mr.O.Obulesu, Asst.professor [41]

Page 42: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• The join condition is separated from other search conditions.• The ON clause makes code easy to understand.

Retrieving Records with the ON Clause:

Eg: SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id

FROM employees e JOIN departments dON (e.department_id = d.department_id);

Creating Three-Way Joins with the ON Clause:

Eg: SELECT employee_id, city, department_nameFROM employees e JOIN departments dON d.department_id = e.department_id JOIN locations lON d.location_id = l.location_id;

INNER versus OUTER Joins:

• In SQL: 1999, the join of two tables returning only matched rows is an inner join.• A join between two tables that returns the results of the inner join as well as unmatched rows

left (or right) tables is a left (or right) outer join.• A join between two tables that returns the results of an inner join as well as the results of a

left and right join is a full outer join.LEFT OUTER JOIN:Eg: SELECT e.last_name, e.department_id, d.department_name

FROM employees eLEFT OUTER JOIN departments dON (e.department_id = d.department_id);

Result:

RIGHT OUTER JOIN:Eg: SELECT e.last_name, e.department_id, d.department_name

FROM employees eRIGHT OUTER JOIN departments dON (e.department_id = d.department_id);

Result:

FULL OUTER JOIN:

Prepared by: Mr.O.Obulesu, Asst.professor [42]

Page 43: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Eg: SELECT e.last_name, e.department_id, d.department_nameFROM employees eFULL OUTER JOIN departments dON (e.department_id = d.department_id);

[

Additional Conditions:

Eg: SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id

FROM employees e JOIN departments dON (e.department_id = d.department_id)AND e.manager_id = 149;

Aggregating Data Using Group Functions:

Group functions operate on sets of rows to give one result per group.

Prepared by: Mr.O.Obulesu, Asst.professor [43]

Max (Salary)

24000

Page 44: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Types of Group Functions:• AVG • COUNT • MAX• MIN • STDDEV • SUM• VARIANCE

Group Functions Syntax:SELECT [column,] group_function (column), ...FROM table[WHERE condition][GROUP BY column][ORDER BY column];

Group Functions Syntax:SELECT [column,] group_function (column), ...FROM table[WHERE condition][GROUP BY column][ORDER BY column];

Using the AVG and SUM Functions:

Eg: SELECT AVG (salary), MAX (salary), MIN (salary), SUM (salary)

FROM employees WHERE job_id LIKE '%REP%';

Using the MIN and MAX Functions: You can use MIN and MAX for any data type.Eg: SELECT MIN (hire_date), MAX (hire_date)

FROM employees;Using the COUNT Function:

COUNT (*) returns the number of rows in a table. Eg: SELECT COUNT (*)

FROM employeesWHERE department_id = 50;

• COUNT (expr) returns the number of rows with non-null values for the expr.

Prepared by: Mr.O.Obulesu, Asst.professor [44]

Page 45: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• Display the number of department values in the EMPLOYEES table, excluding the null values.

Eg: SELECT COUNT (commission_pct)FROM employeesWHERE department_id = 80;

Using the DISTINCT Keyword:

• COUNT (DISTINCT expr) returns the number of distinct non-null values of the expr.• Display the number of distinct department values in the EMPLOYEES table.

Eg: SELECT COUNT (DISTINCT department_id) FROM employees;

Group Functions and Null Values:

Group functions ignore null values in the column.

Eg: SELECT AVG (commission_pct)FROM employees;

Using the NVL Function with Group Functions: The NVL function forces group functions to include null values.

Eg: SELECT AVG (NVL (commission_pct, 0))FROM employees;

Creating Groups of Data:

EMPLOYEES

Prepared by: Mr.O.Obulesu, Asst.professor [45]

Page 46: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Fig: The average salary in EMPLOYEES table for each department.

Creating Groups of Data: The GROUP BY Clause Syntax:

SELECT column, group_function (column)FROM table[WHERE condition][GROUP BY group_by_expression][ORDER BY column];

Divide rows in a table into smaller groups by using the GROUP BY clause.

Using the GROUP BY Clause :

All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.

Eg: SELECT department_id, AVG (salary)FROM employeesGROUP BY department_id;

Prepared by: Mr.O.Obulesu, Asst.professor [46]

Page 47: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Using the GROUP BY Clause:

The GROUP BY column does not have to be in the SELECT list.

Eg: SELECT AVG (salary)FROM employeesGROUP BY department_id;

Grouping by More Than One Column:

Prepared by: Mr.O.Obulesu, Asst.professor [47]

Page 48: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Fig: “Add up the salaries in the EMPLOYEES table for each job, grouped by department.

Using the GROUP BY Clause on Multiple Columns:

Prepared by: Mr.O.Obulesu, Asst.professor [48]

Page 49: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Eg: SELECT department_id dept_id, job_id, SUM (salary) FROM employeesGROUP BY department_id, job_id;

Illegal Queries Using Group Functions:

Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause.

Eg: SELECT department_id, COUNT (last_name)FROM employees;

SELECT department_id, COUNT(last_name) *ERROR at line 1:ORA-00937: not a single-group group functions

Column missing in the GROUP BY clause:

Prepared by: Mr.O.Obulesu, Asst.professor [49]

Page 50: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Excluding Group Results:

Fig: Maximum Salary per department when it is greater than 10000

Excluding Group Results: The HAVING ClauseUse the HAVING clause to restrict groups:1. Rows are grouped.2. The group function is applied.3. Groups matching the HAVING clause are displayed.

SELECT column, group_functionFROM table[WHEREcondition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column];

Using the HAVING Clause:

Prepared by: Mr.O.Obulesu, Asst.professor [50]

Page 51: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Eg: SELECT department_id, MAX (salary)FROM employeesGROUP BY department_idHAVING MAX (salary)>10000;

Using the HAVING Clause:

Eg: SELECT job_id, SUM (salary) PAYROLLFROM employeesWHERE job_id NOT LIKE '%REP%'GROUP BY job_idHAVING SUM (salary) > 13000ORDER BY SUM (salary);

Nesting Group Functions:

Eg: SELECT MAX (AVG (salary))FROM employeesGROUP BY department_id;

Subqueries: Using a Subquery to Solve a Problem like “Who has a salary greater than Abel’s?”

Main Query: Which employees have salaries greater than Abel’s salary?

Subquery:

What is Abel’s salary?

Subquery Syntax:

Prepared by: Mr.O.Obulesu, Asst.professor [51]

Page 52: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Eg: SELECT select_listFROM tableWHERE expr operator

(SELECT select_list FROM table);

• The subquery (inner query) executes once before the main query.• The result of the subquery is used by the main query (outer query).

Using a Subquery:

Eg: SELECT last_nameFROM employeesWHERE salary >

(SELECT salary FROM employees WHERE last_name = 'Abel');

Result:

Guidelines for Using Subqueries:

• Enclose subqueries in parentheses. • Place subqueries on the right side of the comparison condition.• The ORDER BY clause in the subquery is not needed unless you are performing Top-N

analysis.• Use single-row operators with single-row subqueries and use multiple-row operators with

multiple-row subqueries.Types of Subqueries:

Single-row subquery

Multiple Row Subquery

Single-Row Subqueries:

Prepared by: Mr.O.Obulesu, Asst.professor [52]

Main Query

Sub QueryST_CLERK

Page 53: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• Return only one row• Use single-row comparison operators

Eg: =, <, >. <=, >= etc.

Executing Single-Row Subqueries:

Eg: SELECT last_name, job_id, salaryFROM employeesWHERE job_id =

(SELECT job_id FROM employees WHERE employee_id = 141)

AND salary > (SELECT salary FROM employees WHERE employee_id = 143);

Using Group Functions in a Subquery:

Eg: SELECT last_name, job_id, salaryFROM employeesWHERE salary =

(SELECT MIN (salary) FROM employees);

The HAVING Clause with Subqueries:

• The Oracle server executes subqueries first.• The Oracle server returns results into the HAVING clause of the main query.

Eg: SELECT department_id, MIN (salary)FROM employeesGROUP BY department_idHAVING MIN (salary) >

(SELECT MIN (salary) FROM employees WHERE department_id = 50);

The HAVING Clause with Subqueries:

Prepared by: Mr.O.Obulesu, Asst.professor [53]

Page 54: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• The Oracle server executes subqueries first.• The Oracle server returns results into the HAVING clause of the main query

Eg: SELECT department_id, MIN (salary)FROM employeesGROUP BY department_idHAVING MIN (salary) >

(SELECT MIN (salary) FROM employees WHERE department_id = 50);

1.What is wrong with this Statement?

Eg: SELECT employee_id, last_nameFROM employeesWHERE salary =

(SELECT MIN (salary) FROM employees GROUP BY department_id);

ERROR at line 4:ORA-01427: single-row subquery returns more thanone row

Single-row operator with multiple-row subquery

2. Will this Statement Return Rows?

Eg: SELECT last_name, job_idFROM employeesWHERE job_id =

(SELECT job_id FROM employees WHERE last_name = 'Haas');

No rows selected

Multiple-Row Subqueries:

• Return more than one row• Use multiple-row comparison operators

Eg: IN, ANY, ALL.

Using the ANY Operator in Multiple-Row Subqueries:

Prepared by: Mr.O.Obulesu, Asst.professor [54]

Page 55: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Eg: SELECT employee_id, last_name, job_id, salaryFROM employeesWHERE salary < ANY

(SELECT salary FROM employees WHERE job_id = 'IT_PROG')

AND job_id <> 'IT_PROG';

Using the ALL Operator InMultiple-Row Subqueries:

Eg: SELECT employee_id, last_name, job_id, salaryFROM employeesWHERE salary < ALL

(SELECT salary FROM employees WHERE job_id = 'IT_PROG')

AND job_id <> 'IT_PROG';

Null Values in a Subquery:Eg: SELECT emp.last_name

FROM employees empWHERE emp.employee_id NOT IN

(SELECT mgr.manager_id FROM employees mgr);

Creating Views:Database ObjectsTABLE - Basic unit of storage; composed of rows and columnsVIEW - Logically represents subsets of data from one or more tablesSEQUENCE - Generates primary key values INDEX - Improves the performance of some queriesSYNONYM - Alternative name for an object

What is a View?Why Use Views?

• To restrict data access

Prepared by: Mr.O.Obulesu, Asst.professor [55]

Page 56: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• To make complex queries easy• To provide data independence• To present different views of the same data

Simple Views and Complex Views:

Feature Simple Views Complex Views Number of tables One One or moreContain functions No YesContain groups of data No YesDML operations through a view, Yes Not always

Creating a View:

• You embed a subquery within the CREATE VIEW statement.

Eg: CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias [, alias]...)] AS subquery

[WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY [CONSTRAINT constraint]];

• The subquery can contain complex SELECT syntax.• Create a view, EMPVU80 that contains details of employees in department 80.

Eg: CREATE VIEW empvu80 AS SELECT employee_id, last_name, salary FROM employees WHERE department_id = 80;

Retrieving Data from a View:

Eg: SELECT * FROM empvu80;

Querying a View:

Eg: SELECT *FROM empvu80;

Prepared by: Mr.O.Obulesu, Asst.professor [56]

Page 57: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Modifying a View:

Modify the EMPVU80 view by using CREATE OR REPLACE VIEW clause. Add an alias for each column name.

Eg: CREATE OR REPLACE VIEW empvu80 (id_number, name, sal, department_id)

AS SELECT employee_id, first_name || ' ' || last_name, salary, department_id FROM employees WHERE department_id = 80;

• Column aliases in the CREATE VIEW clause are listed in the same order as the columns in the subquery.

Creating a Complex View:

Eg: CREATE VIEW dept_sum_vu (Name, minsal, maxsal, avgsal)

AS SELECT d.department_name, MIN (e.salary), MAX (e.salary), AVG (e.salary) FROM employees e, departments d WHERE e.department_id = d.department_id GROUP BY d.department_name;

Rules for Performing DML Operations on a View:

Prepared by: Mr.O.Obulesu, Asst.professor [57]

USER_VIEWSUSER_VIEWS EMPVU80EMPVU80SELECT employee_id, last_name,salaryFROM employeesWHERE department_id=80;

Page 58: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• You can perform DML operations on simple views. • You cannot remove a row if the view contains the following:

– Group functions– A GROUP BY clause– The DISTINCT keyword– The pseudocolumn ROWNUM keyword

You cannot modify data in a view if it contains:

• Group functions• A GROUP BY clause• The DISTINCT keyword• The pseudocolumn ROWNUM keyword• Columns defined by expressions• You can ensure that DML operations performed on the view stay within the domain of the

view by using the WITH CHECK OPTION clause.

Eg: CREATE OR REPLACE VIEW empvu20 AS SELECT *

FROM employees WHERE department_id = 20 WITH CHECK OPTION CONSTRAINT empvu20_ck;

• Any attempt to change the department number for any row in the view fails because it violates the WITH CHECK OPTION constraint.

Denying DML Operations:

• You can ensure that no DML operations occur by adding the WITH READ ONLY option to your view definition.

• Any attempt to perform a DML on any row in the view results in an Oracle server error.

Denying DML Operations:

Eg: CREATE OR REPLACE VIEW empvu10 (Employee_number, employee_name, job_title)

AS SELECT employee_id, last_name, job_id FROM employees WHERE department_id = 10 WITH READ ONLY;

Removing a View: You can remove a view without losing data because a view is based on underlying tables in

the database. DROP VIEW viewname;

Eg: DROP VIEW empvu80;

Inline Views:

Prepared by: Mr.O.Obulesu, Asst.professor [58]

Page 59: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• An inline view is a subquery with an alias (or correlation name) that you can use within a SQL statement.

• A named subquery in the FROM clause of the main query is an example of an inline view.• An inline view is not a schema object.

Top-N Analysis:

• Top-N queries ask for the n largest or smallest values of a column. For example:– What are the ten best selling products?– What are the ten worst selling products?

• Both largest values and smallest values sets are considered Top-N queries. • The high-level structure of a Top-N analysis query is: •

SELECT [column_list], ROWNUM FROM (SELECT [column_list] FROM table ORDER BY Top-N_column)WHERE ROWNUM <= N;

• To display the top three earner names and salaries from the EMPLOYEES table:

Eg: SELECT ROWNUM as RANK, last_name, salary FROM (SELECT last_name, salary FROM employees

ORDER BY salary DESC)WHERE ROWNUM <= 3;

Other Database Objects:

A sequence:• Automatically generates unique numbers• Is a sharable object• Is typically used to create a primary key value• Replaces application code• Speeds up the efficiency of accessing sequence values when cached in memory

The CREATE SEQUENCE Statement Syntax:

CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}];

Prepared by: Mr.O.Obulesu, Asst.professor [59]

Page 60: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• Create a sequence named DEPT_DEPTID_SEQ to be used for the primary key of the DEPARTMENTS table.

• Do not use the CYCLE option.

Eg: CREATE SEQUENCE dept_deptid_seq INCREMENT BY 10 START WITH 120 MAXVALUE 9999 NOCACHE NOCYCLE;

Sequence created.

Confirming Sequences:

• Verify your sequence values in the USER_SEQUENCES data dictionary table.

Eg: SELECT sequence_name, min_value, max_value, increment_by last_number

FROM user_sequences;

• The LAST_NUMBER column displays the next available sequence number if NOCACHE is specified.

NEXTVAL and CURRVAL Pseudocolumns:

• NEXTVAL returns the next available sequence value. It returns a unique value every time it is referenced, even for different users.

• CURRVAL obtains the current sequence value. • NEXTVAL must be issued for that sequence before CURRVAL contains a value.

Using a Sequence:

Eg: INSERT INTO departments (department_id, department_name, location_id)VALUES (dept_deptid_seq.NEXTVAL,'Support', 2500);

• Caching sequence values in memory gives faster access to those values.• Gaps in sequence values can occur when:

– A rollback occurs– The system crashes– A sequence is used in another table

• If the sequence was created with NOCACHE, view the next available value, by querying the USER_SEQUENCES table.

Modifying a Sequence:Eg: ALTER SEQUENCE dept_deptid_seq INCREMENT BY 20 MAXVALUE 999999

Prepared by: Mr.O.Obulesu, Asst.professor [60]

Page 61: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

NOCACHE NOCYCLE;

Guidelines for Modifying a Sequence:

• You must be the owner or have the ALTER privilege for the sequence.• Only future sequence numbers are affected.• The sequence must be dropped and

re-created to restart the sequence at a different number.• Some validation is performed

Removing a Sequence:

• Remove a sequence from the data dictionary by using the DROP SEQUENCE statement.• Once removed, the sequence can no longer be referenced

Eg: DROP SEQUENCE dept_deptid_seq;

Sequence dropped.

*What is an Index?

An index:• Is a schema object• Is used by the Oracle server to speed up the retrieval of rows by using a pointer• Can reduce disk I/O by using a rapid path access method to locate data quickly• Is independent of the table it indexes• Is used and maintained automatically by the Oracle server

*How Are Indexes Created?

• Automatically: A unique index is created automatically when you define a PRIMARY KEY or UNIQUE constraint in a table definition.

• Manually: Users can create nonunique indexes on columns to speed up access to the rows.

CREATE INDEX indexON table (column [, column]...);

• Improve the speed of query access to the LAST_NAME column in the EMPLOYEES table.

Eg: CREATE INDEX emp_last_name_idxON employees (last_name);

*When to Create an Index:

You should create an index if:• A column contains a wide range of values

Prepared by: Mr.O.Obulesu, Asst.professor [61]

Page 62: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• A column contains a large number of null values• One or more columns are frequently used together in a WHERE clause or a join condition• The table is large and most queries are expected to retrieve less than 2 to 4 percent of the

rows

*When Not to Create an Index: It is usually not worth creating an index if:

• The table is small• The columns are not often used as a condition in the query• Most queries are expected to retrieve more than 2 to 4 percent of the rows in the table• The table is updated frequently• The indexed columns are referenced as part of an expression•

*Confirming Indexes:• The USER_INDEXES data dictionary view contains the name of the index and its

uniqueness.• The USER_IND_COLUMNS view contains the index name, the table name, and the column

name.

Eg: SELECT ic.index_name, ic.column_name, ic.column_position col_pos, ix.uniquenessFROM user_indexes ix, user_ind_columns icWHERE ic.index_name = ix.index_nameAND ic.table_name = 'EMPLOYEES';

Function-Based Indexes:

• A function-based index is an index based on expressions. • The index expression is built from table columns, constants, SQL functions, and user-defined

functions.

Eg: CREATE INDEX upper_dept_name_idxON departments (UPPER (department_name));

Index created. Eg: SELECT *

FROM departmentsWHERE UPPER (department_name) = 'SALES';

Removing an Index:

• Remove an index from the data dictionary by using the DROP INDEX command.

DROP INDEX indexname;

• Remove the UPPER_LAST_NAME_IDX index from the data dictionary.

Eg: DROP INDEX upper_last_name_idx;

Index dropped.

Prepared by: Mr.O.Obulesu, Asst.professor [62]

Page 63: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• To drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege.

Synonyms:

Simplify access to objects by creating a synonym (another name for an object). With synonyms, you can:

• Ease referring to a table owned by another user• Shorten lengthy object names•

Eg: CREATE [PUBLIC] SYNONYM synonymFOR object;

Creating and Removing Synonyms:

Eg: CREATE SYNONYM d_sum FOR dept_sum_vu;

Synonym Created.

Eg: DROP SYNONYM d_sum;

Synonym dropped.

Controlling User Access Privileges:

• Database security:– System security– Data security

• System privileges: Gaining access to the database• Object privileges: Manipulating the content of the database objects• Schemas: Collections of objects, such as tables, views, and sequences

System Privileges:

• More than 100 privileges are available.• The database administrator has high-level system privileges for tasks such as:

– Creating new users– Removing users– Removing tables

– Backing up tablesCreating Users:

• The DBA creates users by using the CREATE USER statement.Eg: CREATE USER user

IDENTIFIED BY password;CREATE USER ScottIDENTIFIED BY tiger;

User created.

Prepared by: Mr.O.Obulesu, Asst.professor [63]

Page 64: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

User System Privileges:

• Once a user is created, the DBA can grant specific system privileges to a user.

Eg: GRANT privilege [, privilege...] TO user [, user| role, PUBLIC...];

• An application developer, for example, may have the following system privileges:– CREATE SESSION– CREATE TABLE– CREATE SEQUENCE– CREATE VIEW– CREATE PROCEDURE

Granting System Privileges:

Eg: GRANT create session, create table, create sequence, create view TO Scott;

Creating and Granting Privileges to a Role:Create a role

Eg: Create Role Manager;

Revoke Privileges:

Eg: REVOKE create session, create table, create sequence, create view FROM Scott;

Grant privileges to a role:

Eg: Grant Create table to Manager;

Changing Your Password:

• The DBA creates your user account and initializes your password.• You can change your password by using the ALTER USER statement.

Eg: ALTER USER Scott IDENTIFIED BY lion;

• Object privileges vary from object to object.• An owner has all the privileges on the object.• An owner can give specific privileges on that owner’s object

Grant query privileges on the EMPLOYEES table:

Eg: GRANT selectON employeesTO sue, rich;

-----------------------------------------END OF SQL -----------------------------------------

Prepared by: Mr.O.Obulesu, Asst.professor [64]

Page 65: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PL/SQL

Program 1: Creating Tables for Various relations

SQL> create table client_master (client_no varchar2 (6), name varchar2 (20), 2 city varchar2 (15), 3 state varchar2 (15), 4 pincode number (6), 5 bal_due number (10, 2));

Table created.

SQL> desc client_master;

Name Null? Type ----------------------------------------- -------- ---------------------------- CLIENT_NO VARCHAR2 (6) NAME VARCHAR2 (20) CITY VARCHAR2 (15) STATE VARCHAR2 (15) PINCODE NUMBER (6) BAL_DUE NUMBER (10, 2)

SQL> create table product_master (prduct_no varchar2 (10), 2 description varchar2 (20), 3 profit_percent number (3), 4 unit_measure varchar2 (5), 5 qty_on_hand number(6), 6 reorder number(6), 7 sell_price number(6), 8 cost_price number (6));

Table created.

SQL> desc product_master;

Name Null? Type ----------------------------------------------------- -------- ------------------------------------ PRDUCT_NO VARCHAR2 (10) DESCRIPTION VARCHAR2 (20) PROFIT_PERCENT NUMBER(3) UNIT_MEASURE VARCHAR2 (5) QTY_ON_HAND NUMBER(6) REORDER NUMBER(6) SELL_PRICE NUMBER(6) COST_PRICE NUMBER(6)

Prepared by: Mr.O.Obulesu, Asst.professor [65]

Page 66: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Program 2. To Perform DML operations on relations and Basic Queries

SQL> insert into product_master values ('p0001','1.44floppies', 5,'piece', 100, 20, 525, 500);

1 row created.

SQL> insert into product_master values ('p03453','monitors', 6,'piece', 10, 3, 12000, 11200);

1 row created.

SQL> insert into product_master values ('p06734','mouse',5,'piece',20,5,1050,500);

1 row created.

SQL> insert into product_master values ('p07865','1.22floppies',5,'piece',100,20,525,500);

1 row created.

SQL> insert into product_master values ('p07868','keyboards',2,'piece',10,3,3150,3050);

1 row created.

SQL> insert into product_master values ('p07885','cddrive', 2.5,'piece',10,3,5200,5100);

1 row created.

SQL> insert into product_master values ('p07965','540hdd',4,'piece',10,3,8400,8000);

1 row created.

SQL> insert into product_master values ('p07975','1.44drive',5,'piece',10,3,1050,1000);

1 row created.

SQL> insert into product_master values ('p08865','1.22drive',5,'piece',2,3,1050,1000);

1 row created.

Prepared by: Mr.O.Obulesu, Asst.professor [66]

Page 67: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL> insert into client_master (client_no, name, city, pincode, state, bal_due)2 values('&client_no', '&name', '&city', &pincode, '&state', &bal_due);

Enter value for client_no: 001Enter value for name: ivanEnter value for city: bombayEnter value for pincode: 400054Enter value for state: maharastraEnter value for bal_due: 15000old 2: values('&client_no','&name','&city',&pincode,'&state',&bal_due)new 2: values ('001','ivan','bombay',400054,'maharastra',15000)

1 row created.

SQL> /Enter value for client_no: 002Enter value for name: vandanaEnter value for city: madrasEnter value for pincode: 780001Enter value for state: tamilnaduEnter value for bal_due: 0old 2: values('&client_no','&name','&city',&pincode,'&state',&bal_due)new 2: values('002','vandana','madras',780001,'tamilnadu',0)

1 row created.SQL> /Enter value for client_no: 003Enter value for name: pramadaEnter value for city: bombayEnter value for pincode: 400057Enter value for state: maharastraEnter value for bal_due: 500old 2: values('&client_no','&name','&city',&pincode,'&state',&bal_due)new 2: values('003','pramada','bombay',400057,'maharastra',500)

1 row created.SQL> /Enter value for client_no: 004Enter value for name: basuEnter value for city: bombayEnter value for pincode: 400056Enter value for state: maharastraEnter value for bal_due: 0old 2: values('&client_no','&name','&city',&pincode,'&state',&bal_due)new 2: values('004','basu','bombay',400056,'maharastra',0)

1 row created.

Prepared by: Mr.O.Obulesu, Asst.professor [67]

Page 68: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL> /

Enter value for client_no: 005Enter value for name: raviEnter value for city: delhiEnter value for pincode: 100001Enter value for state: Enter value for bal_due: 2000old 2: values('&client_no','&name','&city',&pincode,'&state',&bal_due)new 2: values('005','ravi','delhi',100001,'',2000)

1 row created.

SQL> /

Enter value for client_no: 006Enter value for name: rukminiEnter value for city: bombayEnter value for pincode: 400050Enter value for state: maharastraEnter value for bal_due: 0old 2: values('&client_no','&name','&city',&pincode,'&state',&bal_due)new 2: values('006','rukmini','bombay',400050,'maharastra',0)

1 row created.

SQL> select * from product_master;

PRODUCT_NO DESCRIPTION PROFIT_PERCENT UNIT_MEASURE QTY_ON_HAND REORDER ---------- -------------------- -------------- ----- ----------- ---------- SELL_PRICE COST_PRICE ---------- ---------- p0001 1.44floppies 5 piece 100 20 525 1150 p03453 monitors 6 piece 10 3 12000 11200 p06734 mouse 5 piece 20 5 1050 500 PRODUCT_NO DESCRIPTION PROFIT_PERCENT UNIT_MEASURE QTY_ON_HAND REORDER ---------- -------------------- -------------- ----- ----------- ---------- SELL_PRICE COST_PRICE ---------- ---------- p07865 1.22floppies 5 piece 100 20 525 500 p07868 keyboards 2 piece 10 3 3150 3050 p07885 cddrive 3 piece 10 3 5200 5100

Prepared by: Mr.O.Obulesu, Asst.professor [68]

Page 69: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PRODUCT_NO DESCRIPTION PROFIT_PERCENT UNIT_MEASURE QTY_ON_HAND REORDER ---------- -------------------- -------------- ----- ----------- ---------- SELL_PRICE COST_PRICE ---------- ---------- p07965 540hdd 4 piece 10 3 8400 8000 p07975 1.44drive 5 piece 10 3 1050 1000 p08865 1.22drive 5 piece 2 3 1050 1000

9 rows selected.SQL> spool off;SQL> select name from client_master;

NAME -------------------- ivan vandana pramada basu ravi rukmini

6 rows selected.SQL> select name, city from client_master;

NAME CITY -------------------- --------------- ivan bombay vandana madras pramada bombay basu bombay ravi delhi rukmini bombay

6 rows selected.

SQL> select product_no, description from product_master;

PRODUCT_NO DESCRIPTION ---------- ----------------------------- p0001 1.44floppies p03453 monitors p06734 mouse p07865 1.22floppies p07868 keyboards p07885 cddrive p07965 540hdd p07975 1.44drive

Prepared by: Mr.O.Obulesu, Asst.professor [69]

Page 70: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

p08865 1.22drive

9 rows selected.

SQL> select *from client_master where city='bombay';

CLIENT NAME CITY STATE PINCODE BAL_DUE _NO

------- --------- ---------- ------------ -------- --------001 ivan bombay maharastra 400054 15000 003 pramada bombay maharastra 400057 500 004 basu bombay maharastra 400056 0 006 rukmini bombay maharastra 400050 0

SQL> select * from client_master where client_no = '001' or client_no='002';

Program 3: To Illustrate Different SQL Functions

Prepared by: Mr.O.Obulesu, Asst.professor [70]

Page 71: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Character Functions: (1) Lower:

SQL> select lower ('jaya') from dual;

LOWE --------- jaya

SQL> select lower ('JAYASANKAR') from dual;

LOWER ('JAY -------------------- jayasankar

SQL> select lower ('JAyasankar') from dual;

LOWER ('JAY -------------------- jayasankar

SQL> select lower ('JAYASANKAR') as "new name" from dual;

new name ------------- jayasankar

(2)UPPER:

SQL> select upper ('jayasankar') from dual;

UPPER('JAY -------------------- JAYASANKAR

SQL> select upper ('jayasankar') as "new name" from dual;

new name ---------- JAYASANKAR

SQL> select upper ('jayaSANKAR') from dual;

UPPER('JAY ---------- JAYASANKAR

SQL> select name from client_master;

Prepared by: Mr.O.Obulesu, Asst.professor [71]

Page 72: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

NAME -------------------- ivan vandana pramada basu ravi rukmini

6 rows selected.

SQL> select upper (name) from client_master;

UPPER(NAME) -------------------- IVAN VANDANA PRAMADA BASU RAVI RUKMINI

6 rows selected.

(3)INITCAP:SQL> select initcap ('jayasankar') from dual;

INITCAP ('J ----------------- Jayasankar

SQL> select initcap ('JAYASANKAR') from dual;INITCAP('J ----------------- Jayasankar

SQL> select initcap (name) from client_master;

INITCAP(NAME) ------------------------

Ivan Vandana Pramada Basu Ravi Rukmini

6 rows selected.(4)CONCAT:

Prepared by: Mr.O.Obulesu, Asst.professor [72]

Page 73: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL> select concat('jaya','sankar') from dual;

CONCAT('JA ------------------ jayasankar

SQL> select first_name,last_name from emp;

FIRST_NAME LAST_NAME ------------ ---------- haseena begam jaya sankar hema giri khaleel ali hari krishna rathod bhaskar ravi chandra

8 rows selected.SQL> select concat (first_name,last_name) from emp;

CONCAT(FIRST_NAME,LA --------------------------------------

haseenabegam jayasankar hemagiri khaleelali harikrishna rathod bhaskar ravichandra

8 rows selected.

(5)LENGTH:

SQL> select length ('jayasankar') from dual;

LENGTH ('JAYASANKAR') ------------------------------------ 10

SQL> select first_name, length (first_name) from emp;FIRST_NAME LENGTH (FIRST_NAME) ---------- ------------------ haseena 7 jaya 4

Prepared by: Mr.O.Obulesu, Asst.professor [73]

Page 74: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

hema 4 khaleel 7 hari 4 rathod 6 bhaskar 7 ravi 4

8 rows selected.

SQL> select first_name, length (first_name) as "length" from emp;

FIRST_NAME length ---------- ---------- haseena 7 jaya 4 hema 4 khaleel 7 hari 4 rathod 6 bhaskar 7 ravi 4

8 rows selected.

(6)INSTR:SQL> select instr ('jayasankar','s') from dual;

INSTR('JAYASANKAR','S') -------------------------------------- 5

SQL> select instr ('jayasankar','a') from dual;

INSTR('JAYASANKAR','A') -------------------------------------- 2

SQL> select instr ('jayasankar','a') "position" from dual;

position ---------- 2 (7)LPAD:SQL> select lpad ('sankar', 10,'*') from dual;

LPAD('SANK ----------------- ****sankar

Prepared by: Mr.O.Obulesu, Asst.professor [74]

Page 75: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL> select lpad('sankar',10,'-') from dual;

LPAD('SANK ------------------ ----sankar

SQL> select lpad(first_name,20,'#') "padding" from emp;

padding ---------------------------- #############haseena ################jaya ################hema #############khaleel ################hari ##############rathod #############bhaskar ################ravi

8 rows selected.

SQL> select lpad (first_name,20,'*') "left padding" from emp;

left padding ----------------------------- *************haseena ****************jaya ****************hema *************khaleel ****************hari **************rathod *************bhaskar ****************ravi

8 rows selected.(8)RPAD:

SQL> select rpad ('jayasankar',20,'*') from dual;

RPAD ('JAYASANKAR', 20 ----------------------------------- jayasankar**********

SQL> select rpad (first_name,20,'*') "right padding" from emp; right padding ---------------------------- haseena************* jaya****************

Prepared by: Mr.O.Obulesu, Asst.professor [75]

Page 76: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

hema**************** khaleel************* hari**************** rathod************** bhaskar************* ravi****************

8 rows selected.

(9)SUBSTR:

SQL> select substr ('jayasankar',1,4) from dual;

SUBS ------- jaya

SQL> select substr ('welcome',4,4) from dual;

SUBS ------- come

Conversion Functions:

SQL> Select To_Char (17145,'$99,999') From Dual;

TO_CHAR ( ---------------- $17,145

SQL> Select To_Char (Hire_Date,'Dd-Mm-Yy') From EMP;

TO_CHAR( ---------------- 10-10-89 23-11-09 23-11-09 08-08-87 23-11-09 14-02-00

9 rows selected.

SQL> Select To_Char (Hire_Date,'Ddth-Mon-Yyyy' From EMP;

Prepared by: Mr.O.Obulesu, Asst.professor [76]

Page 77: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Select To_Char (Hire_Date,'Ddth-Mon-Yyyy' From EMP *ERROR at line 1:ORA-00907: missing right parenthesis

SQL> Select To_Char (Hire_Date,'Ddth-Mon-Yyyy') From Emp;

TO_CHAR (HIRE_ ------------------------ 10TH-OCT-1989 23RD-NOV-2009 23RD-NOV-2009 08TH-AUG-1987 23RD-NOV-2009 14TH-FEB-2000

9 rows selected.

SQL> Select To_Date ('25/10/99','Dd/Mm/Yy') From Dual;

TO_DATE (' --------------- 25-OCT-99

SQL> EXIT;

Date functions:(1) MONTHS_BETWEEN:

SQL> select months_ between (sysdate,'09-aug-1986') from dual;

MONTHS_BETWEEN(SYSDATE,'09-AUG-1986') ----------------------------------------------------------------- 277.698423

SQL> select trunc (months_between (sysdate,'1-aug-1987')) from dual;

TRUNC (MONTHS_BETWEEN(SYSDATE,'1-AUG-1987')) ----------------------------------------------------------------------------- 265

SQL> select months_between ('19-jan-98','3-jul-89') from dual;

MONTHS_BETWEEN('19-JAN-98','3-JUL-89') -------------------------------------------------------------- 102.516129

SQL> select months_between ('19-jan-98','19-jul-89') from dual;

Prepared by: Mr.O.Obulesu, Asst.professor [77]

Page 78: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

MONTHS_BETWEEN('19-JAN-98','19-JUL-89') --------------------------------------------------------------- 102

(2)ADD_MONTHS:

SQL> select add_months ('16-jan-78',116) from dual;

ADD_MONTH ------------------- 16-SEP-87

SQL> select add_months (sysdate,26) from dual;

ADD_MONTH ------------------- 30-NOV-11

SQL> select hire_date,add_months(hire_date,10) as "date after 10 months" from emp;

HIRE_DATE date after 10 months --------- ------------------------ 13-MAY-20 13-MAR-21 12-JUN-10 12-APR-11 10-JUN-10 10-APR-11 10-JUL-98 10-MAY-99 08-AUG-87 08-JUN-88 09-DEC-12 09-OCT-13 10-MAR-85 10-JAN-86 31-MAR-20 31-JAN-21 14-FEB-00 14-DEC-00 24-MAY-25 24-MAR-26 29-JUL-96 29-MAY-97

11 rows selected.

(3)NEXT_DAY:SQL> select next_day (sysdate,'sunday') from dual;

NEXT_DAY (----------------- 04-OCT-09

SQL> select next_day (sysdate,'monday') from dual;NEXT_DAY ( ----------------- 05-OCT-09

SQL> select next_day('09-aug-87','sunday') from dual;NEXT_DAY ( ----------------- 16-AUG-87

(4)LAST_DAY:

Prepared by: Mr.O.Obulesu, Asst.professor [78]

Page 79: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL> select last_day (sysdate) from dual;

LAST_DAY ( ----------------- 30-SEP-09

SQL> select last_name, hire_date, salary,2 to_char (next_day(add_months(hire_date,6),'monday'),'ddspth-month-year') as "review date"

from EMP;

LAST_NAME HIRE_DATE SALARY review date begam 10-OCT-89 8000 sixteenth-april-nineteen ninety sankar 12-JUN-10 45000 thirteenth-december -twenty ten giri 10-JUN-10 25000 thirteenth-december -twenty ten

3 rows selected.

(5)ROUND:

SQL> select round (sysdate,'month') from dual;

ROUND (SYS ----------------- 01-OCT-09

SQL> select round (sysdate,'year') from dual;

ROUND (SYS ----------------- 01-JAN-10

SQL> select round (add_months ('14-jan-90', 0),'month') from dual;

ROUND (ADD ----------------- 01-JAN-90

(6)TRUNC:

SQL> select trunc (sysdate,'month') from dual;

TRUNC (SYS ----------------- 01-SEP-09

SQL> select trunc (sysdate,'year') from dual;TRUNC (SYS ----------------- 01-JAN-09

SQL> select trunc(add_months('14-jan-90',0),'month') from dual;

Prepared by: Mr.O.Obulesu, Asst.professor [79]

Page 80: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

TRUNC (ADD ------------------ 01-JAN-90

(7)LAST_DAY:

SQL> select last_day ('12-feb-90') from dual;

LAST_DAY ( ---------------- 28-FEB-90

SQL> select trunc(add_months('14-jan-90',0),'month') from dual;

TRUNC (ADD ------------------- 01-JAN-90

NUMBER FUNCTIONS:

(1)ROUND:

SQL> select round (654.618625, 2) from dual;

ROUND (654.618625, 2) ----------------------------- 654.62

SQL> select round(7678.653337,2) from dual;

ROUND (7678.653337,2) ------------------------------- 7678.65

SQL> select round(7678.653337) from dual;

ROUND (7678.653337) ----------------------------- 7679

SQL> select salary from EMP;

SALARY ----------

8000 45000 25000

Prepared by: Mr.O.Obulesu, Asst.professor [80]

Page 81: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

25000 40000 13000 12000 7500 8 rows selected.

SQL> select round (salary) from emp;

ROUND (SALARY) -------------------------- 8000 45000 25000 25000 40000 13000 12000 7500

8 rows selected.

(2)TRUNC:

SQL> select trunc (762.26728) from dual;

TRUNC (762.26728) ------------------------- 762

SQL> select trunc (762.26728,3) from dual;

TRUNC (762.26728, 3) --------------------------- 762.267

(3)MOD:SQL> select mod (salary,12) from emp;

MOD (SALARY, 12) -------------------------- 8 0

8 rows selected.SQL> select mod (23,8) from dual;

MOD (23, 8) ---------- 7 (4)SUM:

Prepared by: Mr.O.Obulesu, Asst.professor [81]

Page 82: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL> select sum (salary) from emp;

SUM (SALARY) -------------------- 175500

(5)AVG:SQL> select avg(salary) from emp;

AVG (SALARY) -------------------- 21937.5

(6)MAX:SQL> select max (salary) from EMP;

MAX (SALARY)--------------------- 45000

(7)MIN:SQL> select min (salary) from emp;

MIN (SALARY)-------------------- 7500

(8)LEAST:SQL> select least (12, 198, 63, 64) from dual;

LEAST (12, 198, 63, 64) ------------------------------ 12

SQL> select least (12, 198,63,64) as least_value from dual;

LEAST_VALUE --------------------- 12

(9)GREATEST:SQL> select greatest (12,198,63,64) from dual;

GREATEST (12, 198, 63, 64) ---------------------------------- 198

SQL> select greatest (12, 198, 63, 64) as greatest_value from dual;

GREATEST_VALUE ---------------------------- 198

(10)EXP:

Prepared by: Mr.O.Obulesu, Asst.professor [82]

Page 83: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL> select exp (7) from dual;

EXP (7) ------------- 1096.63316

SQL> select exp(7) exponent from dual;

EXPONENT ----------------- 1096.63316

(11)SQRT:SQL> select sqrt(34) from dual;

SQRT(34) --------------- 5.83095189

SQL> select sqrt(36) square_root from dual;

SQUARE_ROOT ---------------------- 6

(12)POWER:SQL> select power(6,3) as "power" from dual;

power ---------

216 SQL> select power(5,7) from dual;

POWER (5,7) ----------------- 78125

(13)ABS:SQL> select abs(-78364.73) from dual; ABS (-78364.73)

-------------------- 78364.73

SQL> select abs(-78) abosolute from dual;ABOSOLUTE

------------------ 78 SQL> select abs(625) from dual;

ABS (625) ----------

625

Program 4: To llustrate Constraints in SQL

Prepared by: Mr.O.Obulesu, Asst.professor [83]

Page 84: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

(1)PRIMARY KEY:

SQL>Create table employee (eno number (4) primary key, 2 ename varchar2 (10), 3 salary number (5));

Table created.SQL> desc employee; Name Null? Type ----------------- -------- ---------------------

ENO NOT NULL NUMBER (4) ENAME VARCHAR2 (10) SALARY NUMBER (5)

SQL> create table employee (eno number (4), 2 ename varchar2 (10), 3 salary number (5), 4 primary key (eno));

Table created.SQL> desc employee; Name Null? Type ----------------------------------------- -------- ---------------------------- ENO NOT NULL NUMBER(4) ENAME VARCHAR2(10) SALARY NUMBER(5)

SQL> alter table employee add constraint pk primary key (eno);

Table altered.SQL> desc employee; Name Null? Type ----------------------------------------- -------- ---------------------------- ENO NOT NULL NUMBER(4) ENAME VARCHAR2(10) SALARY NUMBER(5)

(2)FOREIGN KEY:

SQL> create table department (deptno number (5), 2 eno number (4) references employee (eno), 3 deptname varchar2 (10), 4 loc varchar2 (10));

Table created.

SQL> desc department;

Prepared by: Mr.O.Obulesu, Asst.professor [84]

Page 85: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Name Null? Type ----------------------------------------- -------- ---------------------------- DEPTNO NUMBER(5) ENO NUMBER(4) DEPTNAME VARCHAR2(10) LOC VARCHAR2(10)

SQL> create table department(deptno number(5), 2 eno number(4), 3 deptname varchar2(10), 4 loc varchar2(10), 5 foreign key(eno) references employee(eno));

Table created.

SQL> create table department(deptno number(5), 2 eno number(4), 3 deptname varchar2(10), 4 loc varchar2(10));

Table created.

SQL> alter table department add constraint fk 2 foreign key (eno) references employee(eno);

Table altered.

(3)NOT NULL:

SQL> create table sample (eno number (3) not null, 2 ename varchar2 (10), 3 salary number (4, 2));

Table created.

SQL> desc sample; Name Null? Type ----------------------------------------- -------- ---------------------------- ENO NOT NULL NUMBER(3) ENAME VARCHAR2(10) SALARY NUMBER(4,2)

SQL> alter table sample modify (ename varchar2 (10) not null);

Table altered.

SQL> desc sample;

Prepared by: Mr.O.Obulesu, Asst.professor [85]

Page 86: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Name Null? Type ----------------------------------------- -------- ---------------------------- ENO NOT NULL NUMBER(3) ENAME NOT NULL VARCHAR2(10) SALARY NUMBER(4,2)

(4)UNIQUE:

SQL> create table sample2 (eno number (4) unique, 2 ename varchar2 (15) unique, 3 salary number (5));

Table created.

SQL> desc sample2; Name Null? Type ----------------------------------------- -------- ---------------------------- ENO NUMBER (4) ENAME VARCHAR2 (15) SALARY NUMBER (5)

SQL> create table sample3 (eno number (5), ename varchar2 (10), salary number (5), 2 unique (eno, ename));

Table created.

SQL> alter table sample3 drop unique (eno, ename);

Table altered.

SQL> alter table sample3 add constraint uni_c unique (eno, ename);

Table altered.

(5)CHECK:

SQL> create table sample5 (eno number (10), 2 ename varchar2 (10) check (ename like 's%'), 3 salary number (6) check (salary>1000));

Table created.SQL> desc sample5; Name Null? Type ----------------------------------------- -------- ---------------------------- ENO NUMBER (10) ENAME VARCHAR2 (10) SALARY NUMBER (6)SQL> drop table sample5;

Prepared by: Mr.O.Obulesu, Asst.professor [86]

Page 87: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Table dropped.

SQL> create table sample5 (eno number(10), ename varchar2(10), 2 salary number (6), 3 check (ename like 's%'), 4 check (salary>1000));

Table created.

SQL> create table sample5 (eno number (10), ename varchar2 (10), 2 salary number (6), 3 check (ename like 's%'), 4 check (salary>1000));

Table created.

SQL> alter table sample3 add constraint ch_ename check(ename like 's%');

Table altered.

(6)DEFAULT:

SQL> create table sample5(eno number(5), 2 ename varchar2 (10), 3 salary number (6), 4 sex char (1) default 'm');

Table created.

SQL> create table sample5(eno number(5), 2 ename varchar2(10), 3 salary number(6), 4 sex char(1));

Table created.

SQL> alter table sample5 modify sex default 'm';

Table altered.

SQL> alter table sample5 add married char default 'u';

Table altered.

Program 5: To Illustrate Concept of Joins in SQL

Prepared by: Mr.O.Obulesu, Asst.professor [87]

Page 88: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SALES_ORDERDescription:S_order_no primary key varchar2S_order_date dateSell_price numberOrder_status varchar2

SALES ORDER DETAILSDescription:S_order_no references sales order(s_order_no) varchar2Product_no references product_master(product_no) varchar2Qty_ordered numberQty_displayed numberProduct_rate number

SALES_MASTERDescription:

Sales_man_no varchar2 primary key starts with s Sales_name varchar2 not nullAddress varchar2 not nullCity varhchar2State varchar2Pincode numberSalesamount not null

/*JOIN RELATED QUERIES */

Prepared by: Mr.O.Obulesu, Asst.professor [88]

Page 89: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

1.Find out the product which has been sold to ‘ivan bayross’?

Select p.description from product_master p,client_master c Where p.client_no=c.client_no;

2.Find out the product & their quantities that has been delivered ?

Select p.product_no , s.qty_ordered from product_master p,sales_order_details s,Sales_order s1

Where p.product_no=s.product_no and s.s_order_no=s1.s_order_no and s.order_status<> ‘inprocess’;

3.Find the product_no & description of moving products?

Select p.product_no,p.description from product_master p,sales_order_details s,Sales_order s1 where p.product_no=s.product_no and s.s_order_no=s1.s_order_no and

order_status(‘inprocess’,’backordered’);

4.Find out the name of clients who purchased ‘cddrive’?

Select c.name from client_master c,product_master p where c.client_no=p.client_no And p.description=’cddrive’;

5.List the productno, sorderno of the customer having the quantitiy ordered details table with product description as ‘1.44 floppy’?

Select p.product_no,s.qty_ordered from product_master p,sales_order_details sWhere p.product_no=s.product_no and qty_ordered <200 and p.description =’1.44floppy’;

6.Find the products and quantities for the orders placed by vandana and ivan?

Select p.description,s.qty_ordered from product_master p,sales_order_details s,client_master c where p.product_no=s.product_no and p.client_no=c.client_no and c.name in (‘ivan’,’vandana’);

7.Find the products and their quantities for the orders placed by the clientno ‘c00001’&’c00002’?

Select p.description,s.qty_ordered from product_master p, sales_order_details s, client_master c where p.product_no =s.product_no and p.client_no=c.client_no and c.cllient_no in (‘c00001’,’c00002’);

Prepared by: Mr.O.Obulesu, Asst.professor [89]

Page 90: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

8.Find the orderno,clientno and salesman no where the order has been received by more than one salesman?

Select s.order_no,c.client_no,sa.salesman_no from sales_order_details s, sales_order so,sales_master sa,sales_master sa1 ,client_master c,product_master p where c.client_no=p.client_noAnd p.product_no=s.product_no and s.sorder_no=so.sorder_no and so.sm_number=sa.sm_number and sa1.sm_number=so.sm_number and sa.sm_number <>sa1.sm_number;

Prepared by: Mr.O.Obulesu, Asst.professor [90]

Page 91: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Program 6: To illustrate the Views in SQL:

Views:

SQL> create or replace view emp_v1 as 2 select emp_id, first_name, salary from EMP;

View created.

SQL> select *from emp_v1;

EMP_ID FIRST_NAME SALARY --------- ---------- --------- 176 haseena 8000 7341 jaya 45000 1543 hema 25000 5456 khaleel 25300 7841 hari 40000 3043 rathod 14200 4321 bhaskar 12000 1763 ravi 7500

8 rows selected.

SQL> insert into emp_v1 values (4568,'lok', 45571);

1 row created.

SQL> select *from emp_v1;

EMP_ID FIRST_NAME SALARY --------- ---------- --------- 176 haseena 8000 7341 jaya 45000 1543 hema 25000 4568 lok 45571 5456 khaleel 25300 7841 hari 40000 3043 rathod 14200 4321 bhaskar 12000 1763 ravi 7500

9 rows selected.

SQL> delete from emp_v1 where emp_id=1763;

1 row deleted.

Prepared by: Mr.O.Obulesu, Asst.professor [91]

Page 92: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL> select *from emp_v1;

EMP_ID FIRST_NAME SALARY --------- ---------- --------- 176 haseena 8000 7341 jaya 45000 1543 hema 25000 4568 lok 45571 5456 khaleel 25300 7841 hari 40000 3043 rathod 14200 4321 bhaskar 12000 8 rows selected.

SQL> create or replace view emp_v2 as 2 select emp_id "eno", first_name "ename", salary from EMP;

View created.

SQL> insert into emp_v2 values (5452,'sankar', 57545);

1 row created.

SQL> select *from emp_v2;

eno ename SALARY --------- ---------- --------- 176 haseena 8000 7341 jaya 45000 1543 hema 25000 4568 lok 45571 5456 khaleel 25300 7841 hari 40000 5452 sankar 57545 3043 rathod 14200 4321 bhaskar 12000

9 rows selected.

SQL> update emp_v1 set emp_id=4567 where emp_id=176;

1 row updated.

SQL> create or replace view emp_dept as 2 select e.emp_id, e.first_name, d.dept_id, d.loc_id from emp e, dept d 3 where e.dept_id=d.dept_id;

Prepared by: Mr.O.Obulesu, Asst.professor [92]

Page 93: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

View created.

SQL> select *from emp_dept;

EMP_ID FIRST_NAME DEPT_ID LOC_ID --------- ---------- --------- --------- 4567 haseena 10 2001 7341 jaya 10 2001 1543 hema 10 2001 5456 khaleel 30 2002 7841 hari 50 2001 3043 rathod 20 2001 4321 bhaskar 40 2002

7 rows selected.

SQL> insert into emp_dept values (5457,'gjs', 20, 2002);insert into emp_dept values(5457,'gjs',20,2002)*ERROR at line 1:ORA-01776: cannot modify more than one base table through a join view

SQL> delete from emp_dept where emp_id=4321;

1 row deleted.

SQL> select *from emp_dept;

EMP_ID FIRST_NAME DEPT_ID LOC_ID --------- ---------- --------- --------- 4567 haseena 10 2001 7341 jaya 10 2001 1543 hema 10 2001 5456 khaleel 30 2002 7841 hari 50 2001 3043 rathod 20 2001

6 rows selected.

SQL> update emp_dept set emp_id=3142 where emp_id=3043;

1 row updated.SQL> select *from emp_dept; EMP_ID FIRST_NAME DEPT_ID LOC_ID --------- ---------- --------- --------- 4567 haseena 10 2001 7341 jaya 10 2001 1543 hema 10 2001

Prepared by: Mr.O.Obulesu, Asst.professor [93]

Page 94: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

5456 khaleel 30 2002 7841 hari 50 2001 3043 rathod 20 2001

6 rows selected.SQL> create or replace view dept_v1 2 as select first_name from emp 3 where salary in (10000, 15000, 20000);

View created.

SQL> create or replace view dept_v1 as 2 select e.first_name,e.job_name,d.dept_name from emp e,dept d 3 where e.salary in (10000,15000,20000) and e.dept_id=d.dept_id;

View created.

SQL> drop view emp_dept;

View dropped.

SQL> drop view emp_v2;

View dropped.

Prepared by: Mr.O.Obulesu, Asst.professor [94]

Page 95: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Program 7: To illustrate the Usage of Group Functions

SQL>select max (salary), first_name, dept_id from emp 2 group by first_name, dept_id;

MAX(SALARY) FIRST_NAME DEPT_ID ----------- ---------- ---------- 12000 bhaskar 40 40000 hari 50 8000 haseena 10 25000 hema 10 45000 jaya 10 25000 khaleel 30 10000 krishna 10 13000 rathod 20 7500 ravi 20000 sada 10 15000 sankar 40

11 rows selected.

SQL> select max (salary), first_name, dept_id from emp 2 group by dept_id, first_name;

MAX(SALARY) FIRST_NAME DEPT_ID ----------- ---------- ---------- 8000 haseena 10 25000 hema 10 45000 jaya 10 10000 krishna 10 20000 sada 10 13000 rathod 20 25000 khaleel 30 12000 bhaskar 40 15000 sankar 40 40000 hari 50 7500 ravi

11 rows selected.

SQL> create view emp_v2 as 2 select first_name, dept_id, max(salary) “maxs”,min(salary) “mins” from emp 3 group by dept_id, first_name having first_name like '%s%';

View created.

SQL> select *from emp_v2;

Prepared by: Mr.O.Obulesu, Asst.professor [95]

Page 96: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

FIRST_NAME DEPT_ID maxs mins ---------- ---------- ---------- --------- haseena 10 8000 8000 krishna 10 10000 10000 sada 10 20000 20000 bhaskar 40 12000 12000 sankar 40 15000 15000

SQL> select first_name, salary from emp;

FIRST_NAME SALARY ---------- ---------- haseena 8000 jaya 45000 hema 25000 sada 20000 khaleel 25000 hari 40000 krishna 10000 sankar 15000 rathod 13000 bhaskar 12000 ravi 7500

11 rows selected.

SQL> select *from emp where to_char (hire_date,'mm') =to_char (sysdate,'mm');

no rows selected

SQL> select *from emp;

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME SALARY COMM MANAGER_ID DEPT_ID ---------- ---------- ---------- ------------------------------ --------- ---------- ---------- ---------- ---------- ---------- ---------- 176 haseena begam 13-MAY-20 3 prof 8000 1200 1001 10 7341 jaya sankar [email protected] 1 hod 45000 1000 1001 10 1543 hema giri 10-JUN-10 2 prof 25000 5000 1001 10 4341 sada siva 10-JUL-98 3 assprof 20000 4800 1001 10 5456 khaleel ali 08-AUG-87 2 prof 25000 5000 1003 30 7841 hari krishna 09-DEC-12 1 hod 40000 9000 1005 50

Prepared by: Mr.O.Obulesu, Asst.professor [96]

Page 97: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

9876 krishna mohan 10-MAR-85 4 clerk 10000 2000 1001 10 1070 sankar vardhan 31-MAR-20 3 assprof 15000 3500 1004 40 3043 rathod 14-FEB-00 2 prof 13000 1000 1002 20 4321 bhaskar 24-MAY-25 4 clerk 12000 0 1004 40 1763 ravi chandra 29-JUL-96 6 clerk 7500 1250

11 rows selected.

SQL> update emp set hire_date='10-oct-89' where emp_id in (176, 1070, 9876);

3 rows updated.

SQL> select *from emp;

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME SALARY COMM MANAGER_ID DEPT_ID ---------- ---------- ---------- ------------------------------ --------- ---------- ---------- ---------- ---------- ---------- ---------- 176 haseena begam 10-OCT-89 3 prof 8000 1200 1001 10 7341 jaya sankar [email protected] 12-JUN-10 1 hod 45000 1000 1001 10 1543 hema giri 10-JUN-10 2 prof 25000 5000 1001 10 4341 sada siva 10-JUL-98 3 assprof 20000 4800 1001 10 5456 khaleel ali 08-AUG-87 2 prof 25000 5000 1003 30 7841 hari krishna 09-DEC-12 1 hod 40000 9000 1005 50 9876 krishna mohan 10-OCT-89 4 clerk 10000 2000 1001 10 1070 sankar vardhan 10-OCT-89 3 assprof 15000 3500 1004 40 3043 rathod 14-FEB-00 2 prof 13000 1000 1002 20 4321 bhaskar 24-MAY-25 4 clerk 12000 0 1004 40 1763 ravi chandra 29-JUL-96 6 clerk 7500 1250

11 rows selected.

SQL> select *from emp;

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME SALARY COMM MANAGER_ID DEPT_ID

Prepared by: Mr.O.Obulesu, Asst.professor [97]

Page 98: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

---------- ---------- ---------- ------------------------------ --------- ---------- ---------- ---------- ---------- ---------- ---------- 176 haseena begam 10-OCT-89 3 prof 8000 1200 1001 10 7341 jaya sankar [email protected] 12-JUN-10 1 hod 45000 1000 1001 10 1543 hema giri 10-JUN-10 2 prof 25000 5000 1001 10 4341 sada siva 10-JUL-98 3 assprof 20000 4800 1001 10 5456 khaleel ali 08-AUG-87 2 prof 25000 5000 1003 30 7841 hari krishna 09-DEC-12 1 hod 40000 9000 1005 50 9876 krishna mohan 10-OCT-89 4 clerk 10000 2000 1001 10 1070 sankar vardhan 10-OCT-89 3 assprof 15000 3500 1004 40 3043 rathod 14-FEB-00 2 prof 13000 1000 1002 20 4321 bhaskar 24-MAY-25 4 clerk 12000 0 1004 40 1763 ravi chandra 29-JUL-96 6 clerk 7500 1250

11 rows selected.

SQL> select * from EMP where to_char (hire_date,'mm') =to_char (sysdate,'mm');

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME SALARY COMM MANAGER_ID DEPT_ID ---------- ---------- ---------- ------------------------------ --------- ---------- ---------- ---------- ---------- ---------- ---------- 176 haseena begam 10-OCT-89 3 prof 8000 1200 1001 10 9876 krishna mohan 10-OCT-89 4 clerk 10000 2000 1001 10 1070 sankar vardhan 10-OCT-89 3 assprof 15000 3500 1004 40

SQL> select max(salary),job_name from emp group by job_name;

MAX (SALARY) JOB_NAME ----------- ------------- 20000 assprof 12000 clerk 45000 hod 25000 prof

SQL> select months_between(hire_date,sysdate) as new_months, 2 max(salary), job_name from emp group by job_name, months_between(hire_date,sysdate);

Prepared by: Mr.O.Obulesu, Asst.professor [98]

Page 99: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

NEW_MONTHS MAX(SALARY) JOB_NAME ---------- ----------- ---------- -239.92499 15000 assprof -134.92499 20000 assprof -239.92499 10000 clerk -158.31209 7500 clerk 187.526622 12000 clerk 8.13952546 45000 hod 38.0427513 40000 hod -265.98951 25000 prof -239.92499 8000 prof -115.79596 13000 prof 8.07500933 25000 prof

11 rows selected.

SQL> select months_between (sysdate, hire_date), max (salary), job_name from EMP 2 group by job_name, months_between (sysdate, hire_date);

MONTHS_BETWEEN(SYSDATE,HIRE_DATE) MAX(SALARY) JOB_NAME --------------------------------- - ---------- ---------- 134.925147 20000 assprof 239.925147 15000 assprof -187.52647 12000 clerk 158.312244 7500 clerk 239.925147 10000 clerk -38.042595 40000 hod -8.139369 45000 hod -8.0748529 25000 prof 115.796115 13000 prof 239.925147 8000 prof 265.989663 25000 prof

11 rows selected.SQL> select *from emp;

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME SALARY COMM MANAGER_ID DEPT_ID ---------- ---------- ---------- ------------------------------ --------- ---------- ---------- ---------- ---------- ---------- ---------- 176 haseena begam 10-OCT-89 3 prof 8000 1200 1001 10 7341 jaya sankar [email protected] 12-JUN-10 1 hod 45000 1000 1001 10 1543 hema giri 10-JUN-10 2 prof 25000 5000 1001 10 4341 sada siva 10-JUL-98 3 assprof 20000 4800 1001 10 5456 khaleel ali 08-AUG-87 2 prof 25000 5000 1003 30 7841 hari krishna 09-DEC-12 1 hod 40000 9000 1005 50 9876 krishna mohan 10-OCT-89 4 clerk 10000 2000 1001 10

Prepared by: Mr.O.Obulesu, Asst.professor [99]

Page 100: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

1070 sankar vardhan 10-OCT-89 3 assprof 15000 3500 1004 40 3043 rathod 14-FEB-00 2 prof 13000 1000 1002 20 4321 bhaskar 24-MAY-25 4 clerk 12000 0 1004 40 1763 ravi chandra 29-JUL-96 6 clerk 7500 1250

11 rows selected.

SQL> select *from emp_v2;

FIRST_NAME DEPT_ID MAXS MINS ---------- - --------- - --------- ---------- haseena 10 8000 8000 krishna 10 10000 10000 sada 10 20000 20000 bhaskar 40 12000 12000 sankar 40 15000 15000

SQL> select max (to_char (hire_date,'yyyy')) from emp;

MAX( -------- 2025

SQL> select count(to_char(hire_date,'yy')) from emp;

COUNT (TO_CHAR (HIRE_DATE,'YY')) ------------------------------ 11

SQL> select count (max(to_char(hire_date,'yyyy'))) from emp group by to_char(hire_date,'yyyy');

COUNT(MAX(TO_CHAR(HIRE_DATE,'YYYY'))) ------------------------------------------------------------------- 8

SQL> exit;

create table studies(pname varchar2(10), 2 splace varchar2 (15), 3 course varchar2 (15), 4 cost number (5));

Table created.

SQL> desc studies; Name Null? Type

Prepared by: Mr.O.Obulesu, Asst.professor [100]

Page 101: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

----------------------------------------- -------- ---------------------------- PNAME VARCHAR2 (10) SPLACE VARCHAR2 (15) COURSE VARCHAR2 (15) CCOST NUMBER (5)

SQL> create table software (pname varchar2(15), 2 title varchar2(15), 3 dev_in varchar2(10), 4 cost number(5), 5 dcost number(5), 6 sold number(5));

Table created.

SQL> desc software; Name Null? Type ----------------------------------------- -------- ---------------------------- PNAME VARCHAR2 (15) TITLE VARCHAR2 (15) DEV_IN VARCHAR2 (10) SCOST NUMBER (5) DCOST NUMBER (5) SOLD NUMBER (5)

SQL> create table programmer(pname varchar2(15), 2 dob date, 3 doj date, 4 gender char(1), 5 prof1 varchar2(5), 6 prof2 varchar2(5), 7 salary number(5));

Table created.

SQL> desc programmer; Name Null? Type ----------------------------------------- -------- ---------------------------- PNAME VARCHAR2 (15) DOB DATE DOJ DATE GENDER CHAR (1) PROF1 VARCHAR2 (5) PROF2 VARCHAR2 (5) SALARY NUMBER (5)

SQL> spool off;create table studies(pname varchar2(10),

Prepared by: Mr.O.Obulesu, Asst.professor [101]

Page 102: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

2 splace varchar2(15), 3 course varchar2(15), 4 ccost number(5));

Table created.

SQL> desc studies; Name Null? Type ----------------------------------------- -------- ---------------------------- PNAME VARCHAR2 (10) SPLACE VARCHAR2 (15) COURSE VARCHAR2 (15) CCOST NUMBER (5)

SQL> create table software(pname varchar2(15), 2 title varchar2(15), 3 dev_in varchar2(10), 4 scost number(5), 5 dcost number(5), 6 sold number(5));

Table created.

SQL> desc software; Name Null? Type ----------------------------------------- -------- ---------------------------- PNAME VARCHAR2 (15) TITLE VARCHAR2 (15) DEV_IN VARCHAR2 (10) SCOST NUMBER (5) DCOST NUMBER (5) SOLD NUMBER (5)

SQL> create table programmer(pname varchar2(15), 2 dob date, 3 doj date, 4 gender char(1), 5 prof1 varchar2(5), 6 prof2 varchar2(5), 7 salary number(5));

Table created.

SQL> desc programmer; Name Null? Type ----------------------------------------- -------- ---------------------------- PNAME VARCHAR2 (15)

Prepared by: Mr.O.Obulesu, Asst.professor [102]

Page 103: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

DOB DATE DOJ DATE GENDER CHAR (1) PROF1 VARCHAR2 (5) PROF2 VARCHAR2 (5) SALARY NUMBER (5)

SQL> spool off;SQL>select *from tab;

TNAME TABTYPE CLUSTERID ------------------------------ ------- ------- CHALLAN_DETAILS TABLE CHALLAN_HEADER TABLE CLIENT_MASTER TABLE DEPT TABLE EMP TABLE EMP_V1 VIEW EMP_V2 VIEW PRODUCT_MASTER TABLE PROGRAMMER TABLE RESERVES TABLE SAILORS TABLE

TNAME TABTYPE CLUSTERID ------------------------------ ------- ---------- SALES_ORDER TABLE SAMPLE1 TABLE SAMPLE3 TABLE SOFTWARE TABLE STUDIES TABLE

16 rows selected.

SQL> select *from software;

PNAME TITLE DEV_IN SCOST DCOST SOLD --------------- --------------- ---------- ---------- ---------- ---------- hasi bank oracle 15000 10000 50 venu resort_info c++ 12300 1056 1520 navani rail_info .net 5632 1253 145 jagan bus_res c 4563 1245 1356 ravi library_mgmt oracle 47896 15623 4589 harinath sys_admn c 7896 4563 1253 jayasankar satilite_mgmt oracle 78965 45863 12356 sada bus_res pascal 4566 10568 2 hari acc vb 4598 2122 45 kasula bank vb 7454 2483 789

Prepared by: Mr.O.Obulesu, Asst.professor [103]

Page 104: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

11 rows selected.

SQL> select last_name, hire_date, salary,2 to_char (next_day(add_months(hire_date,6),'monday'),'ddspth-month-year') as "review date" from emp;

LAST_NAME HIRE_DATE SALARY review date ---------- --------- ---------- ----------------------------------------- begam 10-OCT-89 8000 sixteenth-april-nineteen ninety sankar 12-JUN-10 45000 thirteenth-december -twenty ten giri 10-JUN-10 25000 thirteenth-december -twenty ten LAST_NAME HIRE_DATE SALARY review date ---------- --------- ---------- ------------------------------------------------ siva 10-JUL-98 20000 eleventh-january -nineteen ninety-nine ali 08-AUG-87 25000 fifteenth-february -nineteen eighty-eight krishna 09-DEC-12 40000 tenth-june -twenty thirteen

LAST_NAME HIRE_DATE SALARY review date ---------- --------- ---------- ----------------------------------------- mohan 10-OCT-89 10000 sixteenth-aprilnineteen ninety vardhan 10-OCT-89 15000 sixteenth-april-nineteen ninety 14-FEB-00 13000 twenty-first-august-two thousand

LAST_NAME HIRE_DATE SALARY review date ---------- --------- ---------- ------------------------------------------------

24-MAY-25 12000 first-december -twenty twenty-five Chandra 29-JUL-96 7500 third-february -nineteen ninety-seven 11 rows selected.

SQL> select last_name,hire_date,salary, 2 to_char(next_day(add_months(hire_date,6),'monday'),'ddspth-month-year') as "review date" from emp;

LAST_NAME HIRE_DATE SALARY review date ---------- --------- ---------- ------------------------------------------------ begam 10-OCT-89 8000 sixteenth-april -nineteen ninety sankar 12-JUN-10 45000 thirteenth-december -twenty ten giri 10-JUN-10 25000 thirteenth-december -twenty ten siva 10-JUL-98 20000 eleventh-january -nineteen ninety-nine ali 08-AUG-87 25000 fifteenth-february -nineteen eighty-eight krishna 09-DEC-12 40000 tenth-june -twenty thirteen mohan 10-OCT-89 10000 sixteenth-april -nineteen ninety vardhan 10-OCT-89 15000 sixteenth-april -nineteen ninety

Prepared by: Mr.O.Obulesu, Asst.professor [104]

Page 105: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

14-FEB-00 13000 twenty-first-august -two thousand 24-MAY-25 12000 first-december -twenty twenty-five chandra 29-JUL-96 7500 third-february -nineteen ninety-seven

11 rows selected.

SQL> select first_name||last_name, hire_date, salary,2 to_char (next_day (add_months (hire_date,6),'monday'),'ddspth-month-year') as "review date" from emp;

FIRST_NAME||LAST_NAME HIRE_DATE SALARY review date -------------------- -------- ------------ ------------ ------------------------------------- haseenabegam 10-OCT-89 8000 sixteenth-april -nineteen ninety jayasankar 12-JUN-10 45000 thirteenth-december -twenty ten hemagiri 10-JUN-10 25000 thirteenth-december -twenty ten sadasiva 10-JUL-98 20000 eleventh-january-nineteenninety-nine khaleelali 08-AUG-87 25000 fifteenth-february -nineteen eighty-eight harikrishna 09-DEC-12 40000 tenth-june -twenty thirteen krishnamohan 10-OCT-89 10000 sixteenth-april -nineteen ninety sankarvardhan 10-OCT-89 15000 sixteenth-april -nineteen ninety rathod 14-FEB-00 13000 twenty-first-august -two thousand bhaskar 24-MAY-25 12000 first-december -twenty twenty-five ravichandra 29-JUL-96 7500 third-february -nineteen ninety-seven

11 rows selected.

SQL> select first_name||last_name, hire_date, to_char(hire_date,'ddspth') as "day" 2 from emp;

FIRST_NAME||LAST_NAME HIRE_DATE day -------------------- --------- -------------- haseenabegam 10-OCT-89 tenth jayasankar 12-JUN-10 twelfth hemagiri 10-JUN-10 tenth sadasiva 10-JUL-98 tenth khaleelali 08-AUG-87 eighth harikrishna 09-DEC-12 ninth krishnamohan 10-OCT-89 tenth sankarvardhan 10-OCT-89 tenth rathod 14-FEB-00 fourteenth bhaskar 24-MAY-25 twenty-fourth ravichandra 29-JUL-96 twenty-ninth

11 rows selected.

SQL> select first_name||last_name, hire_date, to_char (hire_date,'day') as "day" 2 from emp;

Prepared by: Mr.O.Obulesu, Asst.professor [105]

Page 106: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

FIRST_NAME||LAST_NAM HIRE_DATE day -------------------- --------- --------- haseenabegam 10-OCT-89 tuesday jayasankar 12-JUN-10 saturday hemagiri 10-JUN-10 thursday sadasiva 10-JUL-98 friday khaleelali 08-AUG-87 saturday harikrishna 09-DEC-12 sunday krishnamohan 10-OCT-89 tuesday sankarvardhan 10-OCT-89 tuesday rathod 14-FEB-00 monday bhaskar 24-MAY-25 saturday ravichandra 29-JUL-96 monday

11 rows selected.

SQL> select initcap (lower (last_name)), length (last_name) from EMP;

INITCAP(LO LENGTH(LAST_NAME) ---------- ----------------- Begam 5 Sankar 6 Giri 4 Siva 4 Ali 3 Krishna 7 Mohan 5 Vardhan 7 Chandra 7

11 rows selected.

SQL> select initcap (lower (last_name)), length (last_name) from EMP 2 where last_name like 'j%' or last_name like 'a%';

INITCAP (LO LENGTH (LAST_NAME) ---------- ----------------- Ali 3

SQL> select initcap(lower(last_name)),length(last_name) from emp 2 where last_name 3 in ('j%','a%');

no rows selected

SQL> select count(*) from software where scost>=dcost; COUNT (*)

-------------- 9

Prepared by: Mr.O.Obulesu, Asst.professor [106]

Page 107: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL> select sum (sold) from software where scost>=dcost; SUM (SOLD)

----------------- 22103 SQL> select sum (sold),dev_in from software group by dev_in;

SUM (SOLD) DEV_IN ---------- ---------- 145 .net 2611 c 1520 c++ 16995 oracle 4 pascal 834 vb

6 rows selected.

SQL> select sum ((scost-dcost)*sold) from software;

SUM ((SCOST-DCOST)*SOLD) ------------------------------------------ 587703602

SQL> select to_char (sum ((scost-dcost)*sold),'$99,99,99,999') from software;

TO_CHAR (SUM ((S ------------------------- $58,77,03,602

SQL> clear screen;SQL> select emp_id, last_name, salary, salary*15/100 as "increased salary" from emp;

EMP_ID LAST_NAME SALARY increased salary ---------- -------------------- ---------------- ------------------- 176 begam 8000 1200 7341 sankar 45000 6750 1543 giri 25000 3750 4341 siva 20000 3000 5456 ali 25000 3750 7841 krishna 40000 6000 9876 mohan 10000 1500 1070 vardhan 15000 2250 3043 13000 1950 4321 12000 1800 1763 chandra 7500 1125

11 rows selected.SQL> spool off;SQL>select avg (scost) from software where dev_in='oracle';

Prepared by: Mr.O.Obulesu, Asst.professor [107]

Page 108: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

AVG (SCOST) ------------------ 47287

SQL> select pname,trunc(months_between(sysdate,dob)/12) as age, 2 trunc(months_between(sysdate,doj)/12) as experience 3 from programmer;

PNAME AGE EXPERIENCE --------------- ---------- ---------- jagan 23 9 ravi 21 0 harinath 22 2 hasi 21 -11 jayasankar 22 0 navani 22 -13

6 rows selected.

SQL> select pname from studies where course='pgdca';

PNAME --------------- bala babu

SQL> select max(sold) from software;

MAX(SOLD) ----------

12356

SQL> select pname,dob from programmer;

PNAME DOB --------------- --------- jagan 14-JUN-86 ravi 10-DEC-87 harinath 12-JUL-87 hasi 05-NOV-87 jayasankar 09-AUG-87 navani 07-AUG-87

6 rows selected.SQL> select min(ccost) from studies;

MIN(CCOST) ----------

623

Prepared by: Mr.O.Obulesu, Asst.professor [108]

Page 109: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL> select count(*) from studies where course='dca';

COUNT(*) ----------

2 SQL> select sum((scost-dcost)*sold) from software where dev_in='c';

SUM((SCOST-DCOST)*SOLD) -----------------------

8675457

SQL> select *from programmer where pname='jayasankar';

PNAME DOB DOJ G PROF1 PROF2 SALARY --------------- --------- --------- - ---------- ---------- ---------- jayasankar 09-AUG-87 12-JUL-10 m c++ java 65621

SQL> select *from software where pname='jayasankar';

PNAME TITLE DEV_IN SCOST DCOST SOLD --------------- --------------- ---------- ---------- ---------- ---------- jayasankar satilite_mgmt oracle 78965 45863 12356

SQL> select count(*) from studies where splace='pentahour'

COUNT(*) ----------

1 SQL> select *from software where sold>5000;

PNAME TITLE DEV_IN SCOST DCOST SOLD --------------- --------------- ---------- ---------- ---------- ---------- jayasankar satilite_mgmt oracle 78965 45863 12356

SQL> select count(*),title from software group by title,scost,dcost having scost>=dcost;

COUNT(*) TITLE ---------- --------------- 1 bank 1 bus_res 1 library_mgmt 1 rail_info 1 resort_info 1 satilite_mgmt 1 sys_admn

7 rows selected.

Prepared by: Mr.O.Obulesu, Asst.professor [109]

Page 110: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL> select count(*),title from software group by title,scost,dcost having scost>=dcost;

COUNT(*) TITLE ---------- --------------- 1 bank 1 bus_res 1 library_mgmt 1 library_mgmt 1 rail_info 1 rail_info 1 resort_info 1 satilite_mgmt 1 sys_admn

9 rows selected.

SQL> select count(*),title from software group by title ;

COUNT(*) TITLE ---------- --------------- 1 bank 1 bus_res 2 library_mgmt 2 rail_info 1 resort_info 1 satilite_mgmt 1 sys_admn

7 rows selected.

Prepared by: Mr.O.Obulesu, Asst.professor [110]

Page 111: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Program 8;To llustrate the Usage of Sub Queries

1.Find the ProductNo and Description of non moving products?

SQL> select prduct_no,description from product_master 2 where prduct_no in 3 (select prduct_no from sales_order_details where s_order_no in 4 (select s_order_no from sales_order where order_status<>'fulfill'));

PRDUCT_NO DESCRIPTION ---------- -------------------- p0001 1.44floppies p03453 monitors p06734 mouse p07975 1.44drive

2. Find the Customer name, Address, city and pincode for the Client who palced the order No.019001?

SQL> select name,city,pincode from client_master 2 where client_no in 3 (select client_no from product_master 4 where prduct_no in 5 (select prduct_no from sales_order_details where s_order_no='019001'));

NAME CITY PINCODE -------------------- --------------- ---------- vandana madras 12345 pramada bombay 12345

3. Find the client names who placed orders before the month of ‘MAY 1996’?

SQL> select name from client_master 2 where client_no in(select client_no from product_master 3 where prduct_no in(select prduct_no from sales_order_details 4 where s_order_no in(select s_order_no from sales_order 5 where s_order_date<'1-may-96')));

NAME -------------------- ivan vandana pramada rukmini

Prepared by: Mr.O.Obulesu, Asst.professor [111]

Page 112: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

4 Find out if the product 1.44 drive is ordered by only one client and print the client number, name to whom it was sold?

SQL> select c.client_no,c.name from client_master c,product_master p 2 where p.description='1.44drive' and exists(select count(p.client_no) from product_master 3 group by client_no having count(c.client_no)=1);

CLIENT_NO NAME ---------- -------------------- 001 ivan 002 vandana 003 pramada 004 basu 005 ravi 006 rukmini

6 rows selected.

5 Find the names of clients who placed orders worth rs. 10000 or more?

SQL> select name from client_master where client_no in 2 (select client_no from product_master where prduct_no in 3 (select prduct_no from sales_order_details where (qty_ordered*product_rate)>=1000));

NAME -------------------- ivan vandana pramada rukmini

6. Select the orders placed by Ivan?

SQL> select s_order_no from sales_order_details where prduct_no in 2 (select prduct_no from product_master where client_no in 3 (select client_no from client_master where name='ivan'));

S_ORDE ------ 010008

7 Find the names of the persons who are in Haris Department and who also worked on Computers?

SQL> select e.first_name from emp e,dept d

Prepared by: Mr.O.Obulesu, Asst.professor [112]

Page 113: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

2 where e.dept_id=d.dept_id and d.dept_id in((select dept_id from dept where dept_name='computers'), 3 (select d1.dept_id from emp e1,dept d1 where e1.dept_id=d1.dept_id and 4 e1.first_name='hari'));

FIRST_NAME ---------- hari haseena jaya hema

8 Find all the clients and salesman in the city of Bombay?

SQL> select name from client_master where city='bombay' 2 union 3 select sname from sales_master where city='bombay';

NAME -------------------- ivan pramada ravi rukmini

9.Find the salesman name in Bombay who has atleast one client Located at Bombay?

SQL> select s.sname from sales_master s where s.city='bombay' 2 and s.sm_no in(select sm_no from client_master where city='bombay');

SNAME -------------------- jaya ravi

10.Find the produtcnumber, description, quantity on hand, cost price of non moving items in the product_master table?

SQL> select prduct_no,description,qty_on_hand,cost_price from product_master 2 where prduct_no in(select prduct_no from sales_order_details where 3 s_order_no in(select s_order_no from sales_order 4 where order_status='cancelled'));

PRDUCT_NO DESCRIPTION QTY_ON_HAND COST_PRICE---------- -------------------- ----------- ----------p0001 1.44floppies 100 1150

Prepared by: Mr.O.Obulesu, Asst.professor [113]

Page 114: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Program 9

To illustrate Group by clause and TOP-N Analysis

1 .Find the top 3 salaries of employees?

SQL> select salary from (select *from emp order by salary desc) 2 where rownum<=3;

SALARY --------- 45000 40000 25000

2 Display trhe last three minimum salaries?

SQL> select salary from (select *from emp order by salary) 2 where rownum<=3;

SALARY --------- 7500 8000 12000

3. Find the Second maximum salary of Employee?

SQL> select max(salary) from emp where salary<(select max(salary) from emp);

MAX(SALARY) ----------- 40000

4. Find the Third Maximum salary of Employee?

SQL> select max(salary) from emp where salary<(select max(salary) from emp 2 where salary<(select max(salary) from emp));

MAX(SALARY) -----------

Prepared by: Mr.O.Obulesu, Asst.professor [114]

Page 115: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

25000

5.Query to display the list of Service of employee in the form of n years and n months?

SQL> select first_name,trunc(months_between(sysdate,hire_date)/12) "YEARS", 2 trunc(mod(months_between(sysdate,hire_date),12)) months from emp;

FIRST_NAME YEARS MONTHS ---------- --------- --------- haseena 20 1 jaya 0 0 hema 0 0 khaleel 22 3 hari 0 0 rathod 9 9 bhaskar 0 0 ravi 13 3

8 rows selected.

6.Find the Nth Maximum salary of an employee?

SQL> select first_name,salary from emp a 2 where &n=(select count(distinct salary) from emp b where a.salary<b.salary);Enter value for n: 3old 2: where &n=(select count(distinct salary) from emp b where a.salary<b.salary)new 2: where 3=(select count(distinct salary) from emp b where a.salary<b.salary)

FIRST_NAME SALARY ---------- --------- rathod 13000

7.Write a correlated subquery to list out the employees who earn more than the average salary of their department?

SQL> select first_name,salary from emp a 2 where salary>(select avg(salary) from emp b group by dept_id having a.dept_id=b.dept_id);

FIRST_NAME SALARY ---------- --------- jaya 45000

8. Find the lastname and display * against most recently hired employee?

SQL> select first_name,lpad(hire_date,15,'*') from emp 2 where hire_date=(select max(hire_date) from emp);

FIRST_NAME LPAD(HIRE_DATE,

Prepared by: Mr.O.Obulesu, Asst.professor [115]

Page 116: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

---------- --------------- jaya ******23-NOV-09 hema ******23-NOV-09 hari ******23-NOV-09 bhaskar ******23-NOV-09

10 which department has highest annual salary?

SQL> select dept_id,sum(12*(salary+nvl(comm,0))) "Highest ann salary" from emp 2 group by dept_id having sum(12*(salary+nvl(comm,0)))= 3 (select max(sum(12*(salary+nvl(comm,0)))) from emp group by dept_id);

DEPT_ID Highest ann salary --------- ------------------ 10 1022400

11I In which year most people join the company? Display the year and no of employees?

SQL> select to_char(hire_date,'yyyy') "year",count(emp_id) from emp 2 group by to_char(hire_date,'yyyy') having count(emp_id)=(select max(count(emp_id)) 3 from emp group by to_char(hire_date,'yyyy'));

year COUNT(EMP_ID) ---- -------------

2009 4

12.Find the most recently hired employee in each department?

SQL> select *from emp 2 where (dept_id,hire_date) in 3 (select dept_id,max(hire_date) from emp group by dept_id);

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------- SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------- 7341 jaya sankar [email protected] 23-NOV-09 1 hod 45000 1000 1001 10 1543 hema giri 23-NOV-09 2 prof 25000 5000 1001 10 3043 rathod 14-FEB-00 2 prof 13000 1000 1002 20 5456 khaleel ali 08-AUG-87 2 prof 25000 5000 1003 30

Prepared by: Mr.O.Obulesu, Asst.professor [116]

Page 117: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

4321 bhaskar 23-NOV-09 4 clerk 12000 0 1004 40 7841 hari krishna 23-NOV-09 1 hod 40000 9000 1005 50

6 rows selected.

13.List the highest salary paid for each job?

SQL> select job_name,max(salary) from emp group by job_name;

JOB_NAME MAX(SALARY) ---------- ----------- clerk 12000 hod 45000 prof 25000

14.List the details of employee earning more than the highest paid manager?

SQL> select *from emp where salary> 2 (select max(salary) from emp group by job_name having job_name='prof');

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------- SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------- 7341 jaya sankar [email protected] 23-NOV-09 1 hod 45000 1000 1001 10 7841 hari krishna 23-NOV-09 1 hod 40000 9000 1005 50 15.List the employee details whose salary is greater than lowest salary of the employee who belong to departmentnumber 20?

SQL> select *from emp where salary> 2 (select min(salary) from emp group by dept_id having dept_id=20);

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME --------- ---------- ---------- ------------------------------ --------- --------- ----------

Prepared by: Mr.O.Obulesu, Asst.professor [117]

Page 118: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------- 7341 jaya sankar [email protected] 23-NOV-09 1 hod 45000 1000 1001 10 1543 hema giri 23-NOV-09 2 prof 25000 5000 1001 10 5456 khaleel ali 08-AUG-87 2 prof 25000 5000 1003 30 7841 hari krishna 23-NOV-09 1 hod 40000 9000 1005 50

16.List all the employees who don’t have any manager?

SQL> select *from emp where manager_id is null;

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------- SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------- 5456 khaleel ali 08-AUG-87 2 prof 25000 5000 30 7841 hari krishna 23-NOV-09 1 hod 40000 9000 50 1763 ravi chandra 29-JUL-96 6 clerk 7500 1250 17.List all the employees who has atleastone person reporting to them?

SQL> select distinct(a.first_name) from emp a,emp b 2 where a.manager_id=b.manager_id;

FIRST_NAME ---------- bhaskar haseena hema jaya rathod

Prepared by: Mr.O.Obulesu, Asst.professor [118]

Page 119: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Program 10

Implementation of Correlated Subqueries in SQL

Creation:Create table sailors(sid number(2) primary key, sname varchar2(10), rating number(2), age number(4));Create table reserves(sid number(2) references sailors(sid), bid number(3) primary key, day date);Create table boats(bid number(3) references reserves(bid), bname varchar2(10), color varchar2(10));Insert into sailorsValues (&sid,, `&sname`,&rating,&age);

Sid sname rating age ---- -------- -------- -----

22 dustin 7 45.029 brutus 1 33.037 lubber 8 55.532 andy 8 25.558 pusty 10 35.064 horatio 7 35.071 zorba 10 16.074 horatio 9 35.085 art 3 25.595 bob 3 63.5

insert into reserves

values (&sid,&bid,`&data`);

Prepared by: Mr.O.Obulesu, Asst.professor [119]

Page 120: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

sid bid day---- ---- ----22 101 10/10/9822 102 10/10/9822 103 10/8/9822 104 10/7/9831 102 10/10/9831 103 11/06/9831 104 11/12/9864 101 9/05/9864 102 9/08/0874 103 9/08/08

insert into boatsvalues(&bid,`&bname`,`&color`);

bid bname color----- -------- -------101 inter lake blue102 inter lakes red103 clipper green104 marine red

1.Find the names of sailors who reserved boat 103?

Select s.sname From sailors s where s.sid in (select r.sid from reserves r where r.bid=103);

2. Find the names of sailors who reserved red boat?

Select s.sname From sailors s Where s.sid in( Select r.sid From reserves r Where r.bid in(select r.bid From boats b Where b.color=’red’)));

3. Find the names of sailors who have not reserved red boat? Select s.sname

Prepared by: Mr.O.Obulesu, Asst.professor [120]

Page 121: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

From sailors s Where s.sid not in(select r.sid From reserves r Where b.bid in( Select b.bid From baots b Where b.color=’red’));

4. Find the names of sailors who se rating is better than some sailor called ‘Horatio’?

Select s.sname From sailors s Where s.rating >(Select s2.rating From sailors s2 Wheres2.sname=’Horatio’);5. Find the names of sailors who reserved boat number 103?

Select s.sname From sailors s Where Exists(select * from Reserves r where r.bid=103 and r.sid=s.sid);

6.Find sailors whose rating is better than every sailor called ‘Horatio’?

Select s.sid From sailors s Where s.rating>ALL(select s2.rating From sailors s2 Where s2.sname=’Horatio’);7. Find the sailors with highest rating? Select s.sid From sailors s Where s.rating>=ALL(select s2.rating From sailors s2);

8. Find the names of sailors who reserved voth red and green boat?

Select s.sname From sailors S, reserves r, Boat b Where s.sid=r.sid and r.bid=b.bid and b.color=’red’ and s.sid in( select s2.sid from sailors s2,

Prepared by: Mr.O.Obulesu, Asst.professor [121]

Page 122: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

reserves r2, boats b2 where s2.sid=r2.sid and r2.bid=b2.bid and b2.color=’green’);9.Find the names of sailors who have reserved both red and green boat using Intersect operator?

Select s.sname From sailors s Where s.sid in(select r.sid From boat b1, rserves r Where b.bid=b.bid and b.color=’red’) Intersect (Select r2.sid from boats b2, reserves r2 where r2.bid=b2.bid and b2.color=’green’));

10.Find the names of sailors who reserved all boats?

Select s.sname From sailors s Where not exists(select b.bid From boats b Except (select r.bid from resrerves r where r.sid=s.sid));

Prepared by: Mr.O.Obulesu, Asst.professor [122]

Page 123: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PROGRAM 11To Illustrate Indexes, Synonyms,Sequences

SQL> create index client_index on client_master(name);

Index created.

SQL>create index spindex on 2 sales_order_details (s_order_no,prduct_no);

Index created.

SQL> create index ch_index 2 on challan_header(challan_no,s_order_no);

Index created.

SQL> create unique index sales_man_index 2 on sales_master(sname);

Index created.

SQL> select *from sales_master;

SM_NO SNAME ADDRESS CITY STATE PINCODE SALES_AMOUNT ----- -------------------- ---------- ---------- ---------- --------- ------------ s001 jaya 18-224b bombay a.p. 517583 56894 s123 sankar 64-65c hyd a.p. 673482 76547 s002 ravi 61-653c bombay t.n. 673272 57812 s003 hari 623/a bombay m.h. 76257 58374

SQL> select *from sales_master where sname like 'j%';

SM_NO SNAME ADDRESS CITY STATE PINCODE SALES_AMOUNT ----- -------------------- ---------- ---------- ---------- --------- ------------ s001 jaya 18-224b bombay a.p. 517583 56894

SQL> DROP INDEX CH_INDEX;

Index dropped.

Prepared by: Mr.O.Obulesu, Asst.professor [123]

Page 124: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SEQUENCES:~~~~~~~~~~

SQL> create sequence num_seq 2 increment by 1 3 start with 1 4 minvalue 1 5 maxvalue 99 6 cycle;

Sequence created.

SQL> select num_seq.nextval from dual;

NEXTVAL--------- 1

SQL> select num_seq.currval from dual;

CURRVAL--------- 1

SQL> insert into emp(emp_id,first_name) values(num_seq.currval,'sankar');

1 row created.

SQL> select *from emp;

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE--------- ---------- ---------- ------------------------------ --------- JOB_ID JOB_NAME SALARY COMM MANAGER_ID DEPT_ID--------- ---------- --------- --------- ---------- ---------

5456 khaleel ali 08-AUG-87 2 prof 25300 5000 30

7841 hari krishna 23-NOV-09 1 hod 40000 9000 50

5452 sankar

57545

1 sankar

Prepared by: Mr.O.Obulesu, Asst.professor [124]

Page 125: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

4 rows selected.

SQL> alter sequence num_seq 2 increment by 10 3 maxvalue 999 4 nominvalue 5 cycle;

Sequence altered.

SQL> select num_seq.currval from dual;

CURRVAL--------- 1

SQL> select num_seq.nextval from dual;

NEXTVAL--------- 11

SQL> select num_seq.nextval from dual;

NEXTVAL--------- 21

SQL> select num_seq.nextval from dual;

NEXTVAL--------- 31

SQL> create synonym emp_synm for emp;

Synonym created.

SQL> select *from emp_synm;

Prepared by: Mr.O.Obulesu, Asst.professor [125]

Page 126: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------- SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------- 176 haseena begam 10-OCT-89 3 prof 8000 1200 1001 10 7341 jaya sankar [email protected] 23-NOV-09 1 hod 45000 1000 1001 10 1543 hema giri 23-NOV-09 2 prof 25000 5000 1001 10 5456 khaleel ali 08-AUG-87 2 prof 25000 5000 30 7841 hari krishna 23-NOV-09 1 hod 40000 9000 50 3043 rathod 14-FEB-00 2 prof 13000 1000 1002 20 4321 bhaskar 23-NOV-09 4 clerk 12000 0 1004 40 1763 ravi chandra 29-JUL-96 6 clerk 7500 1250

8 rows selected.

SQL> delete from emp_synm where emp_id=1763;

1 row deleted.

SQL> select *from emp_synm;

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------- SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------- 176 haseena begam 10-OCT-89 3 prof 8000 1200 1001 10 7341 jaya sankar [email protected] 23-NOV-09 1 hod 45000 1000 1001 10

Prepared by: Mr.O.Obulesu, Asst.professor [126]

Page 127: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

1543 hema giri 23-NOV-09 2 prof 25000 5000 1001 10 5456 khaleel ali 08-AUG-87 2 prof 25000 5000 30 7841 hari krishna 23-NOV-09 1 hod 40000 9000 50 3043 rathod 14-FEB-00 2 prof 13000 1000 1002 20 4321 bhaskar 23-NOV-09 4 clerk

12000 0 1004 40

7 rows selected.

SQL> select *from emp;

EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_ID JOB_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------- SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------- 176 haseena begam 10-OCT-89 3 prof 8000 1200 1001 10 7341 jaya sankar [email protected] 23-NOV-09 1 hod 45000 1000 1001 10 1543 hema giri 23-NOV-09 2 prof 25000 5000 1001 10 5456 khaleel ali 08-AUG-87 2 prof 25000 5000 30 7841 hari krishna 23-NOV-09 1 hod 40000 9000 50 3043 rathod 14-FEB-00 2 prof 13000 1000 1002 20 4321 bhaskar 23-NOV-09 4 clerk

12000 0 1004 40

Prepared by: Mr.O.Obulesu, Asst.professor [127]

Page 128: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

7 rows selected

Prepared by: Mr.O.Obulesu, Asst.professor [128]

Page 129: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PL/SQL

Overview of PL/SQL PL/SQL is the procedural extension to SQL with design features of programming

languages. Data manipulation and query statements of SQL are included within procedural units

of code.PL/SQL Environment

Prepared by: Mr.O.Obulesu, Asst.professor [129]

PL/SQLBlock

ProceduralStatementExecutor

Oracle ServerSQL statement Executor

PL/SQL Block

Page 130: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Benefits of PL/SQL

Integration

oracle Server

Benefits of PL/SQL

Improved performance

A

Modularize program development

Prepared by: Mr.O.Obulesu, Asst.professor [130]

Other DBMSApplication SQ L

Sql

Application SQLIF.. ThenSQLElseSQLEND IF;

Oracle With PL/SQL

DECLARE

BEGIN

Exception

End;

Page 131: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Benefits of PL/SQL

1.PL/SQL is portable.2. You can declare variables

3. You can program with procedural language control structures. 4.PL/SQL can handle errors.

Benefits of Subprograms Easy maintenance

Improved data security and integrityImproved performance

Improved code clarity

Declaring Variables

)

PL/SQL Block Structure

DECLARE (Optional) Variables, cursors, user-defined exceptionsBEGIN (Mandatory)

Prepared by: Mr.O.Obulesu, Asst.professor [131]

Page 132: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL statements PL/SQL statements

EXCEPTION (Optional) Actions to perform when errors occur END; (Mandatory)

Declare

Begin

Exception

End;

Executing Statements and PL/SQL Blocks

DECLARE v_variable VARCHAR2(5);BEGIN SELECT column_name INTO v_variable FROM table_name;EXCEPTION WHEN exception_name THEN ...END;

Block Types Anonymous Procedure Function[declare] procedure name function nameBegin Begin return datatype

..statements is…statements [exception] Begin[exception] End; ..statementsEnd; Return value

[Exception]End;

Prepared by: Mr.O.Obulesu, Asst.professor [132]

Page 133: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Program Constructs

Use of Variables

Variables can be used for: Temporary storage of data Manipulation of stored values Reusability Ease of maintenance

Handling Variables in PL/SQL Declare and initialize variables in the declaration section. Assign new values to variables in the executable section. Pass values into PL/SQL blocks through parameters. View results through output variables.

Types of Variables PL/SQL variables:

Scalar Composite Reference LOB (large objects)

Non-PL/SQL variables: Bind and host variables

Prepared by: Mr.O.Obulesu, Asst.professor [133]

DECLARE

BEGIN

EXCEPTION

END;

Page 134: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Using iSQL*Plus Variables Within PL/SQL Blocks PL/SQL does not have input or output capability of its own. You can reference substitution variables within a PL/SQL block with a preceding ampersand.

iSQL*Plus host (or “bind”) variables can be used to pass run time values out of the PL/SQL block back to the iSQL*Plus environment

Declaring PL/SQL VariablesSyntax: identifier [CONSTANT] datatype [NOT NULL]

[:= | DEFAULT expr];Examples:DECLARE v_hiredate DATE; v_deptno NUMBER(2) NOT NULL := 10; v_location VARCHAR2(13) := 'Atlanta'; c_comm CONSTANT NUMBER := 1400;

Guidelines for Declaring PL/SQL Variables Follow naming conventions. Initialize variables designated as NOT NULL and CONSTANT. Declare one identifier per line.

Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word

Naming Rules Two variables can have the same name, provided they are in different blocks. The variable name (identifier) should not be the same as the name of table columns used in

the block.DECLARE employee_id NUMBER(6);BEGIN SELECT employee_id

INTO employee_id FROM employees

WHERE last_name = 'Kochhar';END;/Adopt a naming convention for PL/SQL identifiers:for example, v_employee_id

Variable Initialization and Keywords

Prepared by: Mr.O.Obulesu, Asst.professor [134]

Page 135: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Assignment operator (:=) DEFAULT keyword NOT NULL constraintidentifier := expr;

Syntax:v_hiredate := '01-JAN-2001';

Examples:v_ename := 'Maduro';

Scalar Data Types• Hold a single value• Have no internal components• Eg:Text,DateBoolean,Decimal,Paragraph.

Base Scalar Data Type CHAR [(maximum_length)] VARCHAR2 (maximum_length) LONG LONG RAW NUMBER [(precision, scale)] BINARY_INTEGER PLS_INTEGER BOOLEAN

DATE TIMESTAMP TIMESTAMP WITH TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE INTERVAL YEAR TO MONTHINTERVAL DAY TO SECOND

Scalar Variable DeclarationsExamples:

DECLARE v_job VARCHAR2(9); v_count BINARY_INTEGER := 0; v_total_sal NUMBER(9,2) := 0; v_orderdate DATE := SYSDATE + 7; c_tax_rate CONSTANT NUMBER(3,2) := 8.25; v_valid BOOLEAN NOT NULL := TRUE; ...

The %TYPE Attribute

Prepared by: Mr.O.Obulesu, Asst.professor [135]

Page 136: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Declare a variable according to: A database column definition Another previously declared variable

Prefix %TYPE with: The database table and column The previously declared variable name

Declaring Variables with the %TYPE Attribute

Syntax:identifier Table.column_name%TYPE;

Examples:

... v_name employees.last_name%TYPE; v_balance NUMBER(7,2); v_min_balance v_balance%TYPE := 10;

...Declaring Boolean Variables compared by the logical operators AND, OROnly the values TRUE, FALSE, and NULL can

be assigned to a Boolean variable. The variables are , and NOT. The variables always yield TRUE, FALSE, or NULL. Arithmetic, character, and date expressions can be used to return a Boolean value.

Using Bind VariablesTo reference a bind variable in PL/SQL, you must prefix its name with a colon (:).Example:

VARIABLE g_salary NUMBERBEGIN SELECT salary INTO :g_salary FROM employees WHERE employee_id = 178; END;/PRINT g_salary

Referencing Non-PL/SQL VariablesStore the annual salary into a iSQL*Plus host variable.:g_monthly_sal := v_sal / 12;

• Reference non-PL/SQL variables as host variables.• Prefix the references with a colon (:).

DBMS_OUTPUT.PUT_LINE

Prepared by: Mr.O.Obulesu, Asst.professor [136]

Page 137: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

An Oracle-supplied packaged procedure An alternative for displaying data from a PL/SQL block Must be enabled in iSQL*Plus with

SET SERVEROUTPUT ONSET SERVEROUTPUT ONDEFINE p_annual_sal = 60000 DECLARE v_sal NUMBER(9,2) := &p_annual_sal;BEGIN v_sal := v_sal/12; DBMS_OUTPUT.PUT_LINE ('The monthly salary is ' || TO_CHAR(v_sal));END;/Writing Executable Statements Statements can continue over several lines. Lexical units can be classified as:

Delimiters Identifiers Literals Comments

IDENTIFIERS Can contain up to 30 characters Must begin with an alphabetic character Can contain numerals, dollar signs, underscores, and number signs Cannot contain characters such as hyphens, slashes, and spaces Should not have the same name as a database table column name Should not be reserved wordsPL/SQL Block Syntax and Guidelines Literals

Character and date literals must be enclosed in single quotation marks. Numbers can be simple values or scientific notation.

v_name := 'Henderson';

A slash ( / ) runs the PL/SQL block in a script file or in some tools such as iSQL*PLUS. Prefix single-line comments with two dashes (--). Place multiple-line comments between the symbols /* and */. Example: DECLARE... v_sal NUMBER (9,2);BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_sal := :g_monthly_sal * 12;END; -- This is the end of the block

Prepared by: Mr.O.Obulesu, Asst.professor [137]

Page 138: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SQL Functions in PL/SQL

Available in procedural statements: Single-row number Single-row character Data type conversion Date Timestamp GREATEST and LEAST Miscellaneous functions

Not available in procedural statements: DECODE Group functions

SQL Functions in PL/SQL: Examples

Build the mailing list for a company. Convert the employee name to lowercase. v_mailing_address := v_name||CHR(10)|| v_address||CHR(10)||

v_state||CHR(10)||v_zip;v_ename := LOWER(v_ename);

Data Type Conversion

Convert data to comparable data types. Mixed data types can result in an error and affect performance. Conversion functions:

– TO_CHAR– TO_DATE– TO_NUMBER

DECLARE v_date DATE := TO_DATE('12-JAN-2001', 'DD-MON-YYYY'); BEGIN . . .

This statement produces a compilation error if the variable v_date is declared as a DATE data typev_date := 'January 13, 2001'; Nested Blocks and Variable Scope PL/SQL blocks can be nested wherever an executable statement is allowed. A nested block becomes a statement.

Prepared by: Mr.O.Obulesu, Asst.professor [138]

Page 139: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

An exception section can contain nested blocks.The scope of an identifier is that region of a program unit (block, subprogram, or package) from which you can reference the identifier... x BINARY_INTEGER;BEGIN ... DECLARE y NUMBER; BEGIN y:= x; END; ...END;Identifier ScopeAn identifier is visible in the regions where you can reference the identifier without having to qualify it: A block can look up to the enclosing block. A block cannot look down to enclosed blocks.Qualify an Identifier<<outer>>DECLARE birthdate DATE;BEGIN DECLARE birthdate DATE; BEGIN ... outer.birthdate := TO_DATE('03-AUG-1976', 'DD-MON-YYYY'); END;....END;Determining Variable Scope<<outer>> DECLARE v_sal NUMBER(7,2) := 60000; v_comm NUMBER(7,2) := v_sal * 0.20; v_message VARCHAR2(255) := ' eligible for commission';BEGIN DECLARE v_sal NUMBER(7,2) := 50000; v_comm NUMBER(7,2) := 0; v_total_compNUMBER(7,2) := v_sal + v_comm; BEGIN v_message := 'CLERK not'||v_message; outer.v_comm := v_sal * 0.30;

Prepared by: Mr.O.Obulesu, Asst.professor [139]

Page 140: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

END; v_message := 'SALESMAN'||v_message;END;

Operators in PL/SQL

Logical Arithmetic Concatenation Parentheses to control order

of operations Exponential operator (**)Examples: Increment the counter for a loop. Set the value of a Boolean flag. Validate whether an employee number contains a valuev_count := v_count + 1; v_equal := (v_n1 = v_n2);v_valid := (v_empno IS NOT NULL);Programming Guidelines

Make code maintenance easier by: Documenting code with comments Developing a case convention for the code Developing naming conventions for identifiers and other objects Enhancing readability by indentingIndenting Code

BEGIN IF x=0 THEN y:=1; END IF;END;DECLARE v_deptno NUMBER(4); v_location_id NUMBER(4);BEGIN SELECT department_id, location_id INTO v_deptno,

v_location_id FROM departments WHERE department_name = 'Sales'; ...END;

Prepared by: Mr.O.Obulesu, Asst.professor [140]

Page 141: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

/

Interacting with the Oracle ServerSQL Statements in PL/SQL Extract a row of data from the database by using the SELECT command. Make changes to rows in the database by using DML commands. Control a transaction with the COMMIT, ROLLBACK, or SAVEPOINT command. Determine DML outcome with implicit cursor attributes.

SELECT Statements in PL/SQL

Retrieve data from the database with a SELECT statement.Syntax:

SELECT select_list INTO {variable_name[, variable_name]... | record_name}

FROM table [WHERE condition];DECLARE v_deptno NUMBER(4); v_location_id NUMBER(4);BEGIN SELECT department_id, location_id INTO v_deptno, v_location_id FROM departments WHERE department_name = 'Sales'; ...END;/Retrieving Data in PL/SQLSET SERVEROUTPUT ONDECLARE v_sum_sal NUMBER(10,2); v_deptno NUMBER NOT NULL := 60; BEGIN SELECT SUM(salary) -- group function INTO v_sum_sal FROM employees WHERE department_id = v_deptno; DBMS_OUTPUT.PUT_LINE ('The sum salary is ' || TO_CHAR(v_sum_sal));END;/Naming Conventions

Prepared by: Mr.O.Obulesu, Asst.professor [141]

Page 142: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

DECLARE hire_date employees.hire_date%TYPE; sysdate hire_date%TYPE; employee_id employees.employee_id%TYPE := 176; BEGIN SELECT hire_date, sysdate INTO hire_date, sysdate FROM employees WHERE employee_id = employee_id; END;/

Manipulating Data Using PL/SQLMake changes to database tables by using DML commands: INSERT UPDATE DELETE MERGEInserting DataAdd new employee information to the EMPLOYEES table.Example:BEGIN INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, job_id, salary) VALUES (employees_seq.NEXTVAL, 'Ruth', 'Cores', 'RCORES', sysdate, 'AD_ASST', 4000);END;/Updating Data

Increase the salary of all employees who are stock clerks.Example:DECLARE v_sal_increase employees.salary%TYPE := 800; BEGIN UPDATE employees

Prepared by: Mr.O.Obulesu, Asst.professor [142]

Page 143: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SET salary = salary + v_sal_increase WHERE job_id = 'ST_CLERK';END;/Deleting DataDelete rows that belong to department 10 from the EMPLOYEES table.Example:DECLARE v_deptno employees.department_id%TYPE := 10; BEGIN DELETE FROM employees WHERE department_id = v_deptno;END;/Merging RowsDECLAREv_empno employees.employee_id%TYPE := 100;

BEGINMERGE INTO copy_emp c USING employees e ON (e.employee_id = v_empno) WHEN MATCHED THEN UPDATE SET c.first_name = e.first_name, c.last_name = e.last_name, c.email = e.email, . . . WHEN NOT MATCHED THEN INSERT VALUES(e.employee_id, e.first_name, e.last_name, . . .,e.department_id);END;Naming Conventions Use a naming convention to avoid ambiguity in the WHERE clause. Database columns and identifiers should have distinct names. Syntax errors can arise because PL/SQL checks the database first for a column in the

table. The names of local variables and formal parameters take precedence over the names of

database tables.The names of database table columns take precedence over the names of local variablesSQL Cursor A cursor is a private SQL work area. There are two types of cursors:

Implicit cursors Explicit cursors

The Oracle server uses implicit cursors to parse and execute your SQL statements. Explicit cursors are explicitly declared by the programmer.

SQL Cursor Attributes

Prepared by: Mr.O.Obulesu, Asst.professor [143]

Page 144: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Using SQL cursor attributes, you can test the outcome of your SQL statements.

Delete rows that have the specified employee ID from the EMPLOYEES table. Print the number of rows deleted.Example:

VARIABLE rows_deleted VARCHAR2(30)DECLARE v_employee_id employees.employee_id%TYPE := 176;BEGIN DELETE FROM employees WHERE employee_id = v_employee_id; :rows_deleted := (SQL%ROWCOUNT || ' row deleted.');END;/PRINT rows_deleted

Transaction Control Statements Initiate a transaction with the first DML command to follow a COMMIT or

ROLLBACK. Use COMMIT and ROLLBACK SQL statements to terminate a transaction explicitly.Writing Control StructuresControlling PL/SQL Flow of Execution You can change the logical execution of statements using conditional IF statements and

loop control structures. Conditional IF statements:

– IF-THEN-END IF– IF-THEN-ELSE-END IF– IF-THEN-ELSIF-END IF

IF StatementsSyntax:

Prepared by: Mr.O.Obulesu, Asst.professor [144]

SQL%ROWCOUNT Number of rows affected by the most recent SQL statement (an integer

value) SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement affects oneor more rows

SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQL

statement does not affect any rows

SQL%ISOPEN Always evaluates to FALSE because PL/SQL closes implicit cursors immediately after they are executed

Page 145: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Simple IF StatementsIf the last name is Vargas: Set job ID to SA_REP Set department number to 80 . . . IF v_ename = 'Vargas' THEN v_job := 'SA_REP'; v_deptno := 80; END IF; . . .Compound IF StatementsIf the last name is Vargas and the salary is more than 6500:Set department number to 60.. . .IF v_ename = 'Vargas' AND salary > 6500 THEN v_deptno := 60;END IF;. . .

IF-THEN-ELSE Statements

Set a Boolean flag to TRUE if the hire date is greater than five years; otherwise, set the Boolean flag to FALSE.DECLARE v_hire_date DATE := '12-Dec-1990'; v_five_years BOOLEAN;BEGIN. . .

Prepared by: Mr.O.Obulesu, Asst.professor [145]

IF Condition

THEN actions(including further IF statements)

ELSE actions(including further IF statements)

Page 146: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

IF MONTHS_BETWEEN(SYSDATE,v_hire_date)/12 > 5 THEN v_five_years := TRUE;ELSE v_five_years := FALSE;END IF;...

True

IF-THEN-ELSIF StatementsFor a given value, calculate a percentage of that value based on a condition.Example:. . .IF v_start > 100 THEN v_start := 0.2 * v_start;ELSIF v_start >= 50 THEN v_start := 0.5 * v_start;ELSE v_start := 0.1 * v_start;END IF;. . .CASE Expressions A CASE expression selects a result and returns it. To select the result, the CASE expression uses an expression whose value is used to select one of severalCASE selector WHEN expression1 THEN result1

Prepared by: Mr.O.Obulesu, Asst.professor [146]

IF Condition

THEN actions

Elsif Condition

Then Action Else Actions

Page 147: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

WHEN expression2 THEN result2 ... WHEN expressionN THEN resultN [ELSE resultN+1;]END;CASE Expressions: ExampleSET SERVEROUTPUT ONDECLARE v_grade CHAR(1) := UPPER('&p_grade'); v_appraisal VARCHAR2(20);BEGIN v_appraisal := CASE v_grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good' ELSE 'No such grade' END;DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade || ' Appraisal ' || v_appraisal);END;/Handling NullsWhen working with nulls, you can avoid some common mistakes by keeping in mind the following rules: • Simple comparisons involving nulls always yield NULL. • Applying the logical operator NOT to a null yields NULL. • In conditional control statements, if the condition yields NULL, its associated sequence

of statements is not executed. Iterative Control: LOOP Statements

Loops repeat a statement or sequence of statements multiple times. There are three loop types:

Basic loop FOR loop WHILE loop

DECLARE v_country_id locations.country_id%TYPE := 'CA';

v_location_id locations.location_id%TYPE; v_counter NUMBER(2) := 1;

v_city locations.city%TYPE := 'Montreal';BEGIN

SELECT MAX(location_id) INTO v_location_id FROM locations WHERE country_id = v_country_id;

LOOP INSERT INTO locations(location_id, city, country_id)

VALUES((v_location_id + v_counter),v_city, v_country_id); v_counter := v_counter + 1;

Prepared by: Mr.O.Obulesu, Asst.professor [147]

Page 148: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

EXIT WHEN v_counter > 3; END LOOP;END;/

FOR LoopsFOR counter IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . .END LOOP;

Use a FOR loop to shortcut the test for the number of iterations. Do not declare the counter; it is declared implicitly. 'lower_bound .. upper_bound' is required syntax.FOR LoopsInsert three new locations IDs for the country code of CA and the city of Montreal.DECLARE v_country_id locations.country_id%TYPE := 'CA'; v_location_id locations.location_id%TYPE; v_city locations.city%TYPE := 'Montreal';BEGIN SELECT MAX(location_id) INTO v_location_id FROM locations WHERE country_id = v_country_id; FOR i IN 1..3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES((v_location_id + i), v_city, v_country_id ); END LOOP;END; Guidelines Reference the counter within the loop only; it is undefined outside the loop.Do not reference the counter as the target of an assignmentGuidelines While Using Loops Use the basic loop when the statements inside the loop must execute at least once. Use the WHILE loop if the condition has to be evaluated at the start of each iteration. Use a FOR loop if the number of iterations is known.Nested Loops and Labels Nest loops to multiple levels. Use labels to distinguish between blocks and loops. Exit the outer loop with the EXIT statement that references the label.

..BEGIN <<Outer_loop>>

Prepared by: Mr.O.Obulesu, Asst.professor [148]

Page 149: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

LOOP v_counter := v_counter+1; EXIT WHE.N v_counter>10; <<Inner_loop>> LOOP ... EXIT Outer_loop WHEN total_done = 'YES'; -- Leave both loops EXIT WHEN inner_done = 'YES'; -- Leave inner loop only ... END LOOP Inner_loop; ... END LOOP Outer_loop;END;

Working with Composite Data Types

Composite Data Types Are of two types:

PL/SQL RECORDs PL/SQL Collections

– INDEX BY Table– Nested Table– VARRAY

Contain internal components Are reusablePL/SQL Records Must contain one or more components of any scalar, RECORD, or INDEX BY table

data type, called fields Are similar in structure to records in a third generation language (3GL) Are not the same as rows in a database table Treat a collection of fields as a logical unit Are convenient for fetching a row of data from a table for processing

Creating a PL/SQL RecordTYPE type_name IS RECORD (field_declaration[, field_declaration]…);identifier type_name;

field_name {field_type | variable%TYPE | table.column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr] Declare variables to store the name, job, and salary of a new employee.Example:

... TYPE emp_record_type IS RECORD (last_name VARCHAR2(25),

Prepared by: Mr.O.Obulesu, Asst.professor [149]

Page 150: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

job_id VARCHAR2(10), salary NUMBER(8,2)); emp_record emp_record_type;...PL/SQL Record Structure

The %ROWTYPE Attribute

Declare a variable according to a collection of columns in a database table or view. Prefix %ROWTYPE with the database table. Fields in the record take their names and data types from the columns of the table or

view.Advantages of Using %ROWTYPE

The number and data types of the underlying database columns need not be known. The number and data types of the underlying database column may change at run time. The attribute is useful when retrieving a row with the SELECT * statement.

The %ROWTYPE AttributeExamples:Declare a variable to store the information about a department from the DEPARTMENTS table. dept_record departments%ROWTYPE; Declare a variable to store the information about an employee from the EMPLOYEES table.emp_record employees%ROWTYPE;INDEX BY Tables

Are composed of two components: Primary key of data type BINARY_INTEGER

Prepared by: Mr.O.Obulesu, Asst.professor [150]

Field1 (data type) Field2 (data type) Field3 (data type

Field1 (data type) Field2 (data type) Field3 (data type)employee_id number(6) last_name varchar2(25) job_id varchar2(10)

100 King AD_PRES

Page 151: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Column of scalar or record data type Can increase in size dynamically because they are unconstrained

Creating an INDEX BY TableTYPE type_name IS TABLE OF {column_type | variable%TYPE | table.column%TYPE} [NOT NULL] | table.%ROWTYPE [INDEX BY BINARY_INTEGER];identifier type_name

Declare an INDEX BY table to store namesTYPE ename_table_type IS TABLE OF employees.last_name%TYPE INDEX BY BINARY_INTEGER;ename_table ename_table_type;...DECLARE TYPE ename_table_type IS TABLE OF employees.last_name%TYPE INDEX BY BINARY_INTEGER; TYPE hiredate_table_type IS TABLE OF DATE INDEX BY BINARY_INTEGER; ename_table ename_table_type; hiredate_table hiredate_table_type;BEGIN ename_table(1) := 'CAMERON'; hiredate_table(8) := SYSDATE + 7; IF ename_table.EXISTS(1) THEN INSERT INTO ...INDEX BY Table of Records

• Define a TABLE variable with a permitted PL/SQL data type.• Declare a PL/SQL variable to hold department information.

Example:DECLARE TYPE dept_table_type IS TABLE OF departments%ROWTYPE INDEX BY BINARY_INTEGER; dept_table dept_table_type; -- Each element of dept_table is a record SET SERVEROUTPUT ONDECLARE TYPE emp_table_type is table of employees%ROWTYPE INDEX BY BINARY_INTEGER; my_emp_table emp_table_type; v_count NUMBER(3):= 104; BEGIN

Prepared by: Mr.O.Obulesu, Asst.professor [151]

Page 152: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

FOR i IN 100..v_count LOOP

SELECT * INTO my_emp_table(i) FROM employees WHERE employee_id = i;

END LOOP; FOR i IN my_emp_table.FIRST..my_emp_table.LAST LOOP DBMS_OUTPUT.PUT_LINE(my_emp_table(i).last_name); END LOOP;END;/Writing Explicit CursorsAbout CursorsEvery SQL statement executed by the Oracle Server has an individual cursor associated with it:

Implicit cursors: Declared for all DML and PL/SQL SELECT statements Explicit cursors: Declared and named by the programmer

Active set Table

Controlling Explicit Cursors

• Create a named SQL area

• Identify the active set• Load the current row into variables

• Test for existing rows• Return to FETCH if rows are found• Release the active set• Open the cursor• Fetch a row• Close the Cursor

Prepared by: Mr.O.Obulesu, Asst.professor [152]

Cursor

DECLARE OPEN FetchEMPTY?

Close

Page 153: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Eg:• DECLARE• CURSOR emp_cursor IS • SELECT employee_id, last_name • FROM employees;• CURSOR dept_cursor IS• SELECT *• FROM departments• WHERE location_id = 170;• BEGIN• ...

Opening the Cursor

OPEN cursor_name; Open the cursor to execute the query and identify the active set. If the query returns no rows, no exception is raised. Use cursor attributes to test the outcome after a fetch.

Fetching Data from the CursorFETCH cursor_name INTO [variable1, variable2, ...]

| record_name); Retrieve the current row values into variables. Include the same number of variables. Match each variable to correspond to the columns positionally. Test to see whether the cursor contains rows.

Eg: LOOP FETCH emp_cursor INTO v_empno,v_ename; EXIT WHEN ...; ... -- Process the retrieved data … END LOOP;

Closing the CursorCLOSE cursor_name;

Close the cursor after completing the processing of the rows. Reopen the cursor, if required. Do not attempt to fetch data from a cursor after it has been closed.

Explicit Cursor AttributesObtain status information about a cursor.

Prepared by: Mr.O.Obulesu, Asst.professor [153]

Page 154: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

%ISOPEN Boolean Evaluates to TRUE if the cursor is open%NOTFOUND Boolean Evaluates to TRUE if the most recent fetch does not return a row%FOUNDBoolean Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND %ROWCOUNT Number Evaluates to the total number of rows returned so farThe %ISOPEN Attribute

Fetch rows only when the cursor is open. Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor

is open.Example:IF NOT emp_cursor%ISOPEN THEN

OPEN emp_cursor;END IF;LOOP FETCH emp_cursor...

Controlling Multiple Fetches Process several rows from an explicit cursor using a loop. Fetch a row with each iteration. Use explicit cursor attributes to test the success of each fetch.

The %NOTFOUND and %ROWCOUNT Attributes

Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows.Use the %NOTFOUND cursor attribute to determine when to exit the loopDECLARE v_empno employees.employee_id%TYPE; v_ename employees.last_name%TYPE; CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO v_empno, v_ename; EXIT WHEN emp_cursor%ROWCOUNT > 10 OR emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE (TO_CHAR(v_empno) ||' '|| v_ename); END LOOP; CLOSE emp_cursor;END ;

Prepared by: Mr.O.Obulesu, Asst.professor [154]

Page 155: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Creating ProceduresBenefits of Subprograms

Easy maintenance Improved data security and integrity Improved performance

Improved code clarityDeveloping Subprograms by Using i SQL*Plus

Prepared by: Mr.O.Obulesu, Asst.professor [155]

Page 156: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

What Is a Procedure? A procedure is a type of subprogram that performs an action. A procedure can be stored in the database, as a schema object, for repeated execution.

Syntax for Creating ProceduresCREATE [OR REPLACE] PROCEDURE procedure_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] IS|ASPL/SQL Block;

• The REPLACE option indicates that if the procedure exists, it will be dropped and replaced with the new version created by the statement.

• PL/SQL block starts with either BEGIN or the declaration of local variables and ends with either END or END procedure_name. Formal Versus Actual ParametersFormal parameters: variables declared in the parameter list of a subprogram specification

Example:CREATE PROCEDURE raise_sal(p_id NUMBER, p_amount NUMBER)...END raise_sal;Actual parameters: variables or expressions referenced in the parameter list of a subprogram call

Example:raise_sal(v_id, 2000)

Creating Procedures with Parameters

Prepared by: Mr.O.Obulesu, Asst.professor [156]

Calling Environment

t

Procedure

IN parameterOUT parameter IN OUT parameter(DECLARE)BEGINEXCEPTIONEND;

IN OUT IN OUT Default mode Must be specified Must be specified

Value is passed into Returned to Calling Returned to Calling Subprogram Environment Environment

Formal parameter acts as Uninitialized variable Initialized variable a constant

Actual parameter can be a Must be a variable Must be a variable

literal, expression, constant, or initialized variable

Can be assigned a default Cannot be assigned Cannot be assigned a default value a default value

Page 157: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

IN Parameters: Example

CREATE OR REPLACE PROCEDURE raise_salary (p_id IN employees.employee_id%TYPE)ISBEGIN UPDATE employees SET salary = salary * 1.10 WHERE employee_id = p_id;END raise_salary;/

Eg: P_id

OUT Parameters: Example

CREATE OR REPLACE PROCEDURE query_emp (p_id IN employees.employee_id%TYPE, p_name OUT employees.last_name%TYPE, p_salary OUT employees.salary%TYPE, p_comm OUT employees.commission_pct%TYPE)ISBEGIN SELECT last_name, salary, commission_pct INTO p_name, p_salary, p_comm FROM employees WHERE employee_id = p_id;END query_emp;/Viewing OUT Parameters

• Load and run the emp_query.sql script file to create the QUERY_EMP procedure.

Prepared by: Mr.O.Obulesu, Asst.professor [157]

176

Page 158: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

• Declare host variables, execute the QUERY_EMP procedure, and print the value of the global G_NAME variable

Eg:

VARIABLE g_name VARCHAR2(25)VARIABLE g_sal NUMBERVARIABLE g_comm NUMBER

EXECUTE query_emp(171, :g_name, :g_sal, :g_comm)

PRINT g_name

Methods for Passing Parameters

Positional: List actual parameters in the same order as formal parameters. Named: List actual parameters in arbitrary order by associating each with its corresponding

formal parameter. Combination: List some of the actual parameters as positional and some as named.

DEFAULT Option for Parameters

CREATE OR REPLACE PROCEDURE add_dept (p_name IN departments.department_name%TYPE DEFAULT 'unknown', p_loc IN departments.location_id%TYPE DEFAULT 1700)ISBEGIN INSERT INTO departments(department_id, department_name, location_id) VALUES (departments_seq.NEXTVAL, p_name, p_loc);END add_dept;/Examples of Passing ParametersBEGIN add_dept;

Prepared by: Mr.O.Obulesu, Asst.professor [158]

Page 159: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

add_dept ('TRAINING', 2500); add_dept ( p_loc => 2400, p_name =>'EDUCATION'); add_dept ( p_loc => 1200) ;END;/SELECT department_id, department_name, location_idFROM departments;

Declaring SubprogramsCREATE OR REPLACE PROCEDURE leave_emp2 (p_id IN employees.employee_id%TYPE)IS PROCEDURE log_exec IS BEGIN INSERT INTO log_table (user_id, log_date) VALUES (USER, SYSDATE); END log_exec;BEGIN DELETE FROM employees WHERE employee_id = p_id; log_exec;END leave_emp2;/Invoking a Procedure from an Anonymous PL/SQL BlockDECLARE v_id NUMBER := 163;BEGIN raise_salary(v_id); --invoke procedure COMMIT;...END;Invoking a Procedure from Another ProcedureCREATE OR REPLACE PROCEDURE process_empsIS CURSOR emp_cursor IS

Prepared by: Mr.O.Obulesu, Asst.professor [159]

Page 160: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

SELECT employee_id FROM employees;BEGIN FOR emp_rec IN emp_cursor LOOP raise_salary(emp_rec.employee_id); END LOOP; COMMIT;END process_emps;/Invoking a Procedure from Another ProcedureCREATE OR REPLACE PROCEDURE process_empsIS CURSOR emp_cursor IS SELECT employee_id FROM employees;BEGIN FOR emp_rec IN emp_cursor LOOP raise_salary(emp_rec.employee_id); END LOOP; COMMIT;END process_emps;/Removing ProceduresDrop a procedure stored in the database.DROP PROCEDURE procedure_nameDROP PROCEDURE raise_salary;Creating FunctionsOverview of Stored Functions

A function is a named PL/SQL block that returnsa value.

A function can be stored in the database as a schema object for repeated execution. A function is called as part of an expression.

Syntax for Creating FunctionsCREATE [OR REPLACE] FUNCTION function_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)]RETURN datatypeIS|ASPL/SQL Block;

The PL/SQL block must have at least one RETURN statement.

Prepared by: Mr.O.Obulesu, Asst.professor [160]

Page 161: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Syntax for Creating Functions

CREATE [OR REPLACE] FUNCTION function_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)]RETURN datatypeIS|ASPL/SQL Block;

The PL/SQL block must have at least one RETURN statement.

Creating a Stored Function 1.Enter the text of the CREATE FUNCTION statement in an editor and save it as a SQL script file.2. Run the script file to store the source code and compile the function.3. Use SHOW ERRORS to see compilation errors.4. When successfully compiled, invoke the function.Eg:CREATE OR REPLACE FUNCTION get_sal (p_id IN employees.employee_id%TYPE) RETURN NUMBERIS v_salary employees.salary%TYPE :=0;BEGIN SELECT salary INTO v_salary FROM employees WHERE employee_id = p_id; RETURN v_salary;END get_sal;/Executing Functions

Invoke a function as part of a PL/SQL expression. Create a variable to hold the returned value. Execute the function. The variable will be populated by the value returned through a

RETURN statement.Executing Functions: Example VARIABLE g_salary NUMBER

EXECUTE :g_salary := get_sal(117)

PRINT g_salary

Prepared by: Mr.O.Obulesu, Asst.professor [161]

Page 162: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Advantages of User-Defined Functions in SQL Expressions

Extend SQL where activities are too complex, too awkward, or unavailable with SQL Can increase efficiency when used in the WHERE clause to filter data, as opposed to

filtering the data in the application Can manipulate character strings

Invoking Functions in SQL Expressions: ExampleCREATE OR REPLACE FUNCTION tax(p_value IN NUMBER) RETURN NUMBER ISBEGIN RETURN (p_value * 0.08);END tax;/SELECT employee_id, last_name, salary, tax(salary)FROM employeesWHERE department_id = 100;

Locations to Call User-Defined Functions Select list of a SELECT command Condition of the WHERE and HAVING clauses CONNECT BY, START WITH, ORDER BY, and GROUP BY clauses VALUES clause of the INSERT command SET clause of the UPDATE command

Restrictions on Calling Functions from SQL ExpressionsTo be callable from SQL expressions, a user-defined function must:

Be a stored function Accept only IN parameters Accept only valid SQL data types, not PL/SQL specific types, as parameters Return data types that are valid SQL data types, not PL/SQL specific types Functions called from SQL expressions cannot contain DML statements. Functions called from UPDATE/DELETE statements on a table T cannot contain DML on

the same table T.

Prepared by: Mr.O.Obulesu, Asst.professor [162]

Page 163: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Functions called from an UPDATE or a DELETE statement on a table T cannot query the same table.

Functions called from SQL statements cannot contain statements that end the transactions. Calls to subprograms that break the previous restriction are not allowed in the function.

Restrictions on Calling from SQLCREATE OR REPLACE FUNCTION dml_call_sql (p_sal NUMBER) RETURN NUMBER ISBEGIN INSERT INTO employees(employee_id, last_name, email, hire_date, job_id, salary) VALUES(1, 'employee 1', '[email protected]',

SYSDATE, 'SA_MAN', 1000); RETURN (p_sal + 100);END;/Removing Functions

Overview of PackagesPackages:

Group logically related PL/SQL types, items, and subprograms Consist of two parts:

SpecificationBody

Cannot be invoked, parameterized, or nested Allow the Oracle server to read multiple objects into memory at once

Developing a Package Saving the text of the CREATE PACKAGE statement in two different SQL files facilitates

later modifications to the package. A package specification can exist without a package body, but a package body cannot exist

without a package specification.Creating the Package SpecificationSyntax:

CREATE [OR REPLACE] PACKAGE package_nameIS|AS public type and item declarations subprogram specificationsEND package_name;

The REPLACE option drops and recreates the package specification. Variables declared in the package specification are initialized to NULL by default. All the constructs declared in a package specification are visible to users who are granted

privileges on the package.

Prepared by: Mr.O.Obulesu, Asst.professor [163]

DROP FUNCTION function_name

Page 164: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Creating a Package Specification: ExampleCREATE OR REPLACE PACKAGE comm_package IS g_comm NUMBER := 0.10; --initialized to 0.10 PROCEDURE reset_comm (p_comm IN NUMBER);END comm_package;/

• G_COMM is a global variable and is initialized to 0.10.• RESET_COMM is a public procedure that is implemented in the package body.

Creating a Package Body: ExampleCREATE OR REPLACE PACKAGE BODY comm_packageIS FUNCTION validate_comm (p_comm IN NUMBER) RETURN BOOLEAN IS v_max_comm NUMBER; BEGIN SELECT MAX(commission_pct) INTO v_max_comm FROM employees; IF p_comm > v_max_comm THEN RETURN(FALSE); ELSE RETURN(TRUE); END IF; END validate_comm;/PROCEDURE reset_comm (p_comm IN NUMBER) IS BEGIN IF validate_comm(p_comm) THEN g_comm:=p_comm; --reset global variable ELSE RAISE_APPLICATION_ERROR(-20210,'Invalid commission'); END IF; END reset_comm; END comm_package; /Invoking Package Constructs

CREATE OR REPLACE PACKAGE BODY comm_package IS. . .

PROCEDURE reset_comm (p_comm IN NUMBER) IS BEGIN IF validate_comm(p_comm) THEN g_comm := p_comm; ELSE

Prepared by: Mr.O.Obulesu, Asst.professor [164]

Page 165: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

RAISE_APPLICATION_ERROR (-20210, 'Invalid commission'); END IF; END reset_comm;END comm_package;

Example 2: Invoke a package procedure from i SQL*Plus. EXECUTE comm_package.reset_comm(0.15)Example 3: Invoke a package procedure in a differentschema.EXECUTE scott.comm_package.reset_comm(0.15)Example 4: Invoke a package procedure in a remotedatabase.EXECUTE comm_package.reset_comm@ny(0.15)Declaring a Bodiless Package CREATE OR REPLACE PACKAGE global_consts IS mile_2_kilo CONSTANT NUMBER := 1.6093; kilo_2_mile CONSTANT NUMBER := 0.6214; yard_2_meter CONSTANT NUMBER := 0.9144; meter_2_yard CONSTANT NUMBER := 1.0936;END global_consts;/

EXECUTE DBMS_OUTPUT.PUT_LINE('20 miles = '||20*global_consts.mile_2_kilo||' km') ;

Referencing a Public Variable from a Stand-Alone Procedure

CREATE OR REPLACE PROCEDURE meter_to_yard (p_meter IN NUMBER, p_yard OUT NUMBER) ISBEGIN p_yard := p_meter * global_consts.meter_2_yard;END meter_to_yard;/VARIABLE yard NUMBEREXECUTE meter_to_yard (1, :yard)PRINT yard

Removing Packages

Prepared by: Mr.O.Obulesu, Asst.professor [165]

Page 166: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

To remove the package specification and the body, use the following syntax:DROP PACKAGE package_name;To remove the package body, use the following syntax:DROP PACKAGE BODY package_name; Guidelines for Developing Packages

Construct packages for general use. Define the package specification before the body. The package specification should contain only those constructs that you want to be

public. Place items in the declaration part of the package body when you must maintain them

throughouta session or across transactions.

Changes to the package specification requirerecompilation of each referencing subprogram.

The package specification should contain as few constructs as possible.

Advantages of Packages Modularity: Encapsulate related constructs. Easier application design: Code and compile specification and body separately. Hiding information:

Only the declarations in the package specification are visible and accessible to applications.

Private constructs in the package body are hidden and inaccessible. All coding is hidden in the package body.

Added functionality: Persistency of variablesand cursors

Better performance: The entire package is loaded into memory when the package is first referenced. There is only one copy in memory for all users. The dependency hierarchy is simplified.

Overloading: Multiple subprograms of thesame name

Creating Database Triggers

A trigger: Is a PL/SQL block or a PL/SQL procedure associated with a table, view, schema, or the

database Executes implicitly whenever a particular event takes place Can be either:

Application trigger: Fires whenever an event occurs with a particular application Database trigger: Fires whenever a data event (such as DML) or system event (such

as logon or shutdown) occurs on a schema or databaseGuidelines for Designing Triggers

Design triggers to: Perform related actions

Prepared by: Mr.O.Obulesu, Asst.professor [166]

Page 167: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Centralize global operations Do not design triggers:

Where functionality is already built into the Oracle server That duplicate other triggers

Create stored procedures and invoke them in a trigger, if the PL/SQL code is very lengthy. The excessive use of triggers can result in complex interdependencies, which may be difficult

to maintain in large applications.

Creating DML Triggers

A triggering statement contains: Trigger timing

For table: BEFORE, AFTER For view: INSTEAD OF

Triggering event: INSERT, UPDATE, or DELETE Table name: On table, view Trigger type: Row or statement WHEN clause: Restricting condition Trigger body: PL/SQL block

DML Trigger Components 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.

Triggering user event: Which DML statement causes the trigger to execute? You can use any of the following:

INSERT UPDATE DELETE

Trigger type: Should the trigger body execute for each row the statement affects or only once?

Statement: The trigger body executes once for the triggering event. This is the default. A statement trigger fires once, even if no rows are affected at all.

Row: The trigger body executes once for each row affected by the triggering event. A row trigger is not executed if the triggering event affects no rows.

Trigger body: What action should the trigger perform?The trigger body is a PL/SQL block or a call to a procedure.

Prepared by: Mr.O.Obulesu, Asst.professor [167]

Page 168: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Firing Sequence

Use the following firing sequence for a trigger on a table, when many rows are manipulated

UPDATE employees SET salary = salary * 1.1 WHERE department_id = 30;

Syntax for Creating DML Statement TriggersCREATE [OR REPLACE] TRIGGER trigger_name timing event1 [OR event2 OR event3] ON table_nametrigger_bodyNote: Trigger names must be unique with respect to other triggers in the same schema.

Eg: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;/Testing SECURE_EMP

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);

Prepared by: Mr.O.Obulesu, Asst.professor [168]

Page 169: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Using Conditional Predicates in Triggers

CREATE OR REPLACE TRIGGER secure_empBEFORE INSERT OR UPDATE OR DELETE ON employeesBEGIN IF (TO_CHAR (SYSDATE,'DY') IN ('SAT','SUN')) OR (TO_CHAR (SYSDATE, 'HH24') NOT BETWEEN '08' AND '18') THEN IF DELETING THEN RAISE_APPLICATION_ERROR (-20502,'You may delete from EMPLOYEES table only during business hours.'); ELSIF INSERTING THEN RAISE_APPLICATION_ERROR (-20500,'You may insert into

EMPLOYEES table only during business hours.'); ELSIF UPDATING ('SALARY') THEN RAISE_APPLICATION_ERROR (-20503,'You may update

SALARY only during business hours.'); ELSE RAISE_APPLICATION_ERROR (-20504,'You may update

EMPLOYEES table only during normal hours.'); END IF; END IF;END;Creating a DML Row TriggerSyntax:CREATE [OR REPLACE] TRIGGER trigger_name timing event1 [OR event2 OR event3] ON table_name [REFERENCING OLD AS old | NEW AS new]FOR EACH ROW [WHEN (condition)]trigger_bodyEg:CREATE OR REPLACE TRIGGER restrict_salary

Prepared by: Mr.O.Obulesu, Asst.professor [169]

Page 170: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

BEFORE INSERT OR UPDATE OF salary ON employees FOR EACH ROW BEGIN IF NOT (:NEW.job_id IN ('AD_PRES', 'AD_VP')) AND :NEW.salary > 15000 THEN RAISE_APPLICATION_ERROR (-20202,'Employee cannot earn this amount'); END IF;END;/Using OLD and NEW Qualifiers

Eg:CREATE OR REPLACE TRIGGER audit_emp_values AFTER DELETE OR INSERT OR UPDATE ON employees FOR EACH ROWBEGIN INSERT INTO audit_emp_table (user_name, timestamp, id, old_last_name, new_last_name, old_title, new_title, old_salary, new_salary) VALUES (USER, SYSDATE, :OLD.employee_id, :OLD.last_name, :NEW.last_name, :OLD.job_id, :NEW.job_id, :OLD.salary, :NEW.salary );END;/

Using OLD and NEW Qualifiers: Example Using Audit_Emp_Table

INSERT INTO employees (employee_id, last_name, job_id, salary, ...) VALUES (999, 'Temp emp', 'SA_REP', 1000, ...);

UPDATE employees SET salary = 2000, last_name = 'Smith' WHERE employee_id = 999;

SELECT user_name, timestamp, ... FROM audit_emp_table

Prepared by: Mr.O.Obulesu, Asst.professor [170]

Page 171: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Restricting a Row Trigger

CREATE OR REPLACE TRIGGER derive_commission_pct BEFORE INSERT OR UPDATE OF salary ON employees FOR EACH ROW WHEN (NEW.job_id = 'SA_REP')BEGIN IF INSERTING THEN :NEW.commission_pct := 0; ELSIF :OLD.commission_pct IS NULL THEN :NEW.commission_pct := 0; ELSE :NEW.commission_pct := :OLD.commission_pct + 0.05; END IF;END;/

INSTEAD OF TriggersCreating an INSTEAD OF TriggerSyntax:

CREATE [OR REPLACE] TRIGGER trigger_name INSTEAD OF event1 [OR event2 OR event3] ON view_name [REFERENCING OLD AS old | NEW AS new][FOR EACH ROW]trigger_bodyINSERT into EMP_DETAILS that is based on EMPLOYEES and DEPARTMENTS tablesINSERT INTO emp_details(employee_id, ... )VALUES(9001,'ABBOTT',3000,10,'abbott.mail.com','HR_MAN');

Prepared by: Mr.O.Obulesu, Asst.professor [171]

Page 172: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

INSTEAD OF INSERT into EMP_DETAILSDifferentiating Between Database Triggers and Stored ProceduresTriggersDefined with CREATE TRIGGERData dictionary contains source code in USER_TRIGGERSImplicitly invokedCOMMIT, SAVEPOINT, and ROLLBACK are not allowedProceduresDefined with CREATE PROCEDUREData dictionary contains source code in USER_SOURCEExplicitly invokedCOMMIT, SAVEPOINT, and ROLLBACK are allowedManaging TriggersDisable or reenable a database trigger:ALTER TRIGGER trigger_name DISABLE | ENABLEDisable or reenable all triggers for a table:ALTER TABLE table_name DISABLE | ENABLE ALL TRIGGERSRecompile a trigger for a table:ALTER TRIGGER trigger_name COMPILEDROP TRIGGER SyntaxTo remove a trigger from the database, use the DROP TRIGGER syntax:DROP TRIGGER secure_emp;Note: All triggers on a table are dropped when the table is dropped.After Row and After Statement TriggersCREATE OR REPLACE TRIGGER audit_emp_trigAFTER UPDATE or INSERT or DELETE on EMPLOYEESFOR EACH ROWBEGIN IF DELETING THEN var_pack.set_g_del(1); ELSIF INSERTING THEN var_pack.set_g_ins(1); ELSIF UPDATING ('SALARY') THEN var_pack.set_g_up_sal(1); ELSE var_pack.set_g_upd(1); END IF;END audit_emp_trig;/CREATE OR REPLACE TRIGGER audit_emp_tabAFTER UPDATE or INSERT or DELETE on employees

Prepared by: Mr.O.Obulesu, Asst.professor [172]

Page 173: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

BEGIN audit_emp;END audit_emp_tab;/

---------------------------------- END OF PL/SQL--------------------------------------

Prepared by: Mr.O.Obulesu, Asst.professor [173]

Page 174: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PL/SQL

PROGRAM 1PL/SQL Program to accept a number and display whether it is divisable by 5 or not

SET SERVEROUTPUT ON DECLARE N Number:=&a; BEGIN IF(MOD(N,5)=0) Then DBMS_OUTPUT.PUT_LINE(‘THE NUMBER IS DIVISABLE’); ELSE

DBMS_OUTPUT.PUT_LINE(‘THE NUMBER IS DIVISABLE’);

END IF; END; /

OUTPUT

SQL>@Divisable.sql Enter value for a:15 Old 2: n number:=&a; New 2: n number:=15;THE NUMBER IS DIVISABLE*/

Prepared by: Mr.O.Obulesu, Asst.professor [174]

Page 175: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PROGRAM 2

PL/SQL PROGRAM TO ACEPT A CHARACTER FROM THE USER AND DISPLAY WHETHER IT IS ALPHABET OR A SPECIAL CHARACTER OR A NUMBER

SET SERVEROUTPUT ONDECLARE V_A char(3):=’&v_a’; V_temp number; BEGIN V_temp:=ASCII(V_a); IF(V_temp between 65 and 91 or V_temp between 97 and 122) THEN DBMS_OUTPUT.PUT_LINE(‘The Given Input is Alphabet’); Elsif V_temp between 48 and 57 THEN DBMS_OUTPUT.PUT_LINE(‘The given input is a number’); Else DBMS_OUTPUT.PUT_LINE(‘The given input is a special character’); END IF; END;

/* INPUT / OUTPUT */ ************************/* SQL>@char.sqlEnter value for V_a:gOld 2: V_a char(3):=’&V-a’;New 2: V_a char(3):=’g’;The Given Input is Alphabet

SQL>@char.sql

Enter value for V_a:67Old 2: V_a char(3):=’&V-a’;New 2: V_a char(3):=’67’;The Given Input is a number

PL/SQL procedure successfully completed.

SQL>@char.sql

Enter value for V_a:*

Prepared by: Mr.O.Obulesu, Asst.professor [175]

Page 176: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Old 2: V_a char(3):=’&V-a’;New 2: V_a char(3):=’*’;The Given Input is a special character

PL/SQL procedure successfully completed.

PROGRAM 3A PL/SQL PROGRAM TO ACCEPT TWO NUMBERS AND DISPLAY THE BIGGEST ONE

SET SERVEROUTPUT ONDECLARE N1 number:=&a; N2 number:=&b;BEGIN IF N1>N2 THEN DBMS_OUTPUT.PUT_LINE(‘N1 is bigger’); Else DBMS_OUTPUT>PUT_LINE(‘N2 is bigger’); END IF;END;/

/* INPUT / OUTPUT ******************

SQL>@big.sqlEnter value for a:4 Old 2: N1 number:=&a; New 2: N2 number:=4;Enter value for a:6 Old 2: N1 number:=&b; New 2: N2 number:=6;N2 is bigger

PL/SQL procedure successfully completed.

*/

Prepared by: Mr.O.Obulesu, Asst.professor [176]

Page 177: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PROGRAM 4 /* PL/SQL PROGRAM TO PERFORM ARITHMETIC OPERATIONS */SET SERVEROUTPUT ONDECLARE N1 number := &a; N2 number := &b; V_choice number := &c; V_res number;BEGIN DBMS_OUTPUT.PUT_LINE(‘1.ADDITION’); DBMS_OUTPUT.PUT_LINE(‘2.SUBTRACTION’); DBMS_OUTPUT.PUT_LINE(‘3.MULTIPLICATION’); DBMS_OUTPUT.PUT_LINE(‘4.DIVISION’); DBMS_OUTPUT.PUT_LINE(‘ENTER YOUR CHOICE’);

IF (V_choice=1) THEN V_res:=N1+N2; DBMS_OUTPUT.PUT_LINE(‘the addition of two numbers is: || to_char(V-res)); ElSIF (V_choice=2) THEN V_res:=N1-N2; DBMS_OUTPUT.PUT_LINE(‘the subtraction of two numbers is: || to_char(V-res)); ELSIF(V_choice=3) THEN V_res:=N1*N2; DBMS_OUTPUT.PUT_LINE(‘the multiplication of two numbers is:|| to_char(V-res)); ELSIF (V_choice=4) THEN V_res:=N1/N2; DBMS_OUTPUT.PUT_LINE(‘the division of two numbers is: || to_char(V-res)); ELSE DBMS_OUTPUT.PUT_LINE(‘The choice is invalid’); END IF;END;//* INPUT / OUTPUT ******************SQL>@arith.sqlEnter value for a : 4Old 2: N1 number := &a;New 2: N1 number := 4Enter value for a : 5Old 2: N1 number := &b;

Prepared by: Mr.O.Obulesu, Asst.professor [177]

Page 178: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

New 2: N1 number := 5Enter value for a : 3Old 2: N1 number := &c;New 2: N1 number := 31.ADDITION2.SUBTRACTION3.MULTIPLICATION4.DIVISIONENTER YOUR CHOICE

The multiplication of two numbers is:20

PL/SQL procedure successfully completed.

*/

Prepared by: Mr.O.Obulesu, Asst.professor [178]

Page 179: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PROGRAM 5/* A PL/SQL PROGRAM TO UPDATE THE SALARIES OF THE EMPLOYEES BASED ON THE GIVEN DEPT_NO AND BONUS */

SET SERVEROUTPUT ONDECLARE V_deptno number:=&A; V_salary number;BEGIN If(V_deptno=10) Then Update emply set salary=salary+500 Where dept_id=v_deptno; Elsif(v_deptno=16) Then update emply set salary=salary+400 Where dept_id=v_deptno; Elsif(v_deptno=18) Then Update emply set salary=salary+300 Where dept_id=v_deptno; Elsif(v_deptno=21) Then Update emply set salary=salary+200 Where dept_id= v_deptno; End if; Select salary Into v_salary From emply Where dept_id=v_deptno; DBMS_OUTPUT.PUT_LINE(‘The salary of the employee is’||to_char(v_salary));END;/

/*INPUT/OUTPUT*/

SQL>select * from emply;

Sql>@empsal.sqlEnter the value for a:18Old 2: v_deptno number:=&A;New 2:v_deptno number:=18;THE SALARY OF THE EMPLOYEE IS :24300

PL/SQL Procedure Successfully Completed.

Prepared by: Mr.O.Obulesu, Asst.professor [179]

Page 180: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Enter the value for a:21Old 2: v_deptno number:=&A;New 2:v_deptno number:=18;THE SALARY OF THE EMPLOYEE IS :30000

PL/SQL Procedure Successfully Completed.

Enter the value for a:22Old 2: v_deptno number:=&A;New 2:v_deptno number:=18;THE SALARY OF THE EMPLOYEE IS :27000

PL/SQL Procedure Successfully Completed.

Prepared by: Mr.O.Obulesu, Asst.professor [180]

Page 181: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PROGRAM 6

/*PL/SQL PROGRAM TO DISPLAY EMPLOYEE PAY SLIP USING CURSORS*/

Create a table for employee information which consists of Employee number, Employee name, Basic salary, DA, HRA, Gross salary, Deductions and Net Salary. The DA is calculated as follows:

DA CONDITION70% basic salary Basic Salary <300060% of Basic Salary Basic Salary >3000 and

Basic Salary <600050% of Basic Salary Basic Salary >=6000

The HRA is calculated as follows:

HRA CONDITION30% of Basic Salary +DA Basic Salary <=200025% of Basic Salary +DA Basic Salary >=2000 and

Basic Salary <550020% of Basic Salary +DA Basic Salary >=5500

Gross Salary = Basic Salary + DA + HRA

The deductions are calculated as follows:

DEDUCTION CONDITION

30% of Gross Salary Gross Salary >800020% of Gross Salary Gross Salary >=6000 and

Gross Salary <800015% of Gross Salary Gross Salary >=5000 and

Gross Salary <6000NIL Other wise.

CREATING THE TABLE:

Create table employee (enumber number (4) unique,name varchar2(15),vsal number (6),da number (4),hra number (4),gsal number (6),nsal number (7);

INSERTING DATA:

Insert into employee (enumber, name, bsal )

Prepared by: Mr.O.Obulesu, Asst.professor [181]

Page 182: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Values (&eno ,`&name`, `&bsal`);Enter value for eno:101Enter value for name: jaffarEnter value for bsal:3700

1 row created – message displays on the screen.To enter more records type –‘/’Enter 10 more recordsOpen a editor and write PL/SQL code, as folklows:

o E.g.:edit emp.sql:In the editor type the following lines of code:

o DECLARE X EMPLOYEE.ENUMBER%TYPE; B EMPLOYEE.BSAL%TYPE; JDA EMPLOYEE.DA%TYPE; JHRA EMPLWYEE.HRA%TYPE; JGSAL EMPLOYEE.JGSAL%TYPE; JNSAL EMPLOYEE.JNSAL%TYPE; JDED NUMBER (6); CURSOR C1 IS SELECT ENUMBER,BSAL FROM EMPLOYEE;

BEGINOPEN C1;LOOPFETCH C1 INTO X,B;EXIT WHEN C1%NOTFOUND;

IF B>=6000 THENJDA :=B*50/100;

ELSEIF B>3000 THENJDA:=B*60/100;

ELSEJDA:=B*70/100;

END IF;

IF B>=5500 THEN JHRA:=(B*20/100)+JDA;ELSEIF B>2000 THEN

JHRA:=(B*25/100)+JDA;ELSE

JHRA:=(B*30/100)+JDA;END IF;

JGSAL:=B+JDA+JHRA;

IF JGSAL>8000 THENJDED:=JGSAL*30/100;

ELSEIF JGSAL >=6000 THEN

Prepared by: Mr.O.Obulesu, Asst.professor [182]

Page 183: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

JDED:=JGSAL*20/100;ELSEIF JGSAL >=5000 THEN

JDED:=JGSAL*15/100;ELSE

JDED:=0;END IF;

UPDATE EMPLOYEE SET DA=JDA,HRA=JHRA,GSAL=JGSAL,

NSAL=JGSAL-JDED WHERE ENUMBER=X;END LOOP;CLOSE C1;

END; /

save the program and run 1this program at sql prompt.

E.g.@emp;

Prepared by: Mr.O.Obulesu, Asst.professor [183]

Page 184: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PROGRAM 7/*PL/SQL PROGRAM TO DISPLAY STUDENT INFORMATION USING LOOPS AND CURSORS*/

Create a table for 10th class students information which consists of student name, register number date of birth, father name, medium, marks in telugu, hindi, english, social and maths.The minimum marks for all subject is 35 except hindi. The minimum marks for hindi is 20. Clacilate DIVISION for over all marks as follow

DIVISION CONDITIONFIRST total marks >359 and pass in all subjectsSECOND total marks >299 and <360 and pass in all sub.THIRD otherwise and pass in all subjectsFAIL fail atleast in one of subjects

CREATING THE TABLE:

Create table student(Rnumber number (4) unique,Name varchar2(15), dob date,Fname varchar2(15),Medium varchar2(10),Tel number(3),Hin number(3),Eng number(3),Mat number(3),Sci number(3),Soc number(3),Tot number(4),Res varchar2(20));

INSERTING DATA:Insert into student (rnumber,name,dob,fname,medium,tel,hin,eng,mat,sci,soc) values(&rno, ‘&rname`, `&dob`, `&fname` , `&medium`, &tel, &hin, &eng, &mat.&sci, &soc);

Enter value for rno:101Enter value for name:RAJAEnter value for dob:L6/12/79Enter value for medium:EnglishEnter value for tel:80Enter value for hin:69Enter value for eng:59

Prepared by: Mr.O.Obulesu, Asst.professor [184]

Page 185: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Enter value for mat:91Enter value for sci:87Enter value for soc:85

*1 row created –message displays on the screen.*to enter more records type – ‘/’*enter 10 more records *open a editor and write PL/SQL code, as follows:

e.g.: edit result .sql

*IN THE EDITOR TYPE THE FOLLOWING CODE:DECLARE

X STUDENT.RNUMBER%TYPE;T STUDENT.TEL%TYPE;H STUDENT.HIN%TYPE;E STUDENT.ENG%TYPE;M STUDENT.MAT%TYPE;SC STUDENT.SCI%TYPE;SO STUDENT.SOC%SOCTYPE;TOT2 STUDENT.TOT%TYPE;RES2 STUDENT.RES%TYPE;

CURSOR C1 IS SELECT RNUMBER, TEL, HIN, ENG, MAT, SCI, SOC FROM STUDENT;BEGIN

OPEN C1;LOOPFETCH C1 INTO X,T,H,E,M,SC,SO;EDIT WHEN C1% NOTFOUND;TOT2:=T+H+E+M+SC+SO;

IF T<35 OR H<20 OR E<35 OR M<35 OR SC<35 OR SO<35 THENRES2=”FAIL”;ELSEIF TOT2>359 THENRES2:=”FIRST CLASS”;ELSEIF TOT2>299 THENRES2:=”SECOND CLASS:’ELSERES2:=”THIRD CLASS”;END IF;UPDATE STUDENT SET TOT=TOT2, RES=RES2 WHERE

RNUMBER=X;END LOOP;CLOSE C1;

END;/

*SAVE THE PROGRAM AND THIS PROGRAM AT SQL PROMPT.E.G.&RESULT;

Prepared by: Mr.O.Obulesu, Asst.professor [185]

Page 186: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PROGRAM 8/*PL/SQL PROGRAM TO DISPLAY STUDENT RANK INFORMATION IN A TEST*/Create a Table for EAMCET entrance test which consists of Register Number, name, Marks in maths, physics, chemistry. Calculate total marks and Rank.

Creating the table:

Create table eamcet( Rnumber number(4) unique, Name varchar2(15), Mat number(3), Phy number(3), Che number(3), Tot number(5), Rank number(3));Inserting data:

Insert into eamcet(rnumber, name, mat, phy, che) Enter the value for rno:101 Enter the value for name:Subba Reddy Enter the value for maths:45 Enter the value for physics:58 Enter the value for chemistry:66

*1 row created-message displays on the screen.*to enter more records type-‘/’*enter 10 more records*after inserting records, use following command to calculate the total marks

update eamcet set tot=mat+maths+physics+chemistry;

*open a editor and write PL/SQL code, as follows:e.g.: diet eamcet.sql

*In the editor

DECLAREX EAMCET.RNUMBER%TYPE;M EAMCET.MAT%TYPE;P EAMCET.PHY%TYPE;C EAMCET.CHE%TYPE;TOT2 EAMCET.TOT%TYPE;TOT3 EAMCET.TOT%TYPE;RANK2 STUDENT.RANK%TYPE;CURSOR C1 IS SELECT RNUMBER, MAT, PHY, CHE, TOT

FROM STUDENT ORDER BY TOT DESC;BEGIN

OPEN C1;LOOP

Prepared by: Mr.O.Obulesu, Asst.professor [186]

Page 187: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

FETCH C1 INTO X , M , P , C ,TOT;EXIT WHEN C1%NOTFOUND;

IF TOT2=TOT3 THENN:=N-1;

END IF;

UPDATE EAMCET SET RANK=N WHERE RNUMBER=X;TOT3:=TOT2;N:=N+1;END LOOP;CLOSE C1;

END;/

*save the program and run this program at sql prompt.E.G. @eamcet;

Prepared by: Mr.O.Obulesu, Asst.professor [187]

Page 188: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PROGRAM 9/*PL/SQL PROGRAM FOR ELECTRICITY BILL GENERATION FOR A CUSTOMER*/

Create a table for Electricity bill information which consists of consumer number , consumer name ,consumer type, previous meter reading,present meter reading,name of month.There are three types of customers : Industrial , agricultural and domestic .The total charge is calculated as follows:

TYPE CHARGE PER UNIT CONDITIONS Industrial Rs.5-00 Total units > 2000 Industrial Rs.4-00 Total units<=2000 and >1000 Industrial Rs.3-00 Otherwise. Agricultural RS 2-50 Total units>2000

Agricultural Rs 2-00 Total units<=1000 and >500

Agricultural Rs 1-50 OtherWise

Domestic Rs 3-00 Total units >800

Domestic Rs 2-40 Toatal units <=800 and >500 Domestic Rs.1-80 Otherwise

CREATING THE TABLE:

Create table Elect(cno number(4) unique, Name varchar2(15), Ttype char(1), Cmr number(6), Pmr number(6), Mname varchar2(15), Tcharges number(8));INSERTING DATA: Insert into elect(cno, name, type,cmr, pmr,mname) values(&cno, ‘&name’, ‘&type’, &cmr, &pmr, ‘&mname’)

Enter the value for cno: 101Enter the value for name: SunilEnter the value for type:DCEnter the value for cmr: 4321Enter the value for pmr:1234Enter the value for Mname:January

Prepared by: Mr.O.Obulesu, Asst.professor [188]

Page 189: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

*1 row created- Message Displays on the screen.*To enter more records type -/Enter ten more records for different types (Eg:D,A,I).*Open editor and write PL/SQL code as follows:

Eg: Edit Elect.sql* In the editor : DECLARE

X ELECT.CNO%TYPE; P ELECT. PMR%TYPE; C ELECT.CMR%TYPE; TUNITS NUMBER(6); T ELECT.TTYPE%TYPE; CURSOR C1 IS SELECT CNO, PMR, CMR, CNO,TTYPE FROM ELECT; BEGIN OPEN C1; LOOP FETCH C1 INTO X,P,C,T; EXIT WHEN C1%NOTFOUND; TUNITS:=C-P; IF (T=’I’) THEN IF TUNITS>2000 THEN AMT:= TUNITS*5; ELSIF TUNITS >1000 THEN AMT:= TUNITS*4; ELSE AMT:= TUNITS*3; END IF; ELSIF (T=’A’) THEN IF(TUNITS>100) THEN AMT:=TUNITS*2.5; ELSIF(TUNITS>500) THEN AMT:=TUNITS*2; ELSE AMT:=TUNITS*1.5; END IF; ELSE IF(TUNITS)>800) THEN AMT:=TUNITS*3; ELSIF TUNITS>400 THEN AMT:=TUNITS*2.5; ELSE AMT:=TUNITS*1.8; END IF; END IF;

Prepared by: Mr.O.Obulesu, Asst.professor [189]

Page 190: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

UPDATE ELECT SET TCHARGES=AMT WHERE CNO=X; END LOOP; CLOSE C1;END;/* save the program and run this program at sql prompt. Eg: @elect;

PROGRAM 10/* PL/SQL PROCEDURE TO MODIFY THE SALARY OF AN EMPLOYEE*/

CREATE OR REPLACE PROCEDURE raise_salary (P_id IN employees.employee_id%TYPE)ISBEGIN UPDATE employees SET salary = salary * 1.10 WHERE employee_id = p_id;END raise_salary;/

OUPUT:SQL> @EMP.SQL

SQL> Exec Raise_salary (176);

PL/SQL Procedure Succcessfully Completed

Prepared by: Mr.O.Obulesu, Asst.professor [190]

Page 191: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PROGRAM 11/*PL/SQL FUNCTION TO DISPLAY THE SALARY OF EMPLOYEE*/

CREATE OR REPLACE FUNCTION get_sal (p_id IN employees.employee_id%TYPE) RETURN NUMBERIS v_salary employees.salary%TYPE :=0;BEGIN SELECT salary INTO v_salary FROM employees WHERE employee_id = p_id; RETURN v_salary;END get_sal;/

INPUT-OUTPUTSQL>PL/SQLProcedure Succesfully Completed.VARIABLE g_salary NUMBER

EXECUTE :g_salary := get_sal(117)

PRINT g_salary

Prepared by: Mr.O.Obulesu, Asst.professor [191]

Page 192: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PROGRAM 12/*PROGRAM TO LLIUSTRATE PACKAGE CREATION*/

Package Specification CREATE OR REPLACE PACKAGE comm_package IS g_comm NUMBER := 0.10; --initialized to 0.10 PROCEDURE reset_comm (p_comm IN NUMBER);END comm_package;/Package BodyCREATE OR REPLACE PACKAGE BODY comm_packageIS FUNCTION validate_comm (p_comm IN NUMBER) RETURN BOOLEAN IS v_max_comm NUMBER; BEGIN SELECT MAX(commission_pct) INTO v_max_comm FROM employees; IF p_comm > v_max_comm THEN RETURN(FALSE); ELSE RETURN(TRUE); END IF; END validate_comm;PROCEDURE reset_comm (p_comm IN NUMBER) IS BEGIN IF validate_comm(p_comm) THEN g_comm:=p_comm; --reset global variable ELSE RAISE_APPLICATION_ERROR(-20210,'Invalid commission'); END IF; END reset_comm; END comm_package; /Input-output

EXECUTE comm_package.reset_comm(0.15)EXECUTE scott.comm_package.reset_comm(0.15)EXECUTE comm_package.reset_comm@ny(0.15)

Prepared by: Mr.O.Obulesu, Asst.professor [192]

Page 193: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

PROGRAM 13

/*DATABASE TRIGGER TO UPDATE THE SALARY OF EMPLOYEE BEFORE PERFORMING DML OPERATIONS USING QUALIFIERS*/

CREATE OR REPLACE TRIGGER audit_emp_values AFTER DELETE OR INSERT OR UPDATE ON employees FOR EACH ROWBEGIN INSERT INTO audit_emp_table (user_name, timestamp, id, old_last_name, new_last_name, old_title, new_title, old_salary, new_salary) VALUES (USER, SYSDATE, :OLD.employee_id, :OLD.last_name, :NEW.last_name, :OLD.job_id, :NEW.job_id, :OLD.salary, :NEW.salary );END;/INPUT-OUTPUTSQL>Trrigger created.INSERT INTO employees (employee_id, last_name, job_id, salary, ...) VALUES (999, 'Temp emp', 'SA_REP', 1000, ...);

UPDATE employees SET salary = 2000, last_name = 'Smith' WHERE employee_id = 999;

SELECT user_name, timestamp, ... FROM audit_emp_table;

PROGRAM 14

Prepared by: Mr.O.Obulesu, Asst.professor [193]

Page 194: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

CREATION OF CUSTOMER INFORMATION FORM

DESIGN AND IMPLEMENT A FORM WHICH CONSISTS OF CUSTOMER NAME, CUSTOMER NUMBER, CITY AND PHONE NUMBER FOR DATA ENTRY AND DATA MODIFICATION USING APPROPRIATE TRIGGERS AND CONTROLS.

I.In the back-end create table called customer:

Create table customer( Cno number(4) primary key, Cname varchar2(25), Ccity varchar2(30), Cphone number(10);II.Open Forms Designer.

1. From Object Navigator select ‘Blocks’ node and press ‘+’ button from the right side toolbox or select create command from Navigator Menu.

2. In General tabstrip:Give Base Table: customer—and press tab key, Block Name and Canvas names will be automatically created, if required change then,and select Items tabstrip.

In Items tabstrip:press ‘Select Columns’ button to display the list of existing fileds.

In layout tabstrip set the following: Stule:Form Orientation:Vertical Records:1 Spacing:0Options:Integrity Constraints:Set checkbox value checked.If you want to apply all your table constraints to use in the current from and press OK button.

3. From Tools menu select ‘Layout Editor’ command to add any controls or heading to current form.

4. paste four(04) command buttons on the form from the toolbox,change the properties of those buttons as follows

name label accesskeyADD Add Record ASAVE Save Record SDEL Delete Record DQUIT Exit E

5. write the following PL/SQL code to ADD button.

Trigger :When_Button_PressedCode :Create_record;---compile and close

Prepared by: Mr.O.Obulesu, Asst.professor [194]

Page 195: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

6.Write the following PL/SQL code to SAVE button Trigger :When_Button_PressedCode :Commit_form;---compile and close

7.Write the following PL/SQL code to DEL button Trigger :When_Button_PressedCode :Delete_record;---compile and close

8.Write the following PL/SQL code to QUIT button Trigger :When_Button_PressedCode :exit_form;---compile and close

9.From windows menu select ‘Object Navigator’. 10.Write a form-level trigger to maximize the size of windows. Trigger: Pre-form Code: Set_window_property(forms_mdi_window,window_state,maximize); Set_window_property(‘windows’,window_state;maximize); (press compile button then press close button)

11. Save and run the Form.Select RUN command from File menu.

PROGRAM 15

Prepared by: Mr.O.Obulesu, Asst.professor [195]

Page 196: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

Generation of Reports:

Create item table which consists of item number, item name, type and rate.

Create a Report Using the table item such that all rowa are displayed.The style of the report should be Tabular Report.

CREATING THE TABLE:

Create table item( Ino number(4) primary key, Iname varchar2(15), Itype varchar2(10), Rate number(6));INSERTING DATA:Insert into item values(&itemno,’&iname’, ‘&itype’,’&rate’);

Enter value for ino: 101Enter value for iname: penEnter value for itype: bal_redEnter value for rate: 15

CREATING REPORT IN THE REPORT DESIGNER.

1. select report designer option.( a new reports is created automatically by the name ‘UNTITLED’).

2. select ‘data model’ node from the ‘object navigator’, pressright mouse button and select editor option from the list.

3. Select ‘SQL’(query) button from the left side tool bar, andClick on the blank area of the editor.

4. Press right mouse button, select properties option and pressEnter.

5. In the properties set the general property as follows:Under SELECT statement type, select * from item;And press OK button.

6. Select ‘Default Layout’ from tools menu.7. In the ‘Default Layout’ from dialog box, select the tabular

Option(by default the option will be tabular) And press ok button.

8. Give any heading , if required, in the layout.9.From ‘File’ menu select ‘Run’ Command to run the report.10. In ‘Destination type’Keep your selection ‘Screen’.11. Press ‘Run report’.

Prepared by: Mr.O.Obulesu, Asst.professor [196]

Page 197: DBMS Lab Manual

SREE VIDYANIKETHAN ENGINEERING COLLEGEDEPARTMENT OF IT

THANK YOU

`

Prepared by: Mr.O.Obulesu, Asst.professor [197]


Recommended