You are on page 1of 199

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

DATA BASE MANAGEMENT


LAB MANUAL

SYSTEMS

Prepared By
Mr.O.Obulesu,
Asst.Professor

Prepared by: Mr.O.Obulesu, Asst.professor

[1]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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): Create: Used to Define the database Objects like Tables, Views etc. Eg: Create, Alter, Truncate, Drop.

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;

Prepared by: Mr.O.Obulesu, Asst.professor

[4]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Data Manipulation Language (DML) 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_emp SET department_id = (SELECT department_id FROM employees WHERE employee_id = 100)

Prepared by: Mr.O.Obulesu, Asst.professor

[5]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


WHERE job_id = (SELECT job_id FROM employees WHERE employee_id = 200);

(c)DELETE: 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:

Prepared by: Mr.O.Obulesu, Asst.professor

[6]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


DDL statement is issued DCL statement is issued Normal exit from iSQL*Plus, without explicitly issuing COMMIT or ROLLBACK statements 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 employees WHERE 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.

Prepared by: Mr.O.Obulesu, Asst.professor

[7]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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: Write INSERT statement with a subquery. INSERT INTO sales_reps (id, name, salary, commission_pct) SELECT employee_id, last_name, salary, commission_pct FROM employees WHERE 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 columns View Logically represents subsets of data from one or more tables Sequence Numeric value generator Index Improves the performance of some queries Synonym Gives alternative names to objects Naming Rules: Table names and column names: Must begin with a letter Must be 130 characters long Must contain only AZ, az, 09, _, $, 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 Users Tables: Tables belonging to other users are not in the users schema. You should use the owners 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 columns name or pseudocolumns are illegal values. The default data type must match the column data type. Creating Tables CREATE 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

Prepared by: Mr.O.Obulesu, Asst.professor

[8]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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; Data Types in Oracle: VARCHAR2 (size) CHAR (size) NUMBER (P, S) DATE LONG CLOB RAW and LONG RAW BLOB BFILE ROWID of a Variable-length character data Fixed-length character data Variable-length numeric data Date and time values Variable-length character data upto 2 giga bytes Character data up to 4 gigabytes Raw binary data Binary data up to 4 gigabytes Binary data stored in an external file p to 4 gigabytes A 64 base number system representing the unique address

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);

Prepared by: Mr.O.Obulesu, Asst.professor

[9]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


You use the ADD clause to add columns. Eg: (1) ALTER TABLE dept80 ADD (job_id VARCHAR2 (9)); Table altered. You can change a columns data type, size, and default value. Eg: (2) ALTER TABLE dept80 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 statement Eg: 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

Prepared by: Mr.O.Obulesu, Asst.professor

[10]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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. 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

Prepared by: Mr.O.Obulesu, Asst.professor

[11]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


NOT NULL, .) The UNIQUE Constraint UNIQUE constraint

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:

Prepared by: Mr.O.Obulesu, Asst.professor

[12]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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. ON DELETE SET NULL: Converts dependent foreign key values to null The 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.

Prepared by: Mr.O.Obulesu, Asst.professor

[13]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Apply the CASCADE option to disable dependent integrity constraints. Eg: ALTER TABLE employees DISABLE CONSTRAINT emp_emp_id_pk CASCADE;

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 table Selecting All Columns:
Eg: SELECT * FROM r_departments; Selecting Specific Columns:

Prepared by: Mr.O.Obulesu, Asst.professor

[14]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Eg: SELECT department_id, location_id FROM r_departments; Writing SQL Statements: 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 + * / 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; Description Addition Subtraction Multiplication Division

Prepared by: Mr.O.Obulesu, Asst.professor

[15]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

Defining a Null Value: 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 comm FROM r_employees; Result:

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

Prepared by: Mr.O.Obulesu, Asst.professor

[16]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Result:

Concatenation Operator:A concatenation operator 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:

Prepared by: Mr.O.Obulesu, Asst.professor

[17]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

Duplicate Rows: The default display of queries is all rows, including duplicate rows. Eg: SELECT department_id FROM r_employees; Result:

Eliminating Duplicate Rows: Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause. Eg: SELECT DISTINCT department_id FROM r_employees;

SQL Statements Versus iSQL*Plus Commands SQL:

Prepared by: Mr.O.Obulesu, Asst.professor

[18]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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

SQL Statements
SQL*Plus: An environment Oracle proprietary Keywords can be abbreviated Commands do not allow manipulation of values in the database Runs on a browser Centrally loaded, does not have to be implemented on each machine

SQL*Plus commands
Overview of iSQL*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:

Prepared by: Mr.O.Obulesu, Asst.professor

[19]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

Restricting and Sorting Data In SQL: Limiting Rows Using a Selection:

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_id FROM r_employees WHERE department_id = 90;

Prepared by: Mr.O.Obulesu, Asst.professor

[20]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

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 = > < >= <= != or <> Using Comparison Conditions: Eg: SELECT last_name, salary FROM r_employees WHERE salary <= 3000; Description Equal To Greater Than Less than Greater Than or Equal to Less than or equal to Not Equal To

Other Comparison Conditions: Operator BETWEEN .. AND ..... IN(set) LIKE IS NULL Using the BETWEEN Condition:

Description Between two values (inclusive), Match any of a list of values Match a character pattern Is a null value

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

Prepared by: Mr.O.Obulesu, Asst.professor

[21]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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_id FROM r_employees WHERE 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 Eg: SELECT last_name, manager_id FROM r_employees WHERE manager_id IS NULL; Logical Conditions: AND OR NOT Using the AND Operator: AND requires both conditions to be true Eg: SELECT FROM WHERE AND employee_id, last_name, job_id, salary r_employees salary >=10000 job_id LIKE '%MAN%'; Returns TRUE if both component conditions are true Returns TRUE if either any component condition is true Returns TRUE if the following condition is false

Using the OR Operator:

OR requires either any one condition is to be true.


Eg: SELECT employee_id, last_name, job_id, salary

Prepared by: Mr.O.Obulesu, Asst.professor

[22]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


FROM r_employees WHERE salary >= 10000 OR job_id LIKE '%MAN%';

Using the NOT Operator: Eg: SELECT last_name, job_id FROM r_employees WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP'); Result:

Rules of Precedence: Order Evaluated 1 2 3 4 5 6 7 8 Operator Arithmetic operators Concatenation operator Comparison conditions IS [NOT] NULL, LIKE, [NOT] IN [NOT] BETWEEN NOT logical condition AND logical condition OR logical condition

Override rules of precedence by using parentheses. Eg: SELECT last_name, job_id, salary

Prepared by: Mr.O.Obulesu, Asst.professor

[23]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


FROM r_employees WHERE job_id = 'SA_REP' OR job_id = 'AD_PRES' AND salary > 15000; Result:

Use parentheses to force priority. Eg: SELECT FROM WHERE OR AND last_name, job_id, salary r_employees (job_id = 'SA_REP' job_id = 'AD_PRES') salary > 15000;

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_date FROM r_employees ORDER BY hire_date DESC ;

Prepared by: Mr.O.Obulesu, Asst.professor

[24]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Result:

Sorting by Column Alias: Eg: SELECT employee_id, last_name, salary*12 as annsal FROM r_employees ORDER BY annsal; Result:

Sorting by Multiple Columns:

The order of ORDER BY list is the order of sort


Eg: SELECT FROM ORDER BY Result: last_name, department_id, salary r_employees department_id, salary DESC;

Prepared by: Mr.O.Obulesu, Asst.professor

[25]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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

SQL Functions:

Input arg 1 arg 2

Function Function performs action

Output

Result value

arg n

Input arg 1 arg 2

Function Function performs action

Output

Result value

arg n

Two Types of SQL Functions:

Prepared by: Mr.O.Obulesu, Asst.professor

[26]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

Functions

Single-row functions

Multiple-row functions

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,...)]

Character

General

Single-row functions

Number

Conversion

Date

Character Functions

Prepared by: Mr.O.Obulesu, Asst.professor

[27]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


C rc r h at a e f ntos uc n i

Ce a s

-m i u to a pl i n n a f ntos uc n i
LWR OE UPR PE IICP NTA

C rc r h at a e

-m i u to a pl i n n a f ntos uc n i
CNA OCT SBT USR LNT EGH ISR NT LA |RA PD PD TI RM RPAE ELC

LOWER UPPER INITCAP

CONCAT SUBSTR LENGTH INSTR LPAD TRIM REPLACE

Case Manipulation Functions: These functions convert case for character strings. Function LOWER('SQL Course') UPPER('SQL Course') INITCAP('SQL Course') Using Case Manipulation Functions: Display the employee number, name, and department number for employee Higgins: Eg: SELECT employee_id, last_name, department_id FROM employees WHERE last_name = 'higgins'; No rows selected Eg: SELECT employee_id, last_name, department_id FROM employees WHERE 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,'*') Result sql course SQL COURSE Sql Course

Prepared by: Mr.O.Obulesu, Asst.professor

[28]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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'; RPAD(salary, 10, '*') TRIM('H' FROM 'HelloWorld')

Number Functions:

ROUND: Rounds value to specified decimal ROUND (45.926, 2) output: 45.93 TRUNC: Truncates value to specified decimal TRUNC (45.926, 2) output: 45.92 MOD: Returns remainder of division MOD (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:

Prepared by: Mr.O.Obulesu, Asst.professor

[29]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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 employees WHERE 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 employees WHERE last_name like 'G%';

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 employees WHERE department_id = 90; Result:

Prepared by: Mr.O.Obulesu, Asst.professor

[30]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Date Functions: MONTHS_BETWEEN ADD_MONTHS NEXT_DAY LAST_DAY ROUND TRUNC Using Date Functions: Number of months between two dates Add calendar months to date Next day of the date specified Last day of the month Round date Truncate date

MONTHS_BETWEEN ('01-SEP-95','11-JAN-94') ADD_MONTHS ('11-JAN-94',6) ; NEXT_DAY ('01-SEP-95','FRIDAY') ; LAST_DAY('01-FEB-95');

Output: 19.6774194 Output: '11-JUL-94' Output: '08-SEP-95' Output: '28-FEB-95'

Conversion Functions: Conversion Functions are of two types. 1. Implicit Conversion 2. Explicit Conversion. Implicit Data Type Conversion: For assignments, the Oracle server can automatically Convert 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:

Prepared by: Mr.O.Obulesu, Asst.professor

[31]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

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 0 $ L

Eg: SELECT TO_CHAR(salary, '$99,999.00') SALARY FROM employees WHERE 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:

Prepared by: Mr.O.Obulesu, Asst.professor

[32]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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. 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);

Prepared by: Mr.O.Obulesu, Asst.professor

[33]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

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: 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;

Prepared by: Mr.O.Obulesu, Asst.professor

[34]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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;

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:

Prepared by: Mr.O.Obulesu, Asst.professor

[35]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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

[36]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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.column FROM 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. What is an Equijoin?

Prepared by: Mr.O.Obulesu, Asst.professor

[37]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

Retrieving Records with Equijoins: Eg: SELECT employees.employee_id, employees.last_name, employees.department_id, departments.department_id,

Prepared by: Mr.O.Obulesu, Asst.professor

[38]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


departments.location_id FROM employees, departments WHERE 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_level FROM employees e, job_grades j WHERE e.salary BETWEEN j.lowest_sal AND j.highest_sal; Outer Joins: You use an outer join to also see rows that do not meet the join condition.

Prepared by: Mr.O.Obulesu, Asst.professor

[39]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


The Outer join operator is the plus sign (+). SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column (+) = table2.column;

Eg: (1)

SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column = table2.column (+); Using Outer Joins: Eg: SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id(+) = d.department_id ; Self Joins:

Eg: (2)

Joining a Table to Itself: Eg: SELECT worker.last_name || ' works for ' || manager.last_name FROM employees worker, employees manager WHERE worker.manager_id = manager.employee_id; Joining Tables Using SQL: 1999 Syntax

Prepared by: Mr.O.Obulesu, Asst.professor

[40]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Eg: SELECT table1.column, table2.column FROM 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_name FROM employees CROSS 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 departments NATURAL JOIN locations ;

Prepared by: Mr.O.Obulesu, Asst.professor

[41]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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_id FROM employees e JOIN departments d USING (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. The join condition is separated from other search conditions.

Prepared by: Mr.O.Obulesu, Asst.professor

[42]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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 d ON (e.department_id = d.department_id); Creating Three-Way Joins with the ON Clause: Eg: SELECT employee_id, city, department_name FROM employees e JOIN departments d ON d.department_id = e.department_id JOIN locations l ON 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 e LEFT OUTER JOIN departments d ON (e.department_id = d.department_id); Result:

RIGHT OUTER JOIN: Eg: SELECT e.last_name, e.department_id, d.department_name FROM employees e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id); Result:

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

Prepared by: Mr.O.Obulesu, Asst.professor

[43]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


FROM employees e FULL OUTER JOIN departments d ON (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 d ON (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.

Max (Salary) 24000

Prepared by: Mr.O.Obulesu, Asst.professor

[44]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 employees WHERE department_id = 50;

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

Prepared by: Mr.O.Obulesu, Asst.professor

[45]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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

Eg: SELECT COUNT (commission_pct) FROM employees WHERE 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

[46]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 employees GROUP BY department_id;

Prepared by: Mr.O.Obulesu, Asst.professor

[47]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 employees GROUP BY department_id;

Grouping by More Than One Column:

Prepared by: Mr.O.Obulesu, Asst.professor

[48]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[49]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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

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

[50]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Excluding Group Results:

Fig: Maximum Salary per department when it is greater than 10000 Excluding Group Results: The HAVING Clause Use 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_function FROM table [WHEREcondition] [GROUP BY group_by_expression] [HAVING group_condition] [ORDER BY column]; Using the HAVING Clause:

Prepared by: Mr.O.Obulesu, Asst.professor

[51]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Eg: SELECT department_id, MAX (salary) FROM employees GROUP BY department_id HAVING MAX (salary)>10000;

Using the HAVING Clause: Eg: SELECT job_id, SUM (salary) PAYROLL FROM employees WHERE job_id NOT LIKE '%REP%' GROUP BY job_id HAVING SUM (salary) > 13000 ORDER BY SUM (salary);

Nesting Group Functions: Eg: SELECT MAX (AVG (salary)) FROM employees GROUP BY department_id;

Subqueries: Using a Subquery to Solve a Problem like Who has a salary greater than Abels? Main Query: Which employees have salaries greater than Abels salary? Subquery: What is Abels salary?

Subquery Syntax:

Prepared by: Mr.O.Obulesu, Asst.professor

[52]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Eg: SELECT select_list FROM table WHERE 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_name FROM employees WHERE 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

Main Query Sub Query ST_CLERK

Single-Row Subqueries:

Prepared by: Mr.O.Obulesu, Asst.professor

[53]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Return only one row Use single-row comparison operators Eg: =, <, >. <=, >= etc. Executing Single-Row Subqueries: Eg: SELECT last_name, job_id, salary FROM employees WHERE 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, salary FROM employees WHERE 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 employees GROUP BY department_id HAVING MIN (salary) > (SELECT MIN (salary) FROM employees WHERE department_id = 50); The HAVING Clause with Subqueries:

Prepared by: Mr.O.Obulesu, Asst.professor

[54]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 employees GROUP BY department_id HAVING MIN (salary) > (SELECT MIN (salary) FROM employees WHERE department_id = 50); 1.What is wrong with this Statement? Eg: SELECT employee_id, last_name FROM employees WHERE salary = (SELECT MIN (salary) FROM employees GROUP BY department_id); ERROR at line 4: ORA-01427: single-row subquery returns more than one row Single-row operator with multiple-row subquery 2. Will this Statement Return Rows? Eg: SELECT last_name, job_id FROM employees WHERE 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

[55]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Eg: SELECT employee_id, last_name, job_id, salary FROM employees WHERE 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, salary FROM employees WHERE 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 emp WHERE emp.employee_id NOT IN (SELECT mgr.manager_id FROM employees mgr); Creating Views: Database Objects TABLE - Basic unit of storage; composed of rows and columns VIEW - Logically represents subsets of data from one or more tables SEQUENCE - Generates primary key values INDEX Improves the performance of some queries SYNONYM Alternative name for an object What is a View? Why Use Views?

Prepared by: Mr.O.Obulesu, Asst.professor

[56]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


To restrict data access To make complex queries easy To provide data independence To present different views of the same data Simple Views and Complex Views: Feature Number of tables Contain functions Contain groups of data DML operations Creating a View: Simple Views One No No through a view, Yes Complex Views One or more Yes Yes Not always

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

[57]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

USER_VIEWS
SELECT employee_id, last_name,salary FROM employees WHERE department_id=80;

EMPVU80

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;

Prepared by: Mr.O.Obulesu, Asst.professor

[58]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Rules for Performing DML Operations on a View: 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;

Prepared by: Mr.O.Obulesu, Asst.professor

[59]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Inline Views: 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

[60]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[61]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 index ON table (column [, column]...); Improve the speed of query access to the LAST_NAME column in the EMPLOYEES table. Eg: CREATE INDEX emp_last_name_idx ON 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

[62]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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.uniqueness FROM user_indexes ix, user_ind_columns ic WHERE ic.index_name = ix.index_name AND 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_idx ON departments (UPPER (department_name)); Index created. Eg: SELECT * FROM departments WHERE 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

[63]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 synonym FOR 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 tables Creating Users: The DBA creates users by using the CREATE USER statement. Eg: CREATE USER user IDENTIFIED BY password; CREATE USER Scott IDENTIFIED BY tiger; User created.

Prepared by: Mr.O.Obulesu, Asst.professor

[64]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 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 owners object Scott;

Grant query privileges on the EMPLOYEES table: Eg: GRANT select ON employees TO sue, rich;

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

Prepared by: Mr.O.Obulesu, Asst.professor

[65]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[66]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[67]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


SQL>
2

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

Enter value for client_no: 001 Enter value for name: ivan Enter value for city: bombay Enter value for pincode: 400054 Enter value for state: maharastra Enter value for bal_due: 15000 old 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: 002 Enter value for name: vandana Enter value for city: madras Enter value for pincode: 780001 Enter value for state: tamilnadu Enter value for bal_due: 0 old 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: 003 Enter value for name: pramada Enter value for city: bombay Enter value for pincode: 400057 Enter value for state: maharastra Enter value for bal_due: 500 old 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: 004 Enter value for name: basu Enter value for city: bombay Enter value for pincode: 400056 Enter value for state: maharastra Enter value for bal_due: 0 old 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

[68]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


SQL> / Enter value for client_no: 005 Enter value for name: ravi Enter value for city: delhi Enter value for pincode: 100001 Enter value for state: Enter value for bal_due: 2000 old 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: 006 Enter value for name: rukmini Enter value for city: bombay Enter value for pincode: 400050 Enter value for state: maharastra Enter value for bal_due: 0 old 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 ----------------------------------------------------------------SELL_PRICE COST_PRICE ------------------p0001 1.44floppies 5 piece 100 20 525 p03453 p06734 monitors mouse 6 piece 5 piece 10 20 3 5 12000 1050 REORDER

1150 11200 500 REORDER

PRODUCT_NO DESCRIPTION PROFIT_PERCENT UNIT_MEASURE QTY_ON_HAND ----------------------------------------------------------------SELL_PRICE COST_PRICE ------------------p07865 1.22floppies 5 piece 100 20 525 p07868 p07885 keyboards cddrive 3 2 piece piece 10 10 3 3 3150 5200

500 3050 5100

Prepared by: Mr.O.Obulesu, Asst.professor

[69]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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

8000 1000 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

[70]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


p08865 9 rows selected. SQL> select *from client_master where city='bombay';
CLIENT _NO NAME CITY STATE PINCODE BAL_DUE

1.22drive

------001 003 004 006

--------ivan pramada basu rukmini

---------bombay bombay bombay bombay

-----------maharastra maharastra maharastra maharastra

-------400054 400057 400056 400050

-------15000 500 0 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

[71]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[72]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[73]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 jaya hema khaleel hari rathod bhaskar ravi

---------begam sankar giri ali krishna 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 jaya

-----------------7 4

Prepared by: Mr.O.Obulesu, Asst.professor

[74]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


hema khaleel hari rathod bhaskar ravi 8 rows selected. SQL> select first_name, length (first_name) as "length" from emp; FIRST_NAME ---------haseena jaya hema khaleel hari rathod bhaskar ravi 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 length ---------7 4 4 7 4 6 7 4 4 7 4 6 7 4

Prepared by: Mr.O.Obulesu, Asst.professor

[75]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[76]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[77]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[78]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 --------13-MAY-20 12-JUN-10 10-JUN-10 10-JUL-98 08-AUG-87 09-DEC-12 10-MAR-85 31-MAR-20 14-FEB-00 24-MAY-25 29-JUL-96 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: date after 10 months -----------------------13-MAR-21 12-APR-11 10-APR-11 10-MAY-99 08-JUN-88 09-OCT-13 10-JAN-86 31-JAN-21 14-DEC-00 24-MAR-26 29-MAY-97

Prepared by: Mr.O.Obulesu, Asst.professor

[79]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 begam sankar giri 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; HIRE_DATE 10-OCT-89 12-JUN-10 10-JUN-10 SALARY 8000 45000 25000 review date sixteenth-april-nineteen ninety thirteenth-december -twenty ten thirteenth-december -twenty ten

Prepared by: Mr.O.Obulesu, Asst.professor

[80]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[81]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[82]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[83]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[84]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 ----------------ENO ENAME SALARY

Null? -------NOT NULL

Type --------------------NUMBER (4) VARCHAR2 (10) 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

[85]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[86]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[87]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[88]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT SALES_ORDER Description: S_order_no primary key S_order_date Sell_price Order_status

varchar2 date number varchar2

SALES ORDER DETAILS Description: S_order_no references sales order(s_order_no) Product_no references product_master(product_no) Qty_ordered number Qty_displayed number Product_rate number SALES_MASTER Description: Sales_man_no Sales_name Address City State Pincode Salesamount varchar2 varchar2 varchar2 varhchar2 varchar2 number not null primary key starts with s not null not null

varchar2 varchar2

/*JOIN RELATED QUERIES */

Prepared by: Mr.O.Obulesu, Asst.professor

[89]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 s Where 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

[90]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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_no And 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

[91]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 -----------------176 haseena 7341 jaya 1543 hema 5456 khaleel 7841 hari 3043 rathod 4321 bhaskar 1763 ravi 8 rows selected. SQL> insert into emp_v1 values (4568,'lok', 45571); 1 row created. SQL> select *from emp_v1; EMP_ID FIRST_NAME -----------------176 haseena 7341 jaya 1543 hema 4568 lok 5456 khaleel 7841 hari 3043 rathod 4321 bhaskar 1763 ravi 9 rows selected. SQL> delete from emp_v1 where emp_id=1763; 1 row deleted. SALARY --------8000 45000 25000 45571 25300 40000 14200 12000 7500 SALARY --------8000 45000 25000 25300 40000 14200 12000 7500

Prepared by: Mr.O.Obulesu, Asst.professor

[92]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


SQL> select *from emp_v1; EMP_ID FIRST_NAME -----------------176 haseena 7341 jaya 1543 hema 4568 lok 5456 khaleel 7841 hari 3043 rathod 4321 bhaskar 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 --------- ---------176 haseena 7341 jaya 1543 hema 4568 lok 5456 khaleel 7841 hari 5452 sankar 3043 rathod 4321 bhaskar 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; SALARY --------8000 45000 25000 45571 25300 40000 57545 14200 12000 SALARY --------8000 45000 25000 45571 25300 40000 14200 12000

Prepared by: Mr.O.Obulesu, Asst.professor

[93]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


View created. SQL> select *from emp_dept; EMP_ID --------4567 7341 1543 5456 7841 3043 4321 FIRST_NAME ---------haseena jaya hema khaleel hari rathod bhaskar DEPT_ID --------10 10 10 30 50 20 40 LOC_ID --------2001 2001 2001 2002 2001 2001 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 --------4567 7341 1543 5456 7841 3043 FIRST_NAME ---------haseena jaya hema khaleel hari rathod DEPT_ID --------10 10 10 30 50 20 LOC_ID --------2001 2001 2001 2002 2001 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 -----------------4567 haseena 7341 jaya 1543 hema

DEPT_ID --------10 10 10

LOC_ID --------2001 2001 2001

Prepared by: Mr.O.Obulesu, Asst.professor

[94]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


5456 7841 3043 khaleel hari rathod 30 50 20 2002 2001 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

[95]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 -------------------12000 bhaskar 40000 hari 8000 haseena 25000 hema 45000 jaya 25000 khaleel 10000 krishna 13000 rathod 7500 ravi 20000 sada 15000 sankar 11 rows selected. SQL> select max (salary), first_name, dept_id from emp 2 group by dept_id, first_name; MAX(SALARY) FIRST_NAME -------------------8000 haseena 25000 hema 45000 jaya 10000 krishna 20000 sada 13000 rathod 25000 khaleel 12000 bhaskar 15000 sankar 40000 hari 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; DEPT_ID ---------10 10 10 10 10 20 30 40 40 50 DEPT_ID ---------40 50 10 10 10 30 10 20 10 40

Prepared by: Mr.O.Obulesu, Asst.professor

[96]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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

SQL> select first_name, salary from emp; FIRST_NAME ---------haseena jaya hema sada khaleel hari krishna sankar rathod bhaskar ravi 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 jayasankar@gmail.com12-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 SALARY ---------8000 45000 25000 20000 25000 40000 10000 15000 13000 12000 7500

Prepared by: Mr.O.Obulesu, Asst.professor

[97]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


9876 krishna mohan 1001 10 1070 sankar vardhan 3043 rathod 4321 bhaskar 1763 ravi chandra 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 jayasankar@gmail.com 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 JOB_NAME SALARY COMM MANAGER_ID HIRE_DATE DEPT_ID JOB_ID 10-MAR-85 31-MAR-20 14-FEB-00 24-MAY-25 29-JUL-96 3 assprof 2 prof 4 clerk 6 clerk 4 clerk 15000 13000 12000 7500 3500 1000 0 1250 10000 1004 1002 1004 2000 40 20 40

Prepared by: Mr.O.Obulesu, Asst.professor

[98]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


---------- ---------- ---------- ------------------------------ --------- ---------- ---------- ---------- ------------------- ---------176 haseena begam 10-OCT-89 3 prof 8000 1200 1001 10 7341 jaya sankar jayasankar@gmail.com 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) ----------20000 12000 45000 25000 JOB_NAME ------------assprof clerk hod 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

[99]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


NEW_MONTHS ----------239.92499 -134.92499 -239.92499 -158.31209 187.526622 8.13952546 38.0427513 -265.98951 -239.92499 -115.79596 8.07500933 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) --------------------------------- ---------134.925147 20000 239.925147 15000 -187.52647 12000 158.312244 7500 239.925147 10000 -38.042595 40000 -8.139369 45000 -8.0748529 25000 115.796115 13000 239.925147 8000 265.989663 25000 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 jayasankar@gmail.com 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 JOB_NAME ---------assprof assprof clerk clerk clerk hod hod prof prof prof prof MAX(SALARY) ----------15000 20000 10000 7500 12000 45000 40000 25000 8000 13000 25000 JOB_NAME ---------assprof assprof clerk clerk clerk hod hod prof prof prof prof

Prepared by: Mr.O.Obulesu, Asst.professor

[100]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


1070 sankar vardhan 3043 rathod 4321 bhaskar 1763 ravi chandra 11 rows selected. SQL> select *from emp_v2; FIRST_NAME ---------- haseena krishna sada bhaskar sankar DEPT_ID --------- 10 10 10 40 40 MAXS --------8000 10000 20000 12000 15000 MINS ---------8000 10000 20000 12000 15000 10-OCT-89 14-FEB-00 24-MAY-25 29-JUL-96 3 assprof 2 prof 4 clerk 6 clerk 15000 3500 1004 13000 1000 1002 12000 0 1004 7500 1250 40 20 40

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

[101]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[102]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[103]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


DOB DOJ GENDER PROF1 PROF2 SALARY SQL> spool off; SQL>select *from tab; TNAME -----------------------------CHALLAN_DETAILS CHALLAN_HEADER CLIENT_MASTER DEPT EMP EMP_V1 EMP_V2 PRODUCT_MASTER PROGRAMMER RESERVES SAILORS TABTYPE CLUSTERID ------------TABLE TABLE TABLE TABLE TABLE VIEW VIEW TABLE TABLE TABLE TABLE CLUSTERID ---------DATE DATE CHAR (1) VARCHAR2 (5) VARCHAR2 (5) NUMBER (5)

TNAME TABTYPE -----------------------------------SALES_ORDER TABLE SAMPLE1 TABLE SAMPLE3 TABLE SOFTWARE TABLE STUDIES TABLE 16 rows selected. SQL> select *from software; PNAME TITLE --------------- --------------hasi bank venu resort_info navani rail_info jagan bus_res ravi library_mgmt harinath sys_admn jayasankar satilite_mgmt sada bus_res hari acc kasula bank DEV_IN ---------oracle c++ .net c oracle c oracle pascal vb vb

SCOST ---------15000 12300 5632 4563 47896 7896 78965 4566 4598 7454

DCOST ---------10000 1056 1253 1245 15623 4563 45863 10568 2122 2483

SOLD ---------50 1520 145 1356 4589 1253 12356 2 45 789

Prepared by: Mr.O.Obulesu, Asst.professor

[104]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 ---------begam sankar giri LAST_NAME ---------siva ali krishna LAST_NAME ---------mohan vardhan HIRE_DATE --------10-OCT-89 12-JUN-10 10-JUN-10 HIRE_DATE --------10-JUL-98 08-AUG-87 09-DEC-12 HIRE_DATE --------10-OCT-89 10-OCT-89 14-FEB-00 HIRE_DATE --------24-MAY-25 29-JUL-96 SALARY ---------8000 45000 25000 review date ----------------------------------------sixteenth-april-nineteen ninety thirteenth-december -twenty ten thirteenth-december -twenty ten review date -----------------------------------------------eleventh-january -nineteen ninety-nine fifteenth-february -nineteen eighty-eight tenth-june -twenty thirteen

SALARY ---------20000 25000 40000 SALARY ---------10000 15000 13000 SALARY ---------12000 7500

review date ----------------------------------------sixteenth-aprilnineteen ninety sixteenth-april-nineteen ninety twenty-first-august-two thousand review date -----------------------------------------------first-december -twenty twenty-five third-february -nineteen ninety-seven

LAST_NAME ---------Chandra 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 ---------begam sankar giri siva ali krishna mohan vardhan HIRE_DATE --------10-OCT-89 12-JUN-10 10-JUN-10 10-JUL-98 08-AUG-87 09-DEC-12 10-OCT-89 10-OCT-89 SALARY ---------8000 45000 25000 20000 25000 40000 10000 15000 review date -----------------------------------------------sixteenth-april -nineteen ninety thirteenth-december -twenty ten thirteenth-december -twenty ten eleventh-january -nineteen ninety-nine fifteenth-february -nineteen eighty-eight tenth-june -twenty thirteen sixteenth-april -nineteen ninety sixteenth-april -nineteen ninety

Prepared by: Mr.O.Obulesu, Asst.professor

[105]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


14-FEB-00 24-MAY-25 29-JUL-96 13000 12000 7500 twenty-first-august -two thousand first-december -twenty twenty-five third-february -nineteen ninety-seven

chandra 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 -------------------- ------------------haseenabegam 10-OCT-89 jayasankar 12-JUN-10 hemagiri 10-JUN-10 sadasiva 10-JUL-98 khaleelali 08-AUG-87 harikrishna 09-DEC-12 krishnamohan 10-OCT-89 sankarvardhan 10-OCT-89 rathod 14-FEB-00 bhaskar 24-MAY-25 ravichandra 29-JUL-96 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; SALARY review date ------------ ------------------------------------8000 sixteenth-april -nineteen ninety 45000 thirteenth-december -twenty ten 25000 thirteenth-december -twenty ten 20000 eleventh-january-nineteenninety-nine 25000 fifteenth-february -nineteen eighty-eight 40000 tenth-june -twenty thirteen 10000 sixteenth-april -nineteen ninety 15000 sixteenth-april -nineteen ninety 13000 twenty-first-august -two thousand 12000 first-december -twenty twenty-five 7500 third-february -nineteen ninety-seven

Prepared by: Mr.O.Obulesu, Asst.professor

[106]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


FIRST_NAME||LAST_NAM -------------------haseenabegam jayasankar hemagiri sadasiva khaleelali harikrishna krishnamohan sankarvardhan rathod bhaskar ravichandra 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 HIRE_DATE --------10-OCT-89 12-JUN-10 10-JUN-10 10-JUL-98 08-AUG-87 09-DEC-12 10-OCT-89 10-OCT-89 14-FEB-00 24-MAY-25 29-JUL-96 day --------tuesday saturday thursday friday saturday sunday tuesday tuesday monday saturday monday

Prepared by: Mr.O.Obulesu, Asst.professor

[107]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[108]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 --------------jagan ravi harinath hasi jayasankar navani 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 AGE EXPERIENCE ---------- ---------23 9 21 0 22 2 21 -11 22 0 22 -13

Prepared by: Mr.O.Obulesu, Asst.professor

[109]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 --------------- --------- --------- - ---------- ---------- ---------jayasankar 09-AUG-87 12-JUL-10 m c++ java 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. SALARY 65621

Prepared by: Mr.O.Obulesu, Asst.professor

[110]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[111]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[112]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[113]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[114]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[115]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 ---------- --------- --------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: 3 old 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, MONTHS

Prepared by: Mr.O.Obulesu, Asst.professor

[116]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------7341 jaya sankar jayasankar@gmail.com 23-NOV-09 1 hod 45000 1000 1001 10 1543 hema giri 25000 5000 1001 3043 rathod 13000 1000 1002 23-NOV-09 10 14-FEB-00 20 08-AUG-87 30 2 prof 2 prof 2 prof JOB_ID

5456 khaleel ali 25000 5000 1003

Prepared by: Mr.O.Obulesu, Asst.professor

[117]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


4321 bhaskar 12000 0 23-NOV-09 1004 40 23-NOV-09 50 1 hod 4 clerk

7841 hari krishna 40000 9000 1005 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_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------7341 jaya sankar jayasankar@gmail.com 23-NOV-09 1 hod 45000 1000 1001 10 7841 hari krishna 40000 9000 1005 23-NOV-09 50 1 hod JOB_ID

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_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------JOB_ID

Prepared by: Mr.O.Obulesu, Asst.professor

[118]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------7341 jaya sankar jayasankar@gmail.com 45000 1000 1001 10 1543 hema giri 25000 5000 1001 5456 khaleel ali 25000 5000 1003 7841 hari krishna 40000 9000 1005 23-NOV-09 10 08-AUG-87 30 23-NOV-09 50 1 hod 2 prof

23-NOV-09 2 prof

1 hod

16.List all the employees who dont have any manager? SQL> select *from emp where manager_id is null; EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------5456 khaleel ali 08-AUG-87 2 prof 25000 5000 30 7841 hari krishna 40000 9000 1763 ravi chandra 7500 1250 23-NOV-09 50 29-JUL-96 6 clerk 1 hod JOB_ID

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

[119]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 sailors Values (&sid,, `&sname`,&rating,&age); Sid ---22 29 37 32 58 64 71 74 85 95 sname -------dustin brutus lubber andy pusty horatio zorba horatio art 3 bob 3 rating age -----------7 45.0 1 33.0 8 55.5 8 25.5 10 35.0 7 35.0 10 16.0 9 35.0 25.5 63.5

insert into reserves values (&sid,&bid,`&data`);

Prepared by: Mr.O.Obulesu, Asst.professor

[120]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT sid ---22 22 22 22 31 31 31 64 64 74 bid ---101 102 103 104 102 103 104 101 102 103 day ---10/10/98 10/10/98 10/8/98 10/7/98 10/10/98 11/06/98 11/12/98 9/05/98 9/08/08 9/08/08

insert into boats values(&bid,`&bname`,`&color`); bid bname ----- -------101 inter lake 102 inter lakes 103 clipper 104 marine color ------blue red green 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

[121]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[122]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[123]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


PROGRAM 11 To 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

[124]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 2 prof 25300 7841 hari 1 hod 5452 sankar 57545 1 sankar krishna 40000 5000 9000 08-AUG-87 30 23-NOV-09 50

Prepared by: Mr.O.Obulesu, Asst.professor

[125]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

[126]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------176 haseena begam 10-OCT-89 3 prof 8000 1200 1001 10 7341 jaya sankar jayasankar@gmail.com 45000 1000 1001 10 1543 hema giri 25000 5000 1001 5456 khaleel ali 25000 5000 7841 hari krishna 40000 9000 3043 rathod 13000 1000 4321 bhaskar 12000 0 1002 1004 30 23-NOV-09 50 14-FEB-00 20 23-NOV-09 40 29-JUL-96 6 clerk 4 clerk 2 prof 1 hod 23-NOV-09 10 08-AUG-87 2 prof 23-NOV-09 2 prof 1 hod JOB_ID

1763 ravi chandra 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_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------176 haseena begam 10-OCT-89 3 prof 8000 1200 1001 10 7341 jaya sankar jayasankar@gmail.com 45000 1000 1001 10 23-NOV-09 1 hod JOB_ID

Prepared by: Mr.O.Obulesu, Asst.professor

[127]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


1543 hema giri 25000 5000 1001 5456 khaleel ali 25000 5000 7841 hari krishna 40000 9000 3043 rathod 13000 1000 4321 bhaskar 12000 0 1004 40 1002 30 23-NOV-09 50 14-FEB-00 20 23-NOV-09 4 clerk 2 prof 1 hod 23-NOV-09 10 08-AUG-87 2 prof 2 prof

7 rows selected. SQL> select *from emp; EMP_ID FIRST_NAME LAST_NAME EMAIL HIRE_DATE JOB_NAME --------- ---------- ---------- ------------------------------ --------- --------- ---------SALARY COMM MANAGER_ID DEPT_ID --------- --------- ---------- --------176 haseena begam 10-OCT-89 3 prof 8000 1200 1001 10 7341 jaya sankar jayasankar@gmail.com 45000 1000 1001 10 1543 hema giri 25000 5000 1001 5456 khaleel ali 25000 5000 7841 hari krishna 40000 9000 3043 rathod 13000 1000 4321 bhaskar 12000 0 1004 40 1002 30 23-NOV-09 50 14-FEB-00 20 23-NOV-09 4 clerk 2 prof 1 hod 23-NOV-09 10 08-AUG-87 2 prof 23-NOV-09 2 prof 1 hod JOB_ID

Prepared by: Mr.O.Obulesu, Asst.professor

[128]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

7 rows selected

Prepared by: Mr.O.Obulesu, Asst.professor

[129]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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

PL/SQL Block

PL/SQL Block

Procedural Statement Executor

SQL statement Executor

Oracle Server

Prepared by: Mr.O.Obulesu, Asst.professor

[130]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Benefits of PL/SQL Integration

oracle Server Benefits of PL/SQL Improved performance

Application

SQ L Sql SQL IF.. Then SQL Else SQL END IF;

Other DBMS

Application

Oracle With PL/SQL

Modularize program development

DECLARE

BEGIN

Exception
Prepared by: Mr.O.Obulesu, Asst.professor

[131]

End;

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 integrity Improved performance Improved code clarity

Declaring Variables )

PL/SQL Block Structure DECLARE (Optional) Variables, cursors, user-defined exceptions BEGIN (Mandatory)

Prepared by: Mr.O.Obulesu, Asst.professor

[132]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 [declare] Begin statements [exception] End;

Procedure procedure name Begin ..statements [exception] End;

Function function name return datatype is Begin ..statements Return value [Exception] End;

Prepared by: Mr.O.Obulesu, Asst.professor

[133]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Program Constructs

DECLARE

BEGIN EXCEPTION

END;

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

[134]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 Variables Syntax: 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

Prepared by: Mr.O.Obulesu, Asst.professor

[135]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Variable Initialization and Keywords Assignment operator (:=) DEFAULT keyword NOT NULL constraint identifier := 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 MONTH INTERVAL DAY TO SECOND

Scalar Variable Declarations Examples: DECLARE v_job v_count v_total_sal v_orderdate c_tax_rate VARCHAR2(9); BINARY_INTEGER := 0; NUMBER(9,2) := 0; DATE := SYSDATE + 7; CONSTANT NUMBER(3,2) := 8.25;

Prepared by: Mr.O.Obulesu, Asst.professor

[136]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


v_valid ... BOOLEAN NOT NULL := TRUE;

The %TYPE Attribute 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 Variables To reference a bind variable in PL/SQL, you must prefix its name with a colon (:). Example: VARIABLE g_salary NUMBER BEGIN SELECT salary INTO :g_salary FROM employees WHERE employee_id = 178; END; / PRINT g_salary Referencing Non-PL/SQL Variables Store the annual salary into a iSQL*Plus host variable. :g_monthly_sal := v_sal / 12;

Prepared by: Mr.O.Obulesu, Asst.professor

[137]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Reference non-PL/SQL variables as host variables. Prefix the references with a colon (:).

DBMS_OUTPUT.PUT_LINE An Oracle-supplied packaged procedure An alternative for displaying data from a PL/SQL block Must be enabled in iSQL*Plus with SET SERVEROUTPUT ON SET SERVEROUTPUT ON DEFINE 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 words PL/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

Prepared by: Mr.O.Obulesu, Asst.professor

[138]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


... 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

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_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

v_address||CHR(10)||

Prepared by: Mr.O.Obulesu, Asst.professor

[139]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


...

This statement produces a compilation error if the variable v_date is declared as a DATE data type v_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. 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 Scope An 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;

Prepared by: Mr.O.Obulesu, Asst.professor

[140]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


v_message VARCHAR2(255) := ' eligible for commission'; BEGIN DECLARE v_sal NUMBER(7,2) := 50000; v_comm NUMBER(7,2) := 0; v_total_comp NUMBER(7,2) := v_sal + v_comm; BEGIN v_message := 'CLERK not'||v_message; outer.v_comm := v_sal * 0.30; 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 value v_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 indenting Indenting Code BEGIN IF x=0 THEN y:=1; END IF; END; DECLARE v_deptno NUMBER(4); v_location_id NUMBER(4);

Prepared by: Mr.O.Obulesu, Asst.professor

[141]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


BEGIN SELECT department_id, location_id INTO v_deptno, v_location_id FROM departments WHERE department_name = 'Sales'; ... END; / Interacting with the Oracle Server SQL 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/SQL SET SERVEROUTPUT ON DECLARE v_sum_sal NUMBER(10,2); v_deptno NUMBER NOT NULL := 60; BEGIN

Prepared by: Mr.O.Obulesu, Asst.professor

[142]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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

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/SQL Make changes to database tables by using DML commands: INSERT UPDATE DELETE MERGE Inserting Data Add 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;

Prepared by: Mr.O.Obulesu, Asst.professor

[143]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


/ Updating Data Increase the salary of all employees who are stock clerks. Example: DECLARE v_sal_increase employees.salary%TYPE := 800; BEGIN UPDATE employees SET salary = salary + v_sal_increase WHERE job_id = 'ST_CLERK'; END; / Deleting Data Delete 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 Rows DECLARE v_empno employees.employee_id%TYPE := 100; BEGIN MERGE 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.

Prepared by: Mr.O.Obulesu, Asst.professor

[144]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


The names of database table columns take precedence over the names of local variables SQL 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 Using SQL cursor attributes, you can test the outcome of your SQL statements.

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 Delete rows that have the specified employee ID from the EMPLOYEES table. Print the PL/SQL rows implicit number ofclosesdeleted. cursors Example: immediately after they are executed
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.

Prepared by: Mr.O.Obulesu, Asst.professor

[145]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Use COMMIT and ROLLBACK SQL statements to terminate a transaction explicitly. Writing Control Structures Controlling 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 Statements Syntax: Simple IF Statements If 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 Statements If 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 Condition THEN actions (including further IF statements) ELSE actions (including further IF statements)

Prepared by: Mr.O.Obulesu, Asst.professor

[146]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

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 ... IF MONTHS_BETWEEN(SYSDATE,v_hire_date)/12 > 5 THEN v_five_years := TRUE; ELSE v_five_years := FALSE; END IF; ...

IF Condi tion True THEN actions Then Action

Elsif Cond ition Else Actions

IF-THEN-ELSIF Statements For 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;

Prepared by: Mr.O.Obulesu, Asst.professor

[147]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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 several CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2 ... WHEN expressionN THEN resultN [ELSE resultN+1;] END; CASE Expressions: Example SET SERVEROUTPUT ON DECLARE 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 Nulls When 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

Prepared by: Mr.O.Obulesu, Asst.professor

[148]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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; EXIT WHEN v_counter > 3; END LOOP; END; / FOR Loops FOR 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 Loops Insert 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 assignment Guidelines While Using Loops Use the basic loop when the statements inside the loop must execute at least once.

Prepared by: Mr.O.Obulesu, Asst.professor

[149]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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>> 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 reusable PL/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 Record

Prepared by: Mr.O.Obulesu, Asst.professor

[150]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


TYPE 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), job_id VARCHAR2(10), salary NUMBER(8,2)); emp_record emp_record_type; ... PL/SQL Record Structure

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

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.

Prepared by: Mr.O.Obulesu, Asst.professor

[151]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


The %ROWTYPE Attribute Examples: 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 Column of scalar or record data type Can increase in size dynamically because they are unconstrained Creating an INDEX BY Table TYPE 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 names TYPE 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:

Prepared by: Mr.O.Obulesu, Asst.professor

[152]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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 ON DECLARE 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 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 Cursors About Cursors Every 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

Cursor

Controlling Explicit Cursors

DECLARE

OPEN

Fetch

EM PT Y?

Close [153]

Prepared by: Mr.O.Obulesu, Asst.professor

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

Eg:

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 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 Cursor FETCH 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 ...;

Prepared by: Mr.O.Obulesu, Asst.professor

[154]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


... -- Process the retrieved data END LOOP; Closing the Cursor CLOSE 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 Attributes Obtain status information about a cursor. %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 fetch returns a row; complement of %NOTFOUND %ROWCOUNT Number Evaluates to the total number of rows returned so far The %ISOPEN Attribute

recent

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 loop DECLARE v_empno employees.employee_id%TYPE; v_ename employees.last_name%TYPE;

Prepared by: Mr.O.Obulesu, Asst.professor

[155]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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 ; Creating Procedures Benefits of Subprograms Easy maintenance Improved data security and integrity Improved performance Improved code clarity Developing Subprograms by Using iSQL*Plus

Prepared by: Mr.O.Obulesu, Asst.professor

[156]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 Procedures CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] IS|AS PL/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 Parameters Formal 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:

Prepared by: Mr.O.Obulesu, Asst.professor

[157]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


raise_sal(v_id, 2000)

Calling Environment t

Procedure
IN parameter OUT parameter IN OUT parameter (DECLARE) BEGIN EXCEPTION END;

Creating Procedures with Parameters

IN Default mode Value is passed into Subprogram Formal parameter acts as a constant Actual parameter can be a literal, expression, constant, or initialized variable Can be assigned a default
IN Parameters: Example

OUT Must be specified Returned to Calling Environment

IN OUT Must be specified Returned to Calling Environment

Uninitialized variable Initialized variable Must be a variable Must be a variable

Cannot be assigned a default value

Cannot be assigned a default value

CREATE OR REPLACE PROCEDURE raise_salary (p_id IN employees.employee_id%TYPE) IS BEGIN UPDATE employees SET salary = salary * 1.10 WHERE employee_id = p_id; END raise_salary;

Prepared by: Mr.O.Obulesu, Asst.professor

[158]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


/ Eg:

176
OUT Parameters: Example

P_id

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) IS BEGIN 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 Eg: VARIABLE g_name VARCHAR2(25) VARIABLE g_sal NUMBER VARIABLE g_comm NUMBER EXECUTE query_emp(171, :g_name, :g_sal, :g_comm) PRINT g_name Load and run the emp_query.sql script file to create the QUERY_EMP procedure. Declare host variables, execute the QUERY_EMP procedure, and print the value of the global G_NAME variable

Prepared by: Mr.O.Obulesu, Asst.professor

[159]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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) IS BEGIN INSERT INTO departments(department_id, department_name, location_id) VALUES (departments_seq.NEXTVAL, p_name, p_loc); END add_dept; / Examples of Passing Parameters BEGIN add_dept; add_dept ('TRAINING', 2500); add_dept ( p_loc => 2400, p_name =>'EDUCATION'); add_dept ( p_loc => 1200) ; END; / SELECT department_id, department_name, location_id FROM departments;

Declaring Subprograms CREATE OR REPLACE PROCEDURE leave_emp2 (p_id IN employees.employee_id%TYPE)

Prepared by: Mr.O.Obulesu, Asst.professor

[160]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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 Block DECLARE v_id NUMBER := 163; BEGIN raise_salary(v_id); --invoke procedure COMMIT; ... END; Invoking a Procedure from Another Procedure CREATE OR REPLACE PROCEDURE process_emps IS 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; / Invoking a Procedure from Another Procedure CREATE OR REPLACE PROCEDURE process_emps IS 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;

Prepared by: Mr.O.Obulesu, Asst.professor

[161]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


/ Removing Procedures Drop a procedure stored in the database. DROP PROCEDURE procedure_name DROP PROCEDURE raise_salary; Creating Functions Overview of Stored Functions A function is a named PL/SQL block that returns a 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 Functions CREATE [OR REPLACE] FUNCTION function_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] RETURN datatype IS|AS PL/SQL Block; The PL/SQL block must have at least one RETURN statement.

Syntax for Creating Functions CREATE [OR REPLACE] FUNCTION function_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] RETURN datatype IS|AS PL/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 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: SQL

Prepared by: Mr.O.Obulesu, Asst.professor

[162]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


CREATE OR REPLACE FUNCTION get_sal (p_id IN employees.employee_id%TYPE) RETURN NUMBER IS 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

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: Example CREATE OR REPLACE FUNCTION tax(p_value IN NUMBER) RETURN NUMBER IS BEGIN RETURN (p_value * 0.08); END tax; / SELECT employee_id, last_name, salary, tax(salary) FROM employees WHERE department_id = 100;

Prepared by: Mr.O.Obulesu, Asst.professor

[163]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

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 Expressions To 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. 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 SQL CREATE OR REPLACE FUNCTION dml_call_sql (p_sal NUMBER) RETURN NUMBER IS BEGIN INSERT INTO employees(employee_id, last_name, email, hire_date, job_id, salary) VALUES(1, 'employee 1', 'emp1@company.com', SYSDATE, 'SA_MAN', 1000); RETURN (p_sal + 100); END; /

Prepared by: Mr.O.Obulesu, Asst.professor

[164]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Removing Functions
DROP FUNCTION function_name

Overview of Packages Packages: Group logically related PL/SQL types, items, and subprograms Consist of two parts: Specification Body 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 Specification Syntax: CREATE [OR REPLACE] PACKAGE package_name IS|AS public type and item declarations subprogram specifications END 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. Creating a Package Specification: Example 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; / 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: Example CREATE OR REPLACE PACKAGE BODY comm_package IS FUNCTION validate_comm (p_comm IN NUMBER) RETURN BOOLEAN IS v_max_comm NUMBER;

Prepared by: Mr.O.Obulesu, Asst.professor

[165]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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 RAISE_APPLICATION_ERROR (-20210, 'Invalid commission'); END IF; END reset_comm; END comm_package; Example 2: Invoke a package procedure from iSQL*Plus. EXECUTE comm_package.reset_comm(0.15) Example 3: Invoke a package procedure in a different schema. EXECUTE scott.comm_package.reset_comm(0.15) Example 4: Invoke a package procedure in a remote database. EXECUTE comm_package.reset_comm@ny(0.15) Declaring a Bodiless Package CREATE OR REPLACE PACKAGE global_consts IS

Prepared by: Mr.O.Obulesu, Asst.professor

[166]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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 NUMBER, p_yard OUT NUMBER) IS BEGIN p_yard := p_meter * global_consts.meter_2_yard; END meter_to_yard; / VARIABLE yard NUMBER EXECUTE meter_to_yard (1, :yard) PRINT yard Removing Packages

(p_meter IN

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 throughout a session or across transactions. Changes to the package specification require recompilation of each referencing subprogram.

Prepared by: Mr.O.Obulesu, Asst.professor

[167]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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 variables and 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 the same 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 database Guidelines for Designing Triggers Design triggers to: Perform related actions 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

Prepared by: Mr.O.Obulesu, Asst.professor

[168]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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. 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 Triggers CREATE [OR REPLACE] TRIGGER trigger_name timing

Prepared by: Mr.O.Obulesu, Asst.professor

[169]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


event1 [OR event2 OR event3] ON table_name trigger_body Note: 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 EMPLOYEES table only END IF; END; / Testing SECURE_EMP INSERT INTO employees (employee_id, last_name, email, hire_date, salary, department_id) VALUES (300, 'Smith', 'Rob', 'RSMITH', SYSDATE, first_name, job_id, 'IT_PROG', 4500, 60); insert into during business hours.');

Using Conditional Predicates in Triggers CREATE OR REPLACE TRIGGER secure_emp BEFORE INSERT OR UPDATE OR DELETE ON employees BEGIN IF (TO_CHAR (SYSDATE,'DY') IN ('SAT','SUN')) OR (TO_CHAR (SYSDATE, 'HH24') NOT BETWEEN '08' AND '18') THEN IF DELETING THEN

Prepared by: Mr.O.Obulesu, Asst.professor

[170]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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 Trigger Syntax: 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_body Eg: CREATE OR REPLACE TRIGGER restrict_salary 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 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 ROW BEGIN

cannot earn this

Prepared by: Mr.O.Obulesu, Asst.professor

[171]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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

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;

Prepared by: Mr.O.Obulesu, Asst.professor

[172]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


END; / INSTEAD OF Triggers Creating an INSTEAD OF Trigger Syntax:

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_body INSERT into EMP_DETAILS that is based on EMPLOYEES and DEPARTMENTS tables INSERT INTO emp_details(employee_id, ... ) VALUES(9001,'ABBOTT',3000,10,'abbott.mail.com','HR_MAN');

INSTEAD OF INSERT into EMP_DETAILS Differentiating Between Database Triggers and Stored Procedures Triggers Defined with CREATE TRIGGER Data dictionary contains source code in USER_TRIGGERS Implicitly invoked COMMIT, SAVEPOINT, and ROLLBACK are not allowed Procedures Defined with CREATE PROCEDURE Data dictionary contains source code in USER_SOURCE Explicitly invoked COMMIT, SAVEPOINT, and ROLLBACK are allowed Managing Triggers Disable or reenable a database trigger: ALTER TRIGGER trigger_name DISABLE | ENABLE Disable or reenable all triggers for a table: ALTER TABLE table_name DISABLE | ENABLE ALL TRIGGERS Recompile a trigger for a table:

Prepared by: Mr.O.Obulesu, Asst.professor

[173]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


ALTER TRIGGER trigger_name COMPILE DROP TRIGGER Syntax To 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 Triggers CREATE OR REPLACE TRIGGER audit_emp_trig AFTER UPDATE or INSERT or DELETE on EMPLOYEES FOR EACH ROW BEGIN 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_tab AFTER UPDATE or INSERT or DELETE on employees BEGIN audit_emp; END audit_emp_tab; / ---------------------------------- END OF PL/SQL--------------------------------------

Prepared by: Mr.O.Obulesu, Asst.professor

[174]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

PL/SQL PROGRAM 1 PL/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

Prepared by: Mr.O.Obulesu, Asst.professor

[175]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Old 2: n number:=&a; New 2: n number:=15; THE NUMBER IS DIVISABLE */

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 ON DECLARE 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;

Prepared by: Mr.O.Obulesu, Asst.professor

[176]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


/* INPUT / OUTPUT */ ************************ /* SQL>@char.sql Enter value for V_a:g Old 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:67 Old 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:* 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 3 A PL/SQL PROGRAM TO ACCEPT TWO NUMBERS AND DISPLAY THE BIGGEST ONE SET SERVEROUTPUT ON DECLARE 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

Prepared by: Mr.O.Obulesu, Asst.professor

[177]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


****************** SQL>@big.sql Enter 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. */

PROGRAM 4 /* PL/SQL PROGRAM TO PERFORM ARITHMETIC OPERATIONS */ SET SERVEROUTPUT ON DECLARE 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)

Prepared by: Mr.O.Obulesu, Asst.professor

[178]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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.sql Enter value for a : 4 Old 2: N1 number := &a; New 2: N1 number := 4 Enter value for a : 5 Old 2: N1 number := &b; New 2: N1 number := 5 Enter value for a : 3 Old 2: N1 number := &c; New 2: N1 number := 3 1.ADDITION 2.SUBTRACTION 3.MULTIPLICATION 4.DIVISION ENTER YOUR CHOICE The multiplication of two numbers is:20 PL/SQL procedure successfully completed. */

Prepared by: Mr.O.Obulesu, Asst.professor

[179]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 ON DECLARE 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;

Prepared by: Mr.O.Obulesu, Asst.professor

[180]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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.sql Enter the value for a:18 Old 2: v_deptno number:=&A; New 2:v_deptno number:=18; THE SALARY OF THE EMPLOYEE IS :24300 PL/SQL Procedure Successfully Completed. Enter the value for a:21 Old 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:22 Old 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

[181]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 CONDITION 70% basic salary Basic Salary <3000 60% of Basic Salary Basic Salary >3000 and Basic Salary <6000 50% of Basic Salary Basic Salary >=6000 The HRA is calculated as follows: HRA 30% of Basic Salary +DA 25% of Basic Salary +DA 20% of Basic Salary +DA CONDITION Basic Salary <=2000 Basic Salary >=2000 and Basic Salary <5500 Basic Salary >=5500

Gross Salary = Basic Salary + DA + HRA The deductions are calculated as follows: DEDUCTION CONDITION

Prepared by: Mr.O.Obulesu, Asst.professor

[182]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


30% of Gross Salary 20% of Gross Salary 15% of Gross Salary NIL 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 ) Values (&eno ,`&name`, `&bsal`); Enter value for eno:101 Enter value for name: jaffar Enter value for bsal:3700 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 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; BEGIN OPEN C1; LOOP FETCH C1 INTO X,B; Gross Salary >8000 Gross Salary >=6000 and Gross Salary <8000 Gross Salary >=5000 and Gross Salary <6000 Other wise.

Prepared by: Mr.O.Obulesu, Asst.professor

[183]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


EXIT WHEN C1%NOTFOUND; IF B>=6000 THEN JDA :=B*50/100; ELSEIF B>3000 THEN JDA:=B*60/100; ELSE JDA:=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 THEN JDED:=JGSAL*30/100; ELSEIF JGSAL >=6000 THEN 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

[184]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 FIRST SECOND THIRD FAIL CONDITION total marks >359 and pass in all subjects total marks >299 and <360 and pass in all sub. otherwise and pass in all subjects fail atleast in one of subjects

CREATING THE TABLE: Create table student( Rnumber number (4) unique,

Prepared by: Mr.O.Obulesu, Asst.professor

[185]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Name Fname Medium Tel Hin Eng Mat Sci Soc Tot Res varchar2(15), dob date, varchar2(15), varchar2(10), number(3), number(3), number(3), number(3), number(3), number(3), number(4), 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:101 Enter value for name:RAJA Enter value for dob:L6/12/79 Enter value for medium:English Enter value for tel:80 Enter value for hin:69 Enter value for eng:59 Enter value for mat:91 Enter value for sci:87 Enter 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; LOOP

Prepared by: Mr.O.Obulesu, Asst.professor

[186]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


FETCH 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 THEN RES2=FAIL; ELSEIF TOT2>359 THEN RES2:=FIRST CLASS; ELSEIF TOT2>299 THEN RES2:=SECOND CLASS: ELSE RES2:=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; 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.

Prepared by: Mr.O.Obulesu, Asst.professor

[187]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


*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 DECLARE X 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 FETCH C1 INTO X , M , P , C ,TOT; EXIT WHEN C1%NOTFOUND; IF TOT2=TOT3 THEN N:=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

[188]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 Agricultural Agricultural Domestic RS 2-50 Rs 2-00 Rs 1-50 Rs 3-00 Total units>2000 Total units<=1000 and >500 OtherWise Total units >800

Prepared by: Mr.O.Obulesu, Asst.professor

[189]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Domestic Domestic Rs 2-40 Rs.1-80 Toatal units <=800 and >500 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: 101 Enter the value for name: Sunil Enter the value for type:DC Enter the value for cmr: 4321 Enter the value for pmr:1234 Enter the value for Mname:January *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;

Prepared by: Mr.O.Obulesu, Asst.professor

[190]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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; 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) IS BEGIN UPDATE employees SET salary = salary * 1.10 WHERE employee_id = p_id; END raise_salary; / OUPUT: SQL> @EMP.SQL SQL> Exec Raise_salary (176);

Prepared by: Mr.O.Obulesu, Asst.professor

[191]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


PL/SQL Procedure Succcessfully Completed

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 NUMBER IS 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-OUTPUT SQL>PL/SQLProcedure Succesfully Completed. VARIABLE g_salary NUMBER EXECUTE :g_salary := get_sal(117) PRINT g_salary

Prepared by: Mr.O.Obulesu, Asst.professor

[192]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT 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 Body CREATE OR REPLACE PACKAGE BODY comm_package IS 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);

Prepared by: Mr.O.Obulesu, Asst.professor

[193]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


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)

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 ROW BEGIN 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-OUTPUT SQL>Trrigger created. INSERT INTO employees (employee_id, last_name, job_id, salary, ...) VALUES (999, 'Temp emp', 'SA_REP', 1000, ...);

Prepared by: Mr.O.Obulesu, Asst.professor

[194]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


UPDATE employees SET salary = 2000, last_name = 'Smith' WHERE employee_id = 999; SELECT user_name, timestamp, ... FROM audit_emp_table;

PROGRAM 14 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: customerand 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

Prepared by: Mr.O.Obulesu, Asst.professor

[195]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


Records:1 Spacing:0 Options: 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 accesskey ADD Add Record A SAVE Save Record S DEL Delete Record D QUIT Exit E 5. write the following PL/SQL code to ADD button. Trigger :When_Button_Pressed Code :Create_record;---compile and close

6.Write the following PL/SQL code to SAVE button Trigger :When_Button_Pressed Code :Commit_form;---compile and close 7.Write the following PL/SQL code to DEL button Trigger :When_Button_Pressed Code :Delete_record;---compile and close 8.Write the following PL/SQL code to QUIT button Trigger :When_Button_Pressed Code :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)

Prepared by: Mr.O.Obulesu, Asst.professor

[196]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


11. Save and run the Form.Select RUN command from File menu.

PROGRAM 15

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: 101 Enter value for iname: pen Enter value for itype: bal_red Enter value for rate: 15 CREATING REPORT IN THE REPORT DESIGNER. 1. select report designer option.

Prepared by: Mr.O.Obulesu, Asst.professor

[197]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT


( a new reports is created automatically by the name UNTITLED). 2. select data model node from the object navigator, press right mouse button and select editor option from the list. 3. Select SQL(query) button from the left side tool bar, and Click on the blank area of the editor. 4. Press right mouse button, select properties option and press Enter. 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 typeKeep your selection Screen. 11. Press Run report.

THANK YOU
Prepared by: Mr.O.Obulesu, Asst.professor

[198]

SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT

Prepared by: Mr.O.Obulesu, Asst.professor

[199]

You might also like