DBMS Lab Manual
DBMS Lab Manual
SYSTEMS
Prepared By
Mr.O.Obulesu,
Asst.Professor
[1]
[2]
[3]
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.
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;
[4]
(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)
[5]
(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:
[6]
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.
[7]
[8]
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);
[9]
[10]
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
[11]
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:
[12]
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.
[13]
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:
[14]
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
[15]
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:
[16]
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:
[17]
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;
[18]
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.
[19]
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;
[20]
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
[21]
[22]
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
[23]
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 ;
[24]
Sorting by Column Alias: Eg: SELECT employee_id, last_name, salary*12 as annsal FROM r_employees ORDER BY annsal; Result:
[25]
SQL Functions:
Output
Result value
arg n
Output
Result value
arg n
[26]
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
[27]
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
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
[28]
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:
[29]
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:
[30]
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:
[31]
Using the TO_CHAR Function with Dates: Eg: SELECT last_name, TO_CHAR (hire_date, 'fmDD Month YYYY') AS HIREDATE FROM employees;
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:
[32]
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);
[33]
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;
[34]
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;
[35]
(8 rows)
[36]
(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?
[37]
Retrieving Records with Equijoins: Eg: SELECT employees.employee_id, employees.last_name, employees.department_id, departments.department_id,
[38]
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.
[39]
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
[40]
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 ;
[41]
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.
[42]
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:
[43]
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.
[44]
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.
[45]
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.
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;
[46]
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.
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;
[47]
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;
[48]
Fig: Add up the salaries in the EMPLOYEES table for each job, grouped by department.
[49]
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
[50]
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:
[51]
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:
[52]
Guidelines for Using Subqueries: Enclose subqueries in parentheses. Place subqueries on the right side of the comparison condition. The ORDER BY clause in the subquery is not needed unless you are performing Top-N analysis. Use single-row operators with single-row subqueries and use multiple-row operators with multiple-row subqueries. Types of Subqueries: Single-row subquery Multiple Row Subquery
Single-Row Subqueries:
[53]
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:
[54]
[55]
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?
[56]
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;
[57]
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;
[58]
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;
[59]
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}];
[60]
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.
[61]
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
[62]
*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.
[63]
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.
[64]
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;
[65]
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)
[66]
[67]
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.
[68]
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
[69]
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
[70]
1.22drive
-------15000 500 0 0
[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;
[72]
[73]
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
[74]
[75]
[76]
[77]
[78]
[79]
[80]
[81]
[82]
[83]
[84]
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;
[85]
[86]
[87]
[88]
SREE VIDYANIKETHAN ENGINEERING COLLEGE DEPARTMENT OF IT SALES_ORDER Description: S_order_no primary key S_order_date Sell_price Order_status
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
[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);
[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;
[91]
[92]
[93]
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
[94]
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.
[95]
[96]
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 [email protected] 1 hod 45000 1000 1001 10 1543 hema giri 10-JUN-10 2 prof 25000 5000 1001 10 4341 sada siva 10-JUL-98 3 assprof 20000 4800 1001 10 5456 khaleel ali 08-AUG-87 2 prof 25000 5000 1003 30 7841 hari krishna 09-DEC-12 1 hod 40000 9000 1005 50 SALARY ---------8000 45000 25000 20000 25000 40000 10000 15000 13000 12000 7500
[97]
[98]
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);
[99]
[100]
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.
Null?
Type
[101]
[102]
[103]
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
[104]
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
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
[105]
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
[106]
[107]
[108]
[109]
[110]
[111]
[112]
[113]
[114]
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) -----------
[115]
[116]
[117]
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 [email protected] 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
[118]
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
[119]
Program 10
[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
[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,
[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));
[123]
[124]
[125]
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;
[126]
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 [email protected] 45000 1000 1001 10 23-NOV-09 1 hod JOB_ID
[127]
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 [email protected] 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
[128]
7 rows selected
[129]
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
Oracle Server
[130]
Application
Other DBMS
Application
DECLARE
BEGIN
Exception
Prepared by: Mr.O.Obulesu, Asst.professor
[131]
End;
Declaring Variables )
PL/SQL Block Structure DECLARE (Optional) Variables, cursors, user-defined exceptions BEGIN (Mandatory)
[132]
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;
Function function name return datatype is Begin ..statements Return value [Exception] End;
[133]
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
[134]
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
[135]
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;
[136]
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;
[137]
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
[138]
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)||
[139]
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;
[140]
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);
[141]
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
[142]
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;
[143]
[144]
SQL%ROWCOUNT Number of rows affected by the most recent SQL statement (an integer value) SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement affects oneor more rows SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement does not affect any rows SQL%ISOPEN Always evaluates to FALSE because 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.
[145]
IF Condition THEN actions (including further IF statements) ELSE actions (including further IF statements)
[146]
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-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;
[147]
[148]
[149]
.. 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
[150]
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.
[151]
[152]
Cursor
DECLARE
OPEN
Fetch
EM PT Y?
Close [153]
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.
[154]
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;
[155]
[156]
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:
[157]
Calling Environment t
Procedure
IN parameter OUT parameter IN OUT parameter (DECLARE) BEGIN EXCEPTION END;
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
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;
[158]
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
[159]
[160]
[161]
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
[162]
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;
[163]
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', '[email protected]', SYSDATE, 'SA_MAN', 1000); RETURN (p_sal + 100); END; /
[164]
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;
[165]
[166]
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.
[167]
[168]
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
[169]
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
[170]
[171]
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;
[172]
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:
[173]
[174]
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
[175]
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;
[176]
/*
INPUT / OUTPUT
[177]
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)
[178]
[179]
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;
[180]
[181]
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
[182]
[183]
[184]
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,
[185]
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
[186]
[187]
[188]
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
[189]
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;
[190]
[191]
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
[192]
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);
[193]
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, ...);
[194]
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
[195]
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)
[196]
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.
[197]
THANK YOU
Prepared by: Mr.O.Obulesu, Asst.professor
[198]
[199]