Guest User

Untitled

a guest
Jun 28th, 2017
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 76.43 KB | None | 0 0
  1. 1
  2. qwertyuiopasdfghjklzxcvbnmqwertyui
  3. opasdfghjklzxcvbnmqwertyuiopasdfgh
  4. jklzxcvbnmqwertyuiopasdfghjklzxcvb
  5. nmqwertyuiopasdfghjklzxcvbnmqwer
  6. tyuiopasdfghjklzxcvbnmqwertyuiopas
  7. dfghjklzxcvbnmqwertyuiopasdfghjklzx
  8. cvbnmqwertyuiopasdfghjklzxcvbnmq
  9. wertyuiopasdfghjklzxcvbnmqwertyuio
  10. pasdfghjklzxcvbnmqwertyuiopasdfghjk
  11. lzxcvbnmqwertyuiopasdfghjklzxcvbnm
  12. qwertyuiopasdfghjklzxcvbnmqwertyuio
  13. pasdfghjklzxcvbnmqwertyuiopasdfghj
  14. klzxcvbnmqwertyuiopasdfghjklzxcvbn
  15. mqwertyuiopasdfghjklzxcvbnmrtyuio
  16. pasdfghjklzxcvbnmqwertyuiopasdfghj
  17. klzxcvbnmqwertyuiopasdfghjklzxcvbn
  18. mqwertyuiopasdfghjklzxcvbnmqwerty
  19. Reference Manual
  20. for
  21. Database Systems Lab
  22. School of Computing Science and Engineering
  23. Vellore-632014,Tamil Nadu
  24. Database Systems Lab Manual
  25. CONTENTS
  26. SNo
  27. Topics
  28. Page Number
  29. 1.
  30. BASIC SQL COMMANDS
  31. 1
  32. 2.
  33. CONSTRAINTS
  34. 13
  35. 3.
  36. OPERATORS IN SQL*PLUS
  37. 18
  38. 4.
  39. FUNCTIONS:SINGLE ROW AND GROUP FUNCTIONS
  40. 23
  41. 5.
  42. JOINS
  43. 34
  44. 6.
  45. VIEWS
  46. 45
  47. 7.
  48. PL/SQL
  49. 50
  50. 8.
  51. PL/SQL BLOCK SYNTAX AND GUIDELINES
  52. 58
  53. 9
  54. CONTROL STRUCTURES IN PL/SQL
  55. 67
  56. 10
  57. CURSORS
  58. 73
  59. 11
  60. EXCEPTIONS
  61. 80
  62. 12
  63. PL/SQL BLOCK TYPES:Anonymous blocks and Subprograms
  64. 85
  65. 13
  66. PACKAGES
  67. 93
  68. 14
  69. TRIGGERS
  70. 98
  71. Database Systems Lab Manual
  72. SQL STATEMENTS
  73. SQL statements are classified as follows:
  74. Data Retrieval Statement:
  75. SELECT is the data extracting statement which retrieves the data from the database.
  76. Data Manipulation Language (DML):
  77. This language constitutes the statements that are used to manipulate with the data. It has three commands, which are INSERT, UPDATE and DELETE.
  78. Data Definition Language (DDL):
  79. This is the language used to define the structure of the tables. It sets up, changes, and removes data structures from the tables. It uses 5 commands, which are CREATE, ALTER, DROP, RENAME and TRUNCATE.
  80. Data Transaction Language (DTL):
  81. This is the language used to do undo and redo the transaction performed in the database. The commands are Commit, Rollback, and Save Point
  82. Data Control Language:
  83. This language is used to sanction the rights to the users to use the other user’s database objects. The commands are Grant and Revoke
  84. Consider the following schema based on which the example queries are discussed in this manual.
  85. BASE SCHEMA
  86. EMPLOYEE
  87. Name Type
  88. -------------------------- ----------------------
  89. EMPLOYEE_ID NUMBER(3)
  90. FIRST_NAME VARCHAR2(10)
  91. LAST_NAME VARCHAR2(10)
  92. MGR NUMBER(4)
  93. HIRE_DATE DATE
  94. JOB_ID VARCHAR2(10)
  95. SALARY NUMBER(10)
  96. Database Systems Lab Manual
  97. COMMISION NUMBER(8)
  98. DEPTNO NUMBER(2)
  99. DEPARTMENT
  100. Name Type
  101. --------------- -----------------
  102. DEPTNO NUMBER(2)
  103. DNAME VARCHAR2(14)
  104. LOC VARCHAR2(13)
  105. BONUS
  106. Name Type
  107. ---------------- -------------------
  108. ENAME VARCHAR2(10)
  109. JOB VARCHAR2(9)
  110. SAL NUMBER(10,2)
  111. COMM NUMBER(10)
  112. JOBGRADE
  113. Name Type
  114. ----------------- ---------------------
  115. JOB_ID VARCHAR2(10)
  116. GRADE NUMBER
  117. LOSAL NUMBER
  118. HISAL NUMBER
  119. DATA TYPES IN ORACLE:
  120. Data Type
  121. Description
  122. VARCHAR2(size)
  123. Variable-length character data
  124. CHAR(size)
  125. Fixed-length character data
  126. NUMBER(p,s)
  127. Variable-length numeric data
  128. DATE
  129. Date and time values
  130. LONG
  131. Variable-length character data up to 2 gigabytes
  132. CLOB
  133. Character data up to 4 gigabytes
  134. RAW and LONG RAW
  135. Raw binary data
  136. Database Systems Lab Manual
  137. BLOB
  138. Binary data up to 4 gigabytes
  139. BFILE
  140. Binary data stored in an external file; up to 4 gigabytes
  141. ROWID
  142. A 64 base number system representing the unique address of a row in its table
  143. ORACLE 9I TABLE STRUCTURES
  144.  Table can be created at any time
  145.  No need to specify the size of table, the size is ultimately defined by the amount of space allocated to the database as a whole.
  146.  Tables can have up to 1000 columns
  147. NAMING RULES
  148. Table names and Column names
  149.  Must begin with a letter
  150.  Must be 1-30 characters long
  151.  Must contain only A-Z,a-z,0-9,_,$,#
  152.  Must not duplicate the name of another object owned by the same user
  153.  Must not be a reserved word
  154. Data Definition Language (DDL)
  155. The following are the DDL Commands:
  156. 1. Create 2. Alter 3. Drop 4. Truncate 5. Rename
  157. 1. a. Creating a table
  158. Syntax:
  159. Create table <Table Name>
  160. ( <Field1> <Data Type> <(width) <constraints> ,
  161. <Field2> <Data Type> <(width)> <constraints>,
  162. ..................................);
  163. Database Systems Lab Manual
  164. Example:
  165. SQL> create table employee
  166. ( employee_id number(3),
  167. first_name varchar2(10),
  168. last_name varchar2(10),
  169. mgr number(4),
  170. hire_date date,
  171. job_id varchar2(10),
  172. salary number(10),
  173. commision number(8),
  174. deptno number(2));
  175. Output:
  176. Table created.
  177. Example:
  178. SQL> create table department
  179. (deptno number(2),
  180. dname varchar(14),
  181. loc varchar(13));
  182. Output:
  183. Table created.
  184. Note:
  185. Other tables can be created in the similar way.
  186. b. To view the Structure of the table, desc command is used
  187. Database Systems Lab Manual
  188. SQL> desc employee;
  189. Name Null? Type
  190. -------------------------------------- -------- ---------------
  191. EMPLOYEE_ID NUMBER(3)
  192. FIRST_NAME VARCHAR2(10)
  193. LAST_NAME VARCHAR2(10)
  194. MGR NUMBER(4)
  195. HIRE_DATE DATE
  196. JOB_ID VARCHAR2(10)
  197. SALARY NUMBER(10)
  198. COMMISION NUMBER(8)
  199. DEPTNO NUMBER(2)
  200. 2. Alter Table Statement:
  201. Alter command is used to perform the following action on the table:
  202. a. Adding column in the existing table
  203. b. Increasing and decreasing the column size and changing data types
  204. c. Dropping column
  205. d. Renaming the column
  206. e. Adding and dropping constraints to the table( discussed in constraints topics)
  207. f. Enabling & disabling constraints in the table( discussed in constraints topics)
  208. a. To Add a column to the table (structure)
  209. Add option is used to add a new column
  210. Syntax:
  211. Alter Table <Table-Name> Add <Field Name> <Type> (width);
  212. Example:
  213. SQL> alter table employee add address varchar2 (20);
  214. Output:
  215. Table altered.
  216. b. To Modify a field of the table
  217.  Increase the width or precision of numeric column
  218. Database Systems Lab Manual
  219.  Increase the width of numeric or character columns
  220.  Decrease the width of the column only if the column contains only null values or if the table has no rows
  221.  Change the data type only if the column contains null values
  222. Syntax:
  223. Alter Table <tablename> MODIFY ( <column name > < newdatatype>);
  224. Example:
  225. SQL> alter table employee modify address varchar2 (10);
  226. Output:
  227. Table altered.
  228. c. To Drop a field of the table
  229. Drop option is used to delete a column or remove a constraint
  230. Syntax:
  231. Alter Table <tablename> DROP COLUMN < column name>;
  232. Example:
  233. SQL> alter table employee drop column address;
  234. Output:
  235. Table altered.
  236. d.To rename a column
  237. Syntax:
  238. ALTER TABLE <tablename> RENAME COLUMN <oldcolumnname> TO
  239. <newcolumn name>
  240. Example:
  241. SQL> alter table employee rename column mgr to manager;
  242. Output:
  243. Table altered.
  244.  To Drop a table - Deletes a Table along with all contents
  245. Syntax:
  246. Drop Table <Table-Name>;
  247. Database Systems Lab Manual
  248. Example:
  249. Drop Table Student_table;
  250. Output:
  251. Table Dropped
  252.  To Truncate a table - Deletes all rows from a table ,retaining its structure
  253. Syntax: Truncate Table <tablename>
  254. Example:
  255. SQL> truncate table employee;
  256. Output:
  257. Table truncated.
  258. g. To rename a table- Renames a table with new name
  259. Syntax:
  260. Rename <oldtablename> To <newtablename>
  261. Example:
  262. SQL> rename employee to emp;
  263. Output:
  264. Table renamed
  265. Data manipulation Language (DML)
  266. The following are the DML Commands: 1. Insert 2. Delete 3. Update 4. Select
  267. Insert command is used to load data into the table.
  268. a. Inserting values from user
  269. Syntax:
  270. Insert into <tablename> values ( val1,val2 …);
  271. Example:
  272. SQL> insert into department values(10,'accounts','chennai');
  273. Output:
  274. 1 row created.
  275. Database Systems Lab Manual
  276. b. Inserting values for the specific columns in the table
  277. Syntax:
  278. Insert Into <Table-Name> (Fieldname1, Fieldname2, Fieldname3,..) Values (value1, value2, value3,..);
  279. Example:
  280. SQL> insert into department (deptno,dname)values(20,'finance');
  281. Output:
  282. 1 row created.
  283. c. Inserting interactively(Inserting ,ultiple rows by using single insert command)
  284. Syntax:
  285. Insert Into <tablename> Values( &<column name1> , &<column name2> …);
  286. Example:
  287. SQL> insert into employee values(&empid,'&fn','&ln',&mgr,'&hdate','&job',&sal,
  288. &comm,&dept);
  289. Enter value for empid: 111
  290. Enter value for fn: Smith
  291. Enter value for ln: Ford
  292. Enter value for mgr: 222
  293. Enter value for hdate: 21-jul-2010
  294. Enter value for job: J1
  295. Enter value for sal: 30000
  296. Enter value for comm: 0.1
  297. Enter value for dept: 10
  298. old 2: &comm,&dept)
  299. new 2: 0.1,10)
  300. Output:
  301. 1 row created.
  302. Note: Column names of character and date type should be included with in single quotation.
  303.  Inserting null values
  304. Database Systems Lab Manual
  305. Syntax:
  306. Insert Into <tablename> Values ( val1,’ ‘,’ ‘,val4);
  307. Example:
  308. insert into department values( ‘101’,’’,chennai);
  309. Output:
  310. 1 row created.
  311. 2. To Delete rows from a table
  312. Syntax:
  313. Delete from <table name> [where <condition>];
  314. Example:
  315. a) to delete all rows:
  316. SQL> delete from department;
  317. Output:
  318. 89 rows deleted.
  319. b) conditional deletion:
  320. SQL> delete from department where loc='chennai';
  321. Output:
  322. 1 row deleted.
  323. 3. Modifying (Updating) Records:
  324. a. Updating single column
  325. Syntax:
  326. UPDATE <table name> Set <Field Name> = <Value> Where <Condition>;
  327. Example:
  328. SQL> update department set loc='Hyderabad' where deptno=20;
  329. Output:
  330. 1 row updated.
  331. Note: Without where clause all the rows will get updated.
  332. b. Updating multiple column [while updating more than one column, the column must be separated by comma operator]
  333. Database Systems Lab Manual
  334. Example: SQL> update department set loc='Hyderabad', dname= ‘cse’ where deptno=20;
  335. Output:
  336. 1 row updated.
  337. 4. Selection of Records [Retrieving (Displaying) Data:]
  338. Syntax:
  339. Select <field1, field2 …fieldn> from <table name> where <condition>;
  340. Example:
  341. a) SQL> select * from department;
  342. Output:
  343. DEPTNO DNAME LOC
  344. ---------- -------------- -------------
  345. 10 accounts chennai
  346. 20 finance Hyderabad
  347. 30 IT Bangalore
  348. 40 marketing chennai
  349. Example:
  350. b) SQL> select dname, loc from department;
  351. Output:
  352. DNAME LOC
  353. -------------- -------------
  354. accounts chennai
  355. finance Hyderabad
  356. IT Bangalore
  357. marketing Chennai
  358.  Using Alias name for a field
  359. Syntax:
  360. Select <col1> <alias name 1> , <col2> < alias name 2> from < tab1>;
  361. Example:
  362. SQL> select dname, loc as location from department;
  363. Output:
  364. DNAME LOCATION
  365. -------------- -------------
  366. accounts chennai
  367. Database Systems Lab Manual
  368. finance Hyderabad
  369. IT Bangalore
  370. marketing Chennai
  371.  With distinct clause [Used to retrieve unique value from the column]
  372. Syntax:
  373. Select distinct <col2> from < tab1>;
  374. Example:
  375. SQL> select distinct loc from department;
  376. Output:
  377. LOC
  378. -------------
  379. chennai
  380. Bangalore
  381. Hyderabad
  382.  Creating Table using subquery
  383. Syntax:
  384. Create table <new _table_name> as Select <column names> from <old_table_name>;
  385. Example:
  386. SQL> create table copyOfEmp as select * from employee;
  387. Output:
  388. Table created.
  389.  To view the contents of new Table
  390. SQL> select * from copyofemp;
  391. Output:
  392. EMPLOYEE_ID FIRST_NAME LAST_NAME MANAGER HIRE_DATE JOB_ID SALARY COMMISION DEPTNO
  393. 111 Smith Ford 222 21-JUL-10 J1 30000 0.1 1 0
  394.  To create a table with same structure as an existing table
  395. Syntax:
  396. Database Systems Lab Manual
  397. Create table <new _table_name> as Select <column names> from<old_table_name>
  398. where 1=2;
  399. Example:
  400. create table copyOfEmp2 as select * from employee where 1=2;
  401. Output: Table created.
  402. SQL> select * from copyofemp2;
  403. Output:
  404. no rows selected
  405. SQL> desc copyofemp2;
  406. Output:
  407. Name Null? Type
  408. ----------------------------------------- -------- -----------------
  409. EMPLOYEE_ID NUMBER(3)
  410. FIRST_NAME VARCHAR2(10)
  411. LAST_NAME VARCHAR2(10)
  412. MANAGER NUMBER(4)
  413. HIRE_DATE DATE
  414. JOB_ID VARCHAR2(10)
  415. SALARY NUMBER(10)
  416. COMMISION NUMBER(8)
  417. DEPTNO NUMBER(2)
  418. Note: Only structure of table alone is copied and not the contents.
  419.  Inserting into table using a subquery
  420. Syntax :
  421. Insert into <new_table_name> (Select <columnnames> from <old_table_name>);
  422. Example:
  423. SQL> insert into copyofemp2 (select * from employee where employee_id > 100);
  424. Output:
  425. 50 rows created.
  426. Database Systems Lab Manual
  427. Constraints
  428.  Constraints enforce rules on the table whenever rows are inserted, updated and deleted from the table.
  429.  Prevents the deletion of a table if there are dependencies from other tables.
  430.  Name a constraints or the oracle server generate name by using SYS_cn format.
  431.  Define the constraints at column or table level. constraints can be applied while creation of table or after the table creation by using alter command.
  432.  View the created constraints from User_Constraints data dictionary.
  433. Constraints Types
  434. CONSTRAINT
  435. DESCRIPTION
  436. NOT NULL
  437. Specifies that a column must have some value.
  438. UNIQUE
  439. Specifies that columns must have unique values.
  440. PRIMARY KEY
  441. Specifies a column or a set of columns that uniquely identifies as row. It does not allow null values.
  442. FOREIGN KEY
  443. Foreign key is a column(s) that references a column(s) of a table.
  444. CHECK
  445. Specifies a condition that must be satisfied by all the rows in a table.
  446. Database Systems Lab Manual
  447. 1. Creating Constraints without constraint name
  448. Syntax:
  449. CREATE TABLE < tablename> (
  450. <column name 1> < datatype>,
  451. <column name 2> < datatype> UNIQUE ,
  452. <column name 3> < datatype> ,
  453. PRIMARY KEY ( <column name2>)
  454. );
  455. Example:
  456. CREATE TABLE emp_demo2
  457. ( employee_id NUMBER(6) PRIMARY KEY,
  458. first_name VARCHAR2(20) NOT NULL,
  459. last_name VARCHAR2(25) NOT NULL,
  460. email VARCHAR2(25) UNIQUE,
  461. phone_number VARCHAR2(20) UNIQUE,
  462. job_id VARCHAR2(10),
  463. salary NUMBER(8,2) CHECK(SALARY>0),
  464. deptid NUMBER(4)
  465. ) ;
  466. 2. Creating constraints with constraint name
  467. Syntax:
  468. CREATE TABLE < tablename1> (
  469. <column name 1> < datatype> CONSTRAINT <constraint name1> UNIQUE,
  470. <column name 2> < datatype> CONSTRAINT <constraint name2> NOT NULL,
  471. constraint < constraint name3 > PRIMARY KEY ( <column name1>),
  472. Database Systems Lab Manual
  473. constraint <constraint name4> FOREIGN KEY (<column name2>) REFERENCES <tablename2> (<column name1>)
  474. );
  475. Example:
  476. CREATE TABLE emp_demo3
  477. ( employee_id NUMBER(6) CONSTRAINT emp_eid PRIMARY KEY,
  478. first_name VARCHAR2(20),
  479. last_name VARCHAR2(25) CONSTRAINT emp_last_name_nn NOT NULL,
  480. email VARCHAR2(25) CONSTRAINT emp_email_nn NOT NULL,
  481. phone_number VARCHAR2(20),
  482. job_id VARCHAR2(10) CONSTRAINT emp_job_nn NOT NULL,
  483. salary NUMBER(8,2) CONSTRAINT emp_salary_nn NOT NULL,
  484. deptid NUMBER(4), CONSTRAINT emp_dept FOREIGN KEY(deptid)
  485. REFERENCES department(deptid) ,
  486. CONSTRAINT emp_salary_min CHECK (salary > 0) ,
  487. CONSTRAINT emp_email_uk UNIQUE (email)
  488. ) ;
  489. 3. With check constraint
  490. Syntax:
  491. CREATE TABLE < tablename> (
  492. <column name1 > < datatype> ,
  493. <column name 2> < datatype>,
  494. CHECK ( < column name 1 > in ( values) )
  495. CHECK ( < column name 2 > between <val1> and <val2> ) );
  496. Example:
  497. CREATE TABLE emp_demo4
  498. Database Systems Lab Manual
  499. ( emp_id NUMBER(6),
  500. emp_name VARCHAR2(15),
  501. salary NUMBER(10) CHECK (salary between 1000 and 10000)
  502. );
  503. Adding Constriants
  504. Constraints can be added after the table creation by using alter command
  505. Syntax: Add constraints
  506. ALTER TABLE <tablename> ADD CONSTRAINT <constraint_name> constriant_type (<column name>);
  507. Examples:
  508. ALTER TABLE emp_demo4 ADD CONSTRAINT con_pk1 PRIMARY KEY(emp_id);
  509. ALTER TABLE emp_demo4 ADD CONSTRAINT con_emp_uk UNIQUE(phoneno);
  510. ALTER TABLE emp_demo4 ADD CONSTRAINT con_empfk FOREIGN KEY(DNO) REFERENCES department(dno);
  511. ALTER TABLE emp_demo4 ADD CONSTRAINT con_emp_ck CHECK ( salary >0 );
  512. ALTER TABLE emp_demo4 MODIFY (<Column name> <datatype> CONSTRAINT constraint_name NOT NULL);
  513. Drop Constraints
  514. Syntax
  515. ALTER TABLE <tablename> DROP CONSTRAINT < constraint name >;
  516. Drop the unique key on the email column of the employees table:
  517. e.g ALTER TABLE employees DROP UNIQUE (email);
  518. CASCADE Constraints
  519. The CASCADE Constraints clause is used along with the Drop Column Clause.
  520. Database Systems Lab Manual
  521. • A foreign key with a cascade delete means that if a record in the parent table is deleted,
  522. then the corresponding records in the child table will automatically be deleted. This is
  523. called a cascade delete.
  524. • A foreign key with a cascade delete can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.
  525. Syntax:
  526. CREATE TABLE table_name
  527. (column1 datatype null/not null,
  528. column2 datatype null/not null,
  529. ...
  530. CONSTRAINT fk_column
  531. FOREIGN KEY (column1, column2, ... column_n)
  532. REFERENCES parent_table (column1, column2, ... column_n)
  533. ON DELETE CASCADE
  534. );
  535. Example:
  536. CREATE TABLE supplier
  537. (supplier_id number(10)not null,
  538. supplier_namevarchar2(50)not null,
  539. contact_namevarchar2(50),
  540. CONSTRAINT supplier_pk PRIMARY KEY (supplier_id));
  541. CREATE TABLE products
  542. (product_id number(10)not null,
  543. suppl_id number(10) not null,
  544. CONSTRAINT fk_supplier FOREIGN KEY (suppl_id) REFERENCES
  545. supplier(supplier_id) ON DELETE CASCADE);
  546. Database Systems Lab Manual
  547. Because of the cascade delete, when a record with a particular supplier_ id is deleted from supplier table , then all the records of the same supplier_id will be deleted from products table also.
  548. Operators in SQL*PLUS
  549. Type
  550. Symbol / Keyword
  551. Where to use
  552. Arithmetic
  553. + , - , * , /
  554. To manipulate numerical column values, WHERE clause
  555. Comparison
  556. =, !=, <, <=, >, >=, between, not between, in, not in, like, not like
  557. WHERE clause
  558. Logical
  559. and, or, not
  560. WHERE clause, Combining two queries
  561.  Between..And..
  562. Example:
  563. SQL> select first_name, deptno from employee where salary between 20000 and 35000;
  564. Output:
  565. FIRST_NAME DEPTNO
  566. ---------- ----------
  567. Smith 10
  568.  IN
  569. Example:
  570. SQL> select first_name, deptno from employee where job_id in ('J1','J2');
  571. Output:
  572. FIRST_NAME DEPTNO
  573. ---------- ----------
  574. Smith 10
  575. Database Systems Lab Manual
  576. Arun 30
  577. Nithya 10
  578.  NOT IN
  579. Example:
  580. SQL> select dname,loc from department where loc not in ('chennai','Bangalore');
  581. Output:
  582. DNAME LOC
  583. -------------- -------------
  584. finance Hyderabad
  585.  Like
  586. Use the LIKE condition to perform wild card searches of valid search string values.
  587. Search conditions can contain either characters or numbers
  588. % - denotes zero or many characters.
  589. _ - denotes one character.
  590. Example:
  591. SQL> select dname,loc from department where loc like 'c%';
  592. Output:
  593. DNAME LOC
  594. -------------- -------------
  595. accounts chennai
  596. marketing Chennai
  597. Example:
  598. SQL> select dname,loc from department where loc like 'chen_ _ _';
  599. Output:
  600. DNAME LOC
  601. -------------- -------------
  602. accounts chennai
  603. marketing Chennai
  604. Example:
  605. SQL> select dname,loc from department where loc not like 'c%';
  606. Database Systems Lab Manual
  607. Output:
  608. DNAME LOC
  609. -------------- -------------
  610. finance Hyderabad
  611. IT Bangalore
  612.  Between..and..
  613. Example:
  614. SQL> select first_name, deptno, salary from employee where salary not between 20000 and 35000;
  615. Output:
  616. FIRST_NAME DEPTNO SALARY
  617. ---------- ---------- ----------
  618. Arun 30 40000
  619. Nithya 10 45000
  620. Note: Inserting null value into location column of department table
  621. Example:
  622. SQL> insert into department(deptno,dname) values(40,'Sales');
  623. Output:
  624. 1 row created.
  625.  is Null
  626. Example:
  627. SQL> select * from department where loc is null;
  628. Output:
  629. DEPTNO DNAME LOC
  630. ---------- -------------- -------------
  631. 40 Sales
  632. Example:
  633. SQL> select * from department where loc is not null;
  634. Output:
  635. DEPTNO DNAME LOC
  636. Database Systems Lab Manual
  637. ---------- -------------- -------------
  638. 10 accounts chennai
  639. 20 finance Hyderabad
  640. 30 IT Bangalore
  641. 40 marketing chennai
  642. LOGICAL OPERATORS: Used to combine the results of two or more conditions to produce a single result. The logical operators are: OR, AND, NOT.
  643. Operator Precedence
  644.  Arithmetic operators-Highest precedence
  645.  Comparison operators
  646.  NOT operator
  647.  AND operator
  648.  OR operator----Lowest precedence
  649. The order of precedence can be altered using parenthesis.
  650. Example:
  651. SQL> select first_name, deptno, salary from employee where salary > 20000 ;
  652. Output:
  653. FIRST_NAME DEPTNO SALARY
  654. ---------- ---------- ----------
  655. Smith 10 30000
  656. Arun 30 40000
  657. Nithya 10 45000
  658. Example:
  659. SQL> select first_name, deptno, salary from employee
  660. where salary > 20000 and salary < 35000;
  661. Output:
  662. Database Systems Lab Manual
  663. FIRST_NAME DEPTNO SALARY
  664. ---------- ---------- ----------
  665. Smith 10 30000
  666. Example:
  667. SQL> select first_name, deptno, salary+100 from employee where salary > 35000;
  668. Output:
  669. FIRST_NAME DEPTNO SALARY+100
  670. ---------- ---------- ----------
  671. Arun 30 40100
  672. Example:
  673. SQL> update employee set salary = salary+salary*0.1 where employee_id = 111;
  674. Output:
  675. 1 row updated.
  676. Example:
  677. SQL> select * from department where loc = 'chennai' or dname='IT';
  678. Output:
  679. DEPTNO DNAME LOC
  680. ---------- -------------- -------------
  681. 10 accounts chennai
  682. 30 IT Bangalore
  683. 40 marketing chennai
  684. FUNCTIONS
  685.  Single Row Functions
  686.  Group functions
  687. Single Row Functions
  688. Returns only one value for every row can be used in SELECT command and included in WHERE clause
  689. Types
  690.  Character functions
  691. Database Systems Lab Manual
  692.  Numeric functions
  693.  Date functions
  694. CHARACTER FUNCTIONS:
  695. Character functions accept a character input and return either character or number values. Some of them supported by Oracle are listed below
  696. Syntax
  697. Description
  698. initcap (char)
  699. Changes first letter to capital
  700. lower (char)
  701. Changes to lower case
  702. upper (char)
  703. Changes to upper case
  704. ltrim ( char, set)
  705. Removes the set from left of char
  706. rtrim (char, set)
  707. Removes the set from right of char
  708. translate(char, from, to)
  709. Translate ‘from’ anywhere in char to ‘to’
  710. replace(char, search string, replace string)
  711. Replaces the search string to new
  712. substr(char, m , n)
  713. Returns chars from m to n length
  714. lpad(char, length, special char)
  715. Pads special char to left of char to Max of length
  716. rpad(char, length, special char)
  717. Pads special char to right of char to Max of length
  718. chr(number)
  719. Returns char equivalent
  720. length(char)
  721. Length of string
  722. Examples:
  723. Function
  724. Input
  725. Output
  726. Initcap(char)
  727. SQL>select initcap(‘hello’) from dual;
  728. Hello
  729. Lower(char)
  730. SQL>select lower(‘FUN’) from dual;
  731. fun
  732. Database Systems Lab Manual
  733. Upper(char)
  734. SQL>select upper(‘sun’) from dual;
  735. SUN
  736. Ltrim(char, set)
  737. SQL>select ltrim(‘xyzhello’,’xyz’) from dual;
  738. hello
  739. Rtrim(char, set)
  740. SQL>select rtrim(‘xyzhello’,’llo’) from dual;
  741. xyzhe
  742. translate(char,from,to)
  743. SQL>select translate(‘jack’,’j’,’b’) from dual;
  744. back
  745. Replace(char,from,to)
  746. SQL>select replace(‘jack and jue’,’ j’, ’bl’) from dual;
  747. black and blue
  748. Example:
  749. SQL> select initcap(dname) from department;
  750. Output:
  751. INITCAP(DNAME)
  752. --------------
  753. Accounts
  754. Finance
  755. It
  756. Marketing
  757. Sales
  758. Lpad is a function that takes three arguments. The first argument is the character string which has to be displayed with the left padding. The second is the number which indicates the total length of the return value, the third is the string with which the left padding has to be done when required.
  759. Example:
  760. SQL> select lpad(dname,15,'*') lpd from department;
  761. Output:
  762. LPD
  763. ---------------
  764. *******accounts
  765. ********finance
  766. *************IT
  767. ******marketing
  768. **********Sales
  769. Example:
  770. SQL> select rpad(dname,15,'*') rpd from department;
  771. Output:
  772. Database Systems Lab Manual
  773. RPD
  774. ---------------
  775. accounts*******
  776. finance********
  777. IT*************
  778. marketing******
  779. Sales**********
  780. Length: returns the length of a string
  781. Example:
  782. SQL> select dname, length(dname) from department;
  783. Output:
  784. DNAME LENGTH(DNAME)
  785. -------------- -------------
  786. accounts 8
  787. finance 7
  788. IT 2
  789. marketing 9
  790. Sales 5
  791. Concatenation operator ||: is used to merge or more strings.
  792. Example:
  793. SQL> select dname || ' is located in ' || loc from department;
  794. Output:
  795. DNAME||'ISLOCATEDIN'||LOC
  796. ------------------------------------------
  797. accounts is located in chennai
  798. finance is located in Hyderabad
  799. IT is located in Bangalore
  800. marketing is located in chennai
  801. Sales is located in
  802. NUMERIC FUNCTIONS:
  803. Numeric functions accept numeric input and returns numeric values as output.
  804. Database Systems Lab Manual
  805. Syntax
  806. Description
  807. abs ( )
  808. Returns the absolute value
  809. ceil ( )
  810. Rounds the argument
  811. cos ( )
  812. Cosine value of argument
  813. exp ( )
  814. Exponent value
  815. floor( )
  816. Truncated value
  817. power (m,n)
  818. N raised to m
  819. mod (m,n)
  820. Remainder of m / n
  821. round (m,n)
  822. Rounds m’s decimal places to n
  823. trunc (m,n)
  824. Truncates m’s decimal places to n
  825. sqrt (m)
  826. Square root value
  827. Examples:
  828. Function
  829. Input
  830. Output
  831. Abs( n)
  832. SQL>select abs(-15) from dual
  833. 15
  834. Ceil(n)
  835. SQL>select ceil(48.778) from dual;
  836. 49
  837. Cos(n)
  838. SQL>select cos(180) from dual;
  839. -0.59884601
  840. Cosh(n):
  841. SQL>select cosh(0) from dual;
  842. 1
  843. Exp(n)
  844. SQL>select exp(4) from dual;
  845. 54.59815
  846. Floor(n)
  847. SQL>select floor(4.678) from dual;
  848. 4
  849. Power(m ,n)
  850. SQL>select power(5,2) from dual;
  851. 25
  852. Mod(m ,n)
  853. SQL>select mod(11,2) from dual;
  854. 1
  855. Round(m ,n)
  856. SQL>select round(112.257,2) from dual;
  857. 112.26
  858. Example:
  859. SQL> select ln (2) from dual; (returns natural logarithm value of 2)
  860. Database Systems Lab Manual
  861. SQL>select sign (-35) from dual; (output is -1)
  862. CONVERSION FUNCTIONS: Convert a value from one data type to another.
  863.  To_char ( )
  864. To_ char (d [,fmt]) where d is the date fmt is the format model which specifies the format of the date. This function converts date to a value of varchar2datatype in a form specified by date format fmt.if fmt is neglected then it converts date to varchar2 in the default date format.
  865. Example:
  866. SQL> select to_char (hire_date, 'ddth "of" fmmonth yyyy') from employee;
  867. Output:
  868. TO_CHAR(HIRE_DATE,'DDT
  869. ----------------------
  870. 21st of july 2010
  871. 05th of june 2008
  872. 12th of february 1999
  873.  To_ date ( )
  874. The format is to_date (char [, fmt]). This converts char or varchar data type to date data type. Format model, fmt specifies the form of character.
  875. Example:
  876. SQL>select to_date (‘December 18 2007’,’month-dd-yyyy’) from dual;
  877. Output:
  878. 18-DEC-07 is the output.
  879. Example:
  880. SQL> select round(hire_date,'year') from employee;
  881. Output:
  882. ROUND(HIR
  883. ---------
  884. 01-JAN-11
  885. 01-JAN-08
  886. 01-JAN-99
  887.  To_ Number( )
  888. Database Systems Lab Manual
  889. Allows the conversion of string containing numbers into the number data type on which arithmetic operations can be performed.
  890. Example: SQL> select to_number (‘100’) from dual;
  891. DATE FUNCTIONS
  892. Example:
  893. SQL> select sysdate from dual;
  894. Output:
  895. SYSDATE
  896. ---------
  897. 22-JUL-10
  898. Example:
  899. SQL> select hire_date from employee;
  900. Output:HIRE_DATE
  901. ---------
  902. 21-JUL-10
  903. 05-JUN-08
  904. Function Name
  905. Return Value
  906. ADD_MONTHS (date, n)
  907. Returns a date value after adding ’n’months to the date ’x’.
  908. MONTHS_BETWEEN (x1, x2)
  909. Returns the number of months between dates x1 and x2.
  910. ROUND (x, date_format)
  911. Returns the date ‘x’rounded off to the nearest century, year, month, date, hour, minute, or second as specified by the ‘date_format’.
  912. TRUNC (x, date_format)
  913. Returns the date ‘x’ lesser than or equal to the nearest century, year, month, date, hour, minute, or second as specified by the ‘date_format’.
  914. NEXT_DAY (x, week_day)
  915. Returns the next date of the ‘week_day’on or after the date ‘x’ occurs.
  916. LAST_DAY (x)
  917. It is used to determine the number of days remaining in a month from the date 'x'specified.
  918. SYSDATE
  919. Returns the systems current date and time.
  920. Database Systems Lab Manual
  921. 12-FEB-99
  922. Example:
  923. SQL> select add_months(hire_date,3) from employee;
  924. Output:
  925. ADD_MONTH
  926. ---------
  927. 21-OCT-10
  928. 05-SEP-08
  929. 12-MAY-99
  930. Example:
  931. SQL> select months_between(sysdate,hire_date) from employee;
  932. Output:
  933. MONTHS_BETWEEN(SYSDATE,HIRE_DATE)
  934. ---------------------------------
  935. .047992085
  936. 25.5641211
  937. 137.338315
  938. Example:
  939. SQL> select next_day(hire_date,'wednesday') from employee;
  940. Output:
  941. NEXT_DAY(
  942. ---------
  943. 28-JUL-10
  944. 11-JUN-08
  945. 17-FEB-99
  946. Example:
  947. SQL> select last_day(hire_date) from employee;
  948. Output:
  949. LAST_DAY(
  950. ---------
  951. 31-JUL-10
  952. 30-JUN-08
  953. 28-FEB-99
  954. Database Systems Lab Manual
  955. Group Functions: - Group functions are built-in SQL functions that operate on groups of rows and return one value for the entire group. These functions are: COUNT, MAX, MIN, AVG, SUM, DISTINCT
  956.  Group functions operate on sets of rows to give one result per group of Employees
  957. Dept_id
  958. Salary
  959. 90
  960. 5000
  961. 90
  962. 10000
  963. 90
  964. 10000
  965. 60
  966. 5000
  967. 60
  968. 5000
  969. Types of Group Functions
  970. Syntax
  971. Description
  972. count (*),
  973. count (column name),
  974. count (distinct column name)
  975. Returns number of rows
  976. min (column name)
  977. Min value in the column
  978. max (column name)
  979. Max value in the column
  980. avg (column name)
  981. Avg value in the column
  982. sum (column name)
  983. Sum of column values
  984. The maximum salary in the employees table
  985. Max (salary) 10000
  986. Database Systems Lab Manual
  987. Group Functions Syntax:
  988. Select [column,] group_function(column),..
  989. From table
  990. [where condition]
  991. [GROUP BY column];
  992. Example:
  993. Q.Display the average,highest, lowest and sum of salaries for all the sales representatives.
  994. A. Select avg(salary), max(salary), min(salary), sum(salary) From employees where job_id like ‘%rep%’;
  995. Groups of Data : Divide rows in a table in to smaller groups by using the group by clause
  996. Employee Table
  997. Dept_id
  998. Salary
  999. 10
  1000. 4000
  1001. 10
  1002. 5000
  1003. 10
  1004. 6000
  1005. 50
  1006. 5000
  1007. 50
  1008. 3000
  1009. SET OPERATORS: UNION,UNION ALL,DIFFERENCE,MINUS
  1010. Example:
  1011. sql> select first_name from employees union select name from sample ;
  1012. Output:
  1013. FIRST_NAME
  1014. ----------
  1015. DHANA
  1016. GUNA
  1017. D_id
  1018. Avg(Salary)
  1019. 10
  1020. 5000
  1021. 50
  1022. 4000
  1023. The average salary in employees table for each department
  1024. Database Systems Lab Manual
  1025. JAI
  1026. JAISANKAR
  1027. KUMAR
  1028. RAJA
  1029. VENKAT
  1030. Example:
  1031. sql> select first_name from employees union all select name from sample ;
  1032. Output:
  1033. FIRST_NAME
  1034. ----------
  1035. VENKAT
  1036. JAI
  1037. DHANA
  1038. GUNA
  1039. JAISANKAR
  1040. VENKAT
  1041. RAJA
  1042. KUMAR
  1043. Example:
  1044. sql> select first_name from employees intersect select name from sample ;
  1045. Output:
  1046. FIRST_NAME
  1047. ----------
  1048. VENKAT
  1049. Example:
  1050. sql> select first_name from employees minus select name from sample ;
  1051. Output:
  1052. FIRST_NAME
  1053. ----------
  1054. DHANA
  1055. GUNA
  1056. JAI
  1057. Database Systems Lab Manual
  1058.  JOINS :A join is the SQL way of combining the data from many tables. It is performed by WHERE Clause which combines the specified rows of the tables.
  1059. Type
  1060. Sub type
  1061. Description
  1062. Simple join
  1063. Equi join ( = )
  1064. Non – equi join (<, <=, >, >=, !=, < > )
  1065. Joins rows using equal value of the column
  1066. Joins rows using other relational operators(except = )
  1067. Self join
  1068. -- ( any relational operators)
  1069. Joins rows of same table
  1070. Outer join
  1071. Left outer join ((+) appended to left operand in join condition)
  1072. Right outer join ((+) appended to right operand in join condition)
  1073. Rows common in both tables and uncommon rows have null value in left column
  1074. Vice versa
  1075. Simple Join:
  1076. a. EQUI JOIN OR INNER JOIN : A column (or multiple columns) in two or more tables match.
  1077. Syntax:
  1078. SELECT <column_name(s)> FROM <table_name1> INNER JOIN <table_name2> ON <table_name1.column_name>=<table_name2.column_name>;
  1079. Example 1 :
  1080. SELECT employee.first_name, department.dname FROM employee INNER JOIN department
  1081. Database Systems Lab Manual
  1082. ON employee.deptno = department.deptno; Output:1
  1083. DEPTNO FIRST_NAME
  1084. ---------- ----------
  1085. 10 Smith
  1086. 30 Arun
  1087. 10 Nithya
  1088. Oracle automatically defaults the JOIN to INNER so that the INNER keyword is not required. They are the same query, though. It is preferred not to type the INNER keyword. Example 2 using where Condition:
  1089. SELECT employee.ename, department.dname FROM employee JOIN department ON employee.deptno = department.deptno WHERE department.dname = 'SALES'; Output 2:
  1090. DEPTNO FIRST_NAME
  1091. ---------- ----------
  1092. 10 Smith
  1093. 30 Arun
  1094. 10 Nithya
  1095. b. SELF JOIN: Is a join where a table is joined to itself.
  1096. Syntax:
  1097. SELECT <column_name(s)> FROM <table_name1> JOIN <table_name2> ON <table_name1.column_name>=<table_name1.column_name>;
  1098. Example1:
  1099. SELECT e1.first_name, e2.first_name
  1100. Database Systems Lab Manual
  1101. FROM employee e1 join employee e2
  1102. on e1.mgr = e2.employee_id;
  1103. OR
  1104. SELECT e1.first_name, e2.first_name
  1105. FROM employee e1 join employee e2
  1106. where e1.mgr = e2.employee_id;
  1107. Output:
  1108. FIRST_NAME FIRST_NAME
  1109. ---------------- --------------------
  1110. john john
  1111. An alias is just a way to refer to a column or table with a UNIQUE name. If we try to call both of the instances of the table EMP, Oracle wouldn't know which table instance we refer to. Using an alias clears this confusion
  1112. c. OUTER JOIN
  1113. An outer join tells Oracle to return the rows on the left or right (of the JOIN clause) even if there are no rows. The LEFT OUTER keyword to the JOIN clause says, return the rows to the left (in this case DEPARTMENT) even if there are no rows on the right (in this case employee). Syntax:
  1114. SELECT <column_name(s)> FROM <table_name1> LEFT OUTER JOIN <table_name2> ON <table_name1.column_name>=<table_name2.column_name>;
  1115. Example:
  1116. SELECT department.dname, employee.first_name
  1117. FROM department LEFT OUTER JOIN employee ON department.deptno = employee.deptno WHERE department.dname = 'marketing’;
  1118. Database Systems Lab Manual
  1119. Output:
  1120. DNAME FIRST_NAME
  1121. -------------- ----------
  1122. Marketing
  1123. The RIGHT OUTER keyword to the JOIN clause says ,return the rows to the right relation (in this case DEPARTMENT) even if there are no matching rows on the left relation (in this case employee). Syntax:
  1124. SELECT <column_name(s)> FROM <table_name1> RIGHT OUTER JOIN <table_name2> ON <table_name1.column_name>=<table_name2.column_name>;
  1125. Example:
  1126. SELECT employee.first_name, department.dname FROM employee RIGHT OUTER JOIN department ON employee.deptno = department.deptno WHERE department.dname = 'marketing';
  1127. Output:
  1128. FIRST_NAME DNAME
  1129. ---------- --------------
  1130. marketing
  1131. d. FULL OUTER JOIN
  1132. Let's insert a new record into the employee table:
  1133. INSERT INTO EMPLOYEE (employee_id, first_name, last_name, mgr, hiredate, job-id,sal, comm, deptno) VALUES (9999, 'Joe ‘,’Blow', 7698, sysdate ,0008, 10500, 0, NULL ); Note:
  1134. We inserted an employee record that has no department. How can we get the records for
  1135. Database Systems Lab Manual
  1136. all employees AND all departments? We would use the FULL OUTER join syntax: Syntax:
  1137. SELECT <column_name(s)> FROM <table_name1> FULL OUTER JOIN <table_name2> ON <table_name1.column_name>=<table_name2.column_name>;
  1138. Example:
  1139. SELECT employee.first_name, department.dname FROM employee FULL OUTER JOIN department ON employee.deptno = department.deptno; Output:
  1140. FIRST_NAME DNAME
  1141. ---------- --------------
  1142. Nithya accounts
  1143. Smith accounts
  1144. finance
  1145. john IT
  1146. Arun IT
  1147. marketing
  1148. john
  1149. e.Cross Join
  1150. Displays all the rows and all the colums of both the tables.
  1151. Synatx:
  1152. SELECT <column_name(s)> FROM <table_name1> CROSS JOIN<table_name2>;
  1153. Example:
  1154. select employee.deptno from employee cross join department;
  1155. Or
  1156. select employee.deptno from employee,department;
  1157. Output:
  1158. DEPTNO
  1159. ----------
  1160. 10
  1161. Database Systems Lab Manual
  1162. 10
  1163. 10
  1164. 10
  1165. 30
  1166. 30
  1167. 30
  1168. 30
  1169. 10
  1170. 10
  1171. 10
  1172. DEPTNO
  1173. ----------
  1174. 10
  1175. 30
  1176. 30
  1177. 30
  1178. 30
  1179. f. Natural Join
  1180. If two tables have same column name the values of that column will be displayed only once.
  1181. Syntax:
  1182. SELECT <column_name(s)> FROM <table_name1> Natural JOIN<table_name2>;
  1183. Example:
  1184. select deptno,first_name from employee natural join department;
  1185. Output:
  1186. DEPTNO FIRST_NAME
  1187. ------ ----------
  1188. 10 Smith
  1189. 30 Arun
  1190. 10 Nithya
  1191. 30 john
  1192. SUB QUERIES
  1193.  Nesting of queries
  1194.  A query containing a query in itself A
  1195.  Inner most sub query will be executed first
  1196.  The result of the main query depends on the values return by sub query
  1197. Database Systems Lab Manual
  1198.  Sub query should be enclosed in parenthesis
  1199. 1. Sub query returning only one value
  1200. a. Relational operator before sub query.
  1201. Syntax:
  1202. SELECT <column_name(s)> FROM <table_name> WHERE < column name >
  1203. < relational op.> < sub query>;
  1204. Example:
  1205. SELECT employee_id ,first_name FROM employee
  1206. WHERE deptno =
  1207. (SELECT deptno FROM department
  1208. WHERE dname = ‘IT’)
  1209. Output:
  1210. EMPLOYEE_ID FIRST_NAME
  1211. ----------- ----------
  1212. 112 Arun
  1213. 114 john
  1214. 2. Sub query returning more than one value
  1215. a. ANY
  1216. For the clause any, the condition evaluates to true if there exists at least one row selected by the sub query for which the comparison holds. If the sub query yields an empty result set, the condition is not satisfied.
  1217. Syntax:
  1218. SELECT <column_name(s)> FROM <table_name> WHERE < column name >
  1219. Database Systems Lab Manual
  1220. < relational op.> ANY (<sub query>);
  1221. Example:
  1222. SELECT employee_id ,first_name FROM employee
  1223. WHERE salary>= ANY
  1224. (SELECT salary FROM employee
  1225. WHERE deptno = 30)
  1226. AND deptno = 10;
  1227. Output:
  1228. EMPLOYEE_ID FIRST_NAME
  1229. ----------- ----------
  1230. 113 Nithya
  1231. 112 Arun
  1232. 111 Smith
  1233. 114 john
  1234. 114 john
  1235. b. ALL
  1236. For the clause all, in contrast, the condition evaluates to true if for all rows selected by the sub query the comparison holds. In this case the condition evaluates to true if the Sub query does not yield any row or value.
  1237. Syntax:
  1238. SELECT <column_name(s)> FROM <table_name> WHERE < column name > < relational op.> ALL (<sub query>);
  1239. Example:
  1240. SELECT employee_id ,first_name FROM employee
  1241. WHERE salary > ALL
  1242. (SELECT salary FROM employee
  1243. WHERE deptno = 30);
  1244. Output:
  1245. EMPLOYEE_ID FIRST_NAME
  1246. Database Systems Lab Manual
  1247. ----------- ----------
  1248. 113 Nithya
  1249. c. IN :Main query displays the values that match with any of the values returned by sub query.
  1250. Syntax:
  1251. SELECT <column_name(s)> FROM <table_name>
  1252. WHERE < column name > IN (<sub query>);
  1253. Example:
  1254. SELECT employee_id ,first_name FROM employee
  1255. WHERE deptno IN
  1256. (SELECT deptno FROM department
  1257. WHERE loc = ’Bangalore’);
  1258. Output:
  1259. EMPLOYEE_ID FIRST_NAME
  1260. ----------- ----------
  1261. 114 john
  1262. 112 Arun
  1263. d. NOT IN
  1264. Main query displays the values that match with any of the values returned by sub query.
  1265. Syntax:
  1266. SELECT <column_name(s)> FROM <table_name> WHERE < column name > NOT IN (<sub query>);
  1267. Example:
  1268. SELECT employee_id ,first_name FROM employee
  1269. WHERE deptno NOT IN
  1270. (SELECT deptno FROM department
  1271. WHERE loc = ’Bangalore’);
  1272. Database Systems Lab Manual
  1273. Output:
  1274. EMPLOYEE_ID FIRST_NAME
  1275. ----------- ----------
  1276. 113 Nithya
  1277. 111 Smith
  1278. e. EXISTS
  1279. Main query displays the values that match with any of the values returned by sub query.
  1280. Syntax:
  1281. SELECT <column_name(s)> FROM <table_name> WHERE EXISTS (<sub query>);
  1282. Example:
  1283. SELECT * FROM department
  1284. WHERE EXISTS
  1285. (SELECT * FROM employee
  1286. WHERE deptno = department.deptno);
  1287. Output:
  1288. DEPTNO DNAME LOC
  1289. ---------- -------------- -------------
  1290. 10 accounts chennai
  1291. 30 IT Bangalore
  1292. f. NOT EXISTS
  1293. Main query displays the values that match with any of the values returned by sub query.
  1294. Syntax:
  1295. SELECT <column_name(s)> FROM <table_name> WHERE NOT EXISTS (<sub query>);
  1296. Example:
  1297. SELECT * FROM department
  1298. WHERE NOT EXISTS
  1299. Database Systems Lab Manual
  1300. (SELECT * FROM employee
  1301. WHERE deptno = department.deptno);
  1302. Output:
  1303. DEPTNO DNAME LOC
  1304. ---------- -------------- -------------
  1305. 20 finance Hyderabad
  1306. 40 marketing chennai
  1307. g. GROUP BY CLAUSE
  1308. Often applications require grouping rows that have certain properties and then applying an aggregate function on one column for each group separately. For this, SQL provides the clause group by <group column(s)>. This clause appears after the where clause and must refer to columns of tables listed in the from clause.
  1309. Rule:
  1310. Select attributes and group by clause attributes should be same.
  1311. Syntax:
  1312. SELECT <column_name(s)> FROM <table_name> Where <conditions>
  1313. GROUP BY <column2>, <column1>;
  1314. Example:
  1315. SELECT deptno, min(salary), max(salary)
  1316. FROM employee
  1317. GROUP BY deptno;
  1318. Output:
  1319. DEPTNO MIN(SALARY) MAX(SALARY)
  1320. Database Systems Lab Manual
  1321. --------- ----------- -----------
  1322. 30 30000 40000
  1323. 30000 30000
  1324. 10 33000 45000
  1325. h. HAVING CLAUSE: used to apply a condition to group by clause
  1326. Syntax:
  1327. SELECT <column(s)>
  1328. FROM <table(s)>
  1329. WHERE <condition>
  1330. [GROUP BY <group column(s)>]
  1331. [HAVING <group condition(s)>];
  1332. Example:
  1333. SELECT deptno, min(salary), max(salary)
  1334. FROM employee
  1335. WHERE job_id = ’J2’
  1336. GROUP BY deptno
  1337. HAVING count(*) > 1;
  1338. Output:
  1339. DEPTNO MIN(SALARY) MAX(SALARY)
  1340. ---------- ----------- -----------
  1341. 30 13000 40000
  1342. A query containing a group by clause is processed in the following way:
  1343. 1. Select all rows that satisfy the condition specified in the where clause.
  1344. 2. From these rows form groups according to the group by clause.
  1345. 3. Discard all groups that do not satisfy the condition in the having clause.
  1346. 4. Apply aggregate functions to each group.
  1347. 5. Retrieve values for the columns and aggregations listed in the select clause.
  1348. Database Systems Lab Manual
  1349. i. ORDER BY
  1350. Used along with where clause to display the specified column in ascending order or descending order . Default is ascending order
  1351. Syntax:
  1352. SELECT [distinct] <column(s)>
  1353. FROM <table>
  1354. [ WHERE <condition> ]
  1355. [ ORDER BY <column(s) [asc|desc]> ]
  1356. Example:
  1357. SELECT first_name, deptno, hire_date
  1358. FROM employee
  1359. ORDER BY deptno ASC, hire_date desc;
  1360. Output:
  1361. FIRST_NAME DEPTNO HIRE_DATE
  1362. ---------- ---------- ---------
  1363. Smith 10 21-JUL-10
  1364. Nithya 10 12-FEB-99
  1365. john 30 20-JAN-10
  1366. Arun 30 05-JUN-08
  1367. john 20-JAN-10
  1368. VIEWS
  1369. Definition: A view is a named, derived, virtual table. A view takes the output of a query and treats it as a table; therefore a view can be thought of as a ‘stored query’ or a ‘virtual table’. We can use views in most places where tables can be used. To the user, accessing a view is like accessing a table. The RDBMS creates an illusion of a table, by assigning a name to the view and storing its definition in the database.
  1370. The tables upon which the views are based are called as ‘base tables’.
  1371. CREATION OF A VIEW:
  1372. Database Systems Lab Manual
  1373. The syntax for creating a view is given by:
  1374. create [or replace][[no][force]]view <view_name> [column alias name…]as <query>[with[check option]read only][constraint]];
  1375. Example:
  1376. SQL>create or replace view EMP_VIEW as select * from EMP;
  1377. This statement creates a view named EMP_VIEW .The data in this view comes from the base table EMP. Any changes made to the base table are instantly visible through the view EMP_VIEW.We can use select statement just like on a table.
  1378. SQL>select * from EMP_VIEW;
  1379. When create or replace is given, view is created if it is not available otherwise it is recreated.
  1380. HOW DOES RDBMS HANDLE THE VIEWS: When a reference is made by a user, the RDBMS finds the definition of the view stored in the database .It then translates the user’s request that referenced the view into an equivalent request against the source tables of the view. Thus RDBMS maintains the illusion of the view.
  1381. TYPES OF VIEWS: The different types of views are
  1382. • Column subset view
  1383. • Row subset view
  1384. • Row-Column subset view
  1385. • Grouped view
  1386. • Joined view
  1387. COLUMN SUBSET VIEW:
  1388. A column subset view is one where all the rows but only some of the columns of the base table form the view. The create view
  1389. Example:
  1390. SQL>create or replace view CSV as select empno, ename, sal from EMP;
  1391. This view includes only columns empno, ename, sal of EMP table. Since there is no where clause it includes all the rows.
  1392. ROW SUBSET VIEW:
  1393. Database Systems Lab Manual
  1394. A row subset view is one where all columns but some rows of the source table form the view. All the columns of the base table participate in the view but all rows do not.
  1395. Example:
  1396. SQL> create or replace view RSV as select * from EMP where deptno=10;
  1397. The where clause restricts the no. of rows to those of employees working in Department Number 10.
  1398. ROW-COLUMN SUBSET VIEW:
  1399. A row-column subset view is a view which includes only some rows and columns of the base table.
  1400. Example:
  1401. SQL>create or replace view RCS as select EMPNO, ENAME, SAL from EMP where deptno=10;
  1402. GROUPED VIEW:
  1403. The query specified in the view definition can include the GROUP BY clause. This type of view is called as Grouped View.
  1404. Example:
  1405. SQL>create or replace view GV (dno, avgsal) as select deptno, AVG (SAL) from emp group by deptno;
  1406. JOINED VIEWS:
  1407. A joined view is formed by specifying a two or more table query in the view definition. A joined view draws its data from two or more tables and presents the result as a single virtual table.
  1408. Example:
  1409. SQL>create or replace view JV(empno,ename,sal,dname,loc) as select empno,ename,sal,dname,loc from EMP,DEPT where EMP.deptno=DEPT.deptno;
  1410. CREATING A READ ONLY VIEW:
  1411. Use with read only clause to prevent the users from manipulating records via the view.
  1412. Example:
  1413. Database Systems Lab Manual
  1414. SQL>create or replace view WRO as select * from EMP with read only;
  1415. Note: A view can be created without a base table using FORCE option of create view command.
  1416. Example:
  1417. SQL>create or replace force view FVIEW as select * from MYDEPT;
  1418. In this query MYDEPT table does not exist, so view is created with compilation errors. When MYDEPT table is created and this query is executed, the view is automatically recompiled and become valid.
  1419. VIEW WITH CHECK OPTION:
  1420. This option specifies that inserts and updates performed through the view must result in rows that the view query can select. The CHECK OPTION can be used to maintain integrity on a view.
  1421. Example:
  1422. SQL>insert into RSV (empno, ename, sal, deptno) values (1000,’dinesh’, 5500, 20);
  1423. Though the view is created for deptno 10, we are able to insert records for other department numbers .This can be restricted using WITH CHECK OPTION clause while creating a view.
  1424. Example:
  1425. SQL>create view DEPTNO10_VIEW as select * from EMP where deptno=10 WITH CHECK OPTION CONSTRAINT CHK_DNO10;
  1426. The above statement creates a view DEPTNO10 with a check constraint. This will enforce the view to be inserted or updated only for the department number 10. No other departments can be inserted or updated.
  1427. DROPPING A VIEW:
  1428. A view can be dropped by using DROP VIEW command.A view becomes invalid if its associated base table is dropped.
  1429. Example:
  1430. SQL>drop view DEPTNO10;
  1431. This will not affect the base table EMP.
  1432. Database Systems Lab Manual
  1433. ADVANTAGES OF VIEWS:
  1434.  Valid Information: Views let different users see a table from different perspectives. Only the part that is relevant to the users is visible to them.
  1435.  Restricted Access: Views restrict access to the table. Different users are allowed to see only certain rows or certain columns of a table.
  1436.  Simplified Access: Views simplify database access. For example a view that is a join of three tables where a user does not require all the data in all three tables.
  1437.  Data Integrity: Data Integrity can be maintained by having WITH CHECK OPTION while creating a view.
  1438. RESTRICTIONS ON VIEWS:
  1439.  A view’s query cannot select the CURRVAL or NEXTVAL pseudo columns.
  1440.  If a view’s query selects the ROWID, ROWNUM or LEVEL pseudo columns, they must have aliases in the view’s query.
  1441.  A view can’t be created with an ORDER BY clause.
  1442.  A view can’t be updated, deleted and inserted if it is a grouped view.
  1443.  A view created from multiple tables can’t be updatable.
  1444.  If a view is based on a single underlying table then you can insert, update or delete rows in this view. This will actually insert, update or delete rows in the underlying table. There are restrictions again on doing this:
  1445.  You cannot insert if the underlying table has a NOT NULL column that does not appear in the view.
  1446.  You cannot insert or update if any of the view’s columns referenced in insert or update consist of functions or calculations.
  1447.  You cannot insert, update or delete if the view contains GROUP BY, DISTINCT or a reference to a pseudo column ROWNUM.
  1448. Database Systems Lab Manual
  1449. PL/SQL
  1450. Overview of PL/SQL
  1451. 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.
  1452. Pl/SQL Environment
  1453. The PL/SQL engine in the oracle server process the pl/sql block and it separates SQL staments and sends them individually to the SQL statements executor
  1454. Benefits of PL/SQL
  1455.  Integration
  1456.  Improved performance
  1457.  Modularized program development
  1458.  Portability
  1459.  Identifiers
  1460. PL/SQL engine
  1461. P SQL
  1462. SQL
  1463. PL/SQL block
  1464. Procedural statement executor
  1465. PL/SQL block
  1466. Oracle Server
  1467. SQL statement executor
  1468. Database Systems Lab Manual
  1469. PL/SQL Block structure
  1470. DECLARE (optional)
  1471. Variables, cursors, user-defined exceptions
  1472. BEGIN (Mandatory)
  1473. -SQL statements
  1474. -PL/SQL statements
  1475. EXCEPTION (optional)
  1476. Action to perform when error occur
  1477. END;
  1478. The PL/SQL Block consists of three sections:
  1479. DECLARATIVE
  1480. It contains all variables, constants, cursors and user defined exceptions that are referenced in the executable and declarative sections.
  1481. EXECUTABLE
  1482. It contains SQL statements to manipulate data in the database and PL/SQL statements to manipulate data in the block.
  1483. EXCEPTION HANDLING
  1484. It specifies the actions to perform when errors and abnormal conditions arise in the executable section.
  1485. PL/SQL Block Types
  1486. A PL/SQL program comprises one or more blocks.
  1487. It is classified into two blocks
  1488.  Anonymous Blocks
  1489. Database Systems Lab Manual
  1490. It is unnamed blocks. It is declared at the point in an application where they are to be executed and are passed to the PL/SQL engine for execution at run time.
  1491.  Subprograms
  1492. Subprograms are named PL/SQL blocks that can accept parameters and can be invoked. It can be declared either as procedures or as functions.
  1493. Sample PL/SQL programs
  1494. To write PL/SQL programs, create a script file and run the script file or use editor.
  1495. Steps to create script file
  1496. Step1:
  1497. SQL> edit z:\oracle\sql\var1.sql
  1498. Step2:
  1499. Type the program in notepad
  1500. Step 3:
  1501. Save the program
  1502. Step4:
  1503. Run the program
  1504. SQL> @z:\oracle\sql\var1.sql
  1505. SQL> set serveroutput on;
  1506. This command is used to display the statement executed by dbms_output.put_line package.
  1507. Program 1: Write a program to print a variable value.
  1508. SQL> declare
  1509. 2 a number:=3;
  1510. 3 begin
  1511. Database Systems Lab Manual
  1512. 4 dbms_output.put_line(a);
  1513. 5 end;
  1514. 6 /
  1515. 3
  1516. Program 2: Write a program to print your name and regno.
  1517. 1 declare
  1518. 2 v_name varchar2(10);
  1519. 3 v_regno number;
  1520. 4 begin
  1521. 5 v_name:='venkat';
  1522. 6 v_regno:=39;
  1523. 7 dbms_output.put_line( 'the name is' || v_name);
  1524. 8 dbms_output.put_line('the no is' || v_regno);
  1525. 9 end;
  1526. SQL> /
  1527. the name is venkat
  1528. the no is 39
  1529. PL/SQL procedure successfully completed.
  1530. Database Systems Lab Manual
  1531. Program 3: Write a program to retrieve ssn number of employee whose name is x.
  1532. Assume the following table:
  1533. SSN NAME ESSN DEPTNO SALARY
  1534. ---------- ---------- ---------- ---------- ----------
  1535. 101 x 102 1
  1536. 102 y 103 2
  1537. 103 z 102 3
  1538. 104 p 102 4
  1539. 105 q
  1540. declare v_no number;
  1541. begin
  1542. select ssn into v_no from emp where name='x';
  1543. dbms_output.put_line(v_no);
  1544. end;
  1545. SQL>/
  1546. 101
  1547. PL/SQL procedure successfully completed.
  1548. SCALAR VARIABLE
  1549. It holds a single value and has no internal components.
  1550. Examples : number, character, date, boolean
  1551. Example: using scalar variable
  1552. Database Systems Lab Manual
  1553. 1 declare
  1554. 2 v_name varchar2(10);
  1555. 3 V_count binary_integer:=10;
  1556. 4 V_totalsal number(9,2);
  1557. 5 v_orderdate date:=sysdate;
  1558. 6 c_tax constant number(3,2):=6.23;
  1559. 7 v_valid boolean not null:=true;
  1560. 8 v_regno number default 23;
  1561. 9 begin
  1562. 10 v_name:='venkat';
  1563. 11 v_totalsal:=10000.23;
  1564. 12 dbms_output.put_line(v_name);
  1565. 13 dbms_output.put_line(v_count);
  1566. 14 dbms_output.put_line(v_orderdate);
  1567. 15 dbms_output.put_line(c_tax);
  1568. 16 dbms_output.put_line(v_regno);
  1569. 17 end;
  1570. 18 /
  1571. venkat
  1572. 10
  1573. 19-AUG-05
  1574. 6.23
  1575. 23
  1576. Database Systems Lab Manual
  1577. DECLARING VARIABLE WITH THE %TYPE ATTRIBUTE
  1578. The % type attribute is used to declare a variable according to:
  1579. 1. A database column definition
  1580. 2. Another previously declared variable
  1581. Example: using % type attribute
  1582. 1 declare
  1583. 2 v_no emp.ssn%type;
  1584. 3 V_name varchar2(10):='venkat';
  1585. 4 name v_name%type;
  1586. 5 begin
  1587. 6 v_no:=10;
  1588. 7 name:='ven';
  1589. 8 dbms_output.put_line(v_no);
  1590. 9 dbms_output.put_line(name);
  1591. 10*end;
  1592. 11 /
  1593. 10
  1594. ven
  1595. PL/SQL procedure successfully completed.
  1596. Database Systems Lab Manual
  1597. BIND VARIABLES
  1598. A bind variable is a variable that is declared in a host environment. Bind variables can be used to pass run-time values, which can be either number or character, into or out of one or more PL/SQL programs.
  1599. Example:
  1600. SQL> variable a number;
  1601. SQL> ed
  1602. File:
  1603. 1 begin
  1604. 2 select ssn into:a from emp where name='x';
  1605. 3 dbms_output.put_line(:a);
  1606. 4 end;
  1607. SQL> /
  1608. 101
  1609. PL/SQL procedure successfully completed.
  1610. SQL> print a;
  1611. A
  1612. ----------
  1613. 101
  1614. PL/SQL procedure successfully completed.
  1615. Database Systems Lab Manual
  1616. REFERENCING NON PL/SQL VARIABLES
  1617. To reference host variables, prefix the references with a colon (:) to distinguish them from declared PL/SQL variable.
  1618. SQL> variable gg number;
  1619. SQL> define aa=1000;
  1620. SQL> set verify off
  1621. SQL> declare
  1622. 2 v_sal number(9,2):=&aa;
  1623. 3 begin
  1624. 4 :gg:=v_sal/12;
  1625. 5 end;
  1626. 6 /
  1627. PL/SQL procedure successfully completed.
  1628. SQL> print gg;
  1629. GG
  1630. ----------
  1631. 83.3333333
  1632. PL/SQL BLOCK SYNTAX AND GUIDELINES
  1633. A line of pl/sql text contains groups of characters known as lexical units.
  1634. Lexicals are classified as follows:
  1635.  Delimiters
  1636.  Identifiers, which include reserved words
  1637.  Literals
  1638.  Character literals
  1639.  Numeric literals
  1640. Database Systems Lab Manual
  1641. COMMENTS:
  1642. -- single line commenting
  1643. /* beginning */ ending
  1644. PL/SQL HAS ITS OWN ERROR HANDLING:
  1645.  SQLCODE
  1646.  SQL ERRM
  1647. DATA TYPE CONVERSION
  1648. PL/SQL performs implicit conversions. For E.g. numeric to char.
  1649. The following program highlights conversion involving DATE.
  1650. SQL> ed
  1651. 1 declare
  1652. 2 vdate date;
  1653. 3 begin
  1654. 4 vdate:=to_date('aug 19 ,2005','mon dd,yyyy');
  1655. 5 dbms_output.put_line(vdate);
  1656. 6 end;
  1657. SQL> /
  1658. 19-AUG-05
  1659. PL/SQL procedure successfully completed.
  1660. Database Systems Lab Manual
  1661. SQL FUNCTIONS IN PL/SQL:
  1662. All SQL functions are allowed except decode function and group functions.
  1663. NESTED BLOCKS AND VARIABLE SCOPE
  1664. SQL> declare
  1665. 2 v_a number:=3;
  1666. 3 begin
  1667. 4 declare
  1668. 5 v_b number:=4;
  1669. 6 begin
  1670. 7 dbms_output.put_line(v_b);
  1671. dbms_output.put_line(v_a);
  1672. 8 end;
  1673. 9 dbms_output.put_line(v_a);
  1674. 10 end;
  1675. 11 /
  1676. 4
  1677. 3
  1678. PL/SQL procedure successfully completed.
  1679. Database Systems Lab Manual
  1680. QUALIFYING AN IDENTIFIER An identifier is qualified by using the block label prefix. In the example the outer block is labeled as outer. In the inner block the variable is reference by label, when variable names are same.
  1681. SQL> ed
  1682. 1 <<outer>>
  1683. 2 declare
  1684. 3 v_a number:=3;
  1685. 4 begin
  1686. 5 declare
  1687. 6 v_a number:=4;
  1688. 7 begin
  1689. 8 dbms_output.put_line(v_a);
  1690. 9 dbms_output.put_line(outer.v_a);
  1691. 10 end;
  1692. 11 end;
  1693. 12 /
  1694. 4
  1695. 3
  1696. PL/SQL procedure successfully completed.
  1697. Database Systems Lab Manual
  1698. PROGRAMMING GUIDELINES:
  1699. Category
  1700. Case Conversion
  1701. Examples
  1702. SQL statements
  1703. uppercase
  1704. SELECT,INSERT
  1705. PL/SQL statements
  1706. uppercase
  1707. DECLARE,BEGIN,IF
  1708. Data types
  1709. uppercase
  1710. VARCHAR2,BOOLEAN
  1711. Identifiers
  1712. lowercase
  1713. v_sal
  1714. Database tables and column
  1715. lowercase
  1716. emp, dept
  1717. INTERACTING WITH ORACLE SERVER:
  1718.  Extracts row of data from the database using select
  1719.  Effects changes in the database by using DML commands
  1720.  Controls a transaction with commit, rollback and save point
  1721. NOTES:
  1722.  An end in pl/sql block is not the end of transaction.
  1723.  A block can span multiple transactions, a transaction can span multiple blocks.
  1724.  DDL commands (create,alter,drop) and DCL commands(grant,revoke) are not directly supported.
  1725. SQL> select * from emp;
  1726. SSN NAME ESSN DEPTNO SALARY
  1727. ---------- ---------- ---------- ---------- ----------
  1728. 101 x 102 1
  1729. Database Systems Lab Manual
  1730. 102 y 103 2
  1731. 103 z 102 3
  1732. 104 p 102 4
  1733. 105 q
  1734. SQL> ed
  1735. 1 declare
  1736. 2 v_ssn number;
  1737. 3 v_name varchar2(10);
  1738. 4 begin
  1739. 5 select ssn,name into v_ssn,v_name from emp where name='x';
  1740. 6 dbms_output.put_line(v_ssn);
  1741. 7 dbms_output.put_line(v_name);
  1742. 8 end;
  1743. SQL> /
  1744. 101
  1745. x
  1746. PL/SQL procedure successfully completed.
  1747. RETRIEVING DATA IN PL/SQL:
  1748. SQL> select * from job_grade;
  1749. GRA LOWEST_SAL HIGHEST_SAL
  1750. ---- ---------- -----------------------------------------
  1751. a 3000 4000
  1752. Database Systems Lab Manual
  1753. b 5000 6000
  1754. c 3000 6000
  1755. d 4000 10000
  1756. e 2000 6000
  1757. SQL> ed
  1758. 1 declare
  1759. 2 v_lsal job_grade.lowest_sal%type;
  1760. 3 v_hsal job_grade.highest_sal%type;
  1761. 4 begin
  1762. 5 select sum(lowest_sal),sum(highest_sal) into v_lsal,v_hsal from job_grade;
  1763. 6 dbms_output.put_line(v_lsal);
  1764. 7 dbms_output.put_line(v_hsal);
  1765. 8 end;
  1766. 9 /
  1767. 17000
  1768. 32000
  1769. PL/SQL procedure successfully completed.
  1770. NAMING CONVENTIONS
  1771. A local variable in pl/sql name must not be equal to column names present in database .
  1772. declare
  1773. Database Systems Lab Manual
  1774. lastname varchar2(10);
  1775. begin
  1776. delete from emp where lastname-lastname;
  1777. The above code will delete all employees because of the naming convention problem.
  1778. MANIPULATING DATA USING PL/SQL
  1779. SUBSTIUTION VARIABLE:
  1780. SQL> ed
  1781. Wrote file afiedt.buf
  1782. 1 declare
  1783. 2 v_sal number;
  1784. 3 begin
  1785. 4 v_sal:=&v_sal;
  1786. 5 dbms_output.put_line(v_sal);
  1787. 6 end;
  1788. 7 /
  1789. Enter value for v_sal: 2000
  1790. 2000
  1791. PL/SQL procedure successfully completed.
  1792. INSERTION
  1793. SQL> ed
  1794. Database Systems Lab Manual
  1795. Wrote file afiedt.buf
  1796. 1 begin
  1797. 2 insert into emp(ssn,name) values(123,'venkat');
  1798. 3 dbms_output.put_line('record inserted');
  1799. 4 end;
  1800. 5 /
  1801. record inserted
  1802. PL/SQL procedure successfully completed.
  1803. USAGE OF SUBSTITUTION VARIABLE:
  1804. SQL> ed
  1805. Wrote file afiedt.buf
  1806. 1 begin
  1807. 2 insert into emp(ssn,name) values(&ssn,'&name');
  1808. 3 dbms_output.put_line('record inserted');
  1809. 4 end;
  1810. SQL> /
  1811. Enter value for ssn: 124
  1812. Enter value for name: sampath
  1813. record inserted
  1814. PL/SQL procedure successfully completed.
  1815. Database Systems Lab Manual
  1816. UPDATE:
  1817. SQL> ed
  1818. Wrote file afiedt.buf
  1819. 1 declare
  1820. 2 v_sal number;
  1821. 3 begin
  1822. 4 v_sal:=&v_sal;
  1823. 5 update job_grade set lowest_sal=v_sal where gra='a';
  1824. 6 dbms_output.put_line('record updated');
  1825. 7 end;
  1826. SQL> /
  1827. Enter value for v_sal: 12000
  1828. record updated
  1829. PL/SQL procedure successfully completed.
  1830. SQL> select *from job_grade;
  1831. GRA LOWEST_SAL HIGHEST_SAL
  1832. ---- ---------- -------------------------------------------
  1833. a 12000 4000
  1834. b 5000 6000
  1835. c 3000 6000
  1836. Database Systems Lab Manual
  1837. d 4000 10000
  1838. e 2000 6000
  1839. DELETE:
  1840. SQL> ed
  1841. Wrote file afiedt.buf
  1842. 1 declare
  1843. 2 v_sal number;
  1844. 3 begin
  1845. 4 v_sal:=&v_sal;
  1846. 5 delete from job_grade where lowest_sal=v_sal;
  1847. 6 dbms_output.put_line('record deleted');
  1848. 7 end;
  1849. 8 /
  1850. Enter value for v_sal: 5000
  1851. record deleted
  1852. PL/SQL procedure successfully completed.
  1853. SQL> select * from job_grade;
  1854. GRA LOWEST_SAL HIGHEST_SAL
  1855. ---- ---------- -----------
  1856. a 12000 4000
  1857. c 3000 6000
  1858. d 4000 10000
  1859. Database Systems Lab Manual
  1860. e 2000 6000
  1861. CONTROL STRUCTURES
  1862. • IF statements
  1863.  If –then-end if
  1864.  If-then-else-end if
  1865.  If-then-elseif-end if
  1866. • Case expressions
  1867. • Loop statements
  1868.  Basic loops
  1869.  While loops
  1870.  For loops
  1871. Syntax of IF:
  1872. If condition then
  1873. Statements;
  1874. Else if condition then
  1875. Statements;
  1876. Else
  1877. Statements;
  1878. End if;
  1879. Examples:
  1880. Database Systems Lab Manual
  1881. 1) Find the greatest among two numbers
  1882. 1 declare
  1883. 2 a number;
  1884. 3 b number;
  1885. 4 begin
  1886. 5 a:=&a;
  1887. 6 b:=&b;
  1888. 7 if a>b then
  1889. 8 dbms_output.put_line('gratest number is'||a);
  1890. 9 else
  1891. 10 dbms_output.put_line('gratest number is'||b);
  1892. 11 end if;
  1893. 12 end;
  1894. SQL> /
  1895. Enter value for a: 12 old 5: a:=&a;
  1896. new 5: a:=12;
  1897. Enter value for b: 4 old 6: b:=&b;
  1898. new 6: b:=4;
  1899. greatest number is12
  1900. PL/SQL procedure successfully completed
  1901. Database Systems Lab Manual
  1902. 2) if else with database
  1903. DEPT_ID
  1904. DEPT_NAME
  1905. MANAGER_ID
  1906. LOCATION_ID
  1907. ---------
  1908. ----------
  1909. ----------
  1910. -----------
  1911. 10
  1912. cse
  1913. 200
  1914. 1700
  1915. 20
  1916. it
  1917. 300
  1918. 1800
  1919. 30
  1920. mech
  1921. 400
  1922. 1500
  1923. 40
  1924. ece
  1925. 500
  1926. 1600
  1927. 1 declare
  1928. 2 v_id departments.dept_id%type;
  1929. 3 v_dname departments.dept_name%type;
  1930. 4 begin
  1931. 5 select dept_id,dept_name into v_id,V_dname from departments where manager_id=200;
  1932. 6 if v_id=11 then
  1933. 7 dbms_output.put_line(v_dname);
  1934. 8 elsif v_dname='cse' then
  1935. 9 dbms_output.put_line(v_id);
  1936. 10 else
  1937. 11dbms_output.put_line('recorde not match');
  1938. 12 end if;
  1939. 13 end;
  1940. SQL> / 10
  1941. Database Systems Lab Manual
  1942. PL/SQL procedure successfully completed.
  1943. 3) if/else if/ else
  1944. 1 declare
  1945. 2 a number;
  1946. 3 b number;
  1947. 4 c number;
  1948. 5 begin
  1949. 6 a:=&a;
  1950. 7 b:=&b;
  1951. 8 c:=&c;
  1952. 9 if (a>b) and (a>c) then
  1953. 10 dbms_output.put_line('gratest number is'||a);
  1954. 11 elsif(b>a) and (b>c) then
  1955. 12 dbms_output.put_line('greatest number is'||b);
  1956. 13 else
  1957. 14 dbms_output.put_line('greatest number is'||c);
  1958. 15 end if;
  1959. 16 end;
  1960. SQL>/
  1961. Enter values for a,b and c: 6 4 12
  1962. C is greater :12.
  1963. Database Systems Lab Manual
  1964. PL/SQL procedure successfully completed.
  1965. 4) Case Expressions
  1966. 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 alternatives.
  1967. Syntax :
  1968. CASE selector
  1969. WHEN
  1970. expression1
  1971. THEN result1 WHEN
  1972. expression2
  1973. THEN result2
  1974. ---------
  1975. WHEN expression N THEN result N [ELSE resultN+1
  1976. END;
  1977. Example:
  1978. 1 declare
  1979. 2 va varchar2(10);
  1980. 3 v_result varchar2(10);
  1981. 4 begin
  1982. 5 va:=&va;
  1983. Database Systems Lab Manual
  1984. 6 v_result:=
  1985. 7 CASE va
  1986. 8 WHEN 'a' THEN 'excellent'
  1987. 9 WHEN 'b' THEN 'very good'
  1988. 10 WHEN 'c' THEN 'good'
  1989. 11 ELSE 'poor'
  1990. 12 end;
  1991. 13 dbms_output.put_line('grade is'||v_result);
  1992. 14 end;
  1993. 15 /
  1994. SQL> Enter value for va: 'a' old 5: va:=&va;
  1995. new 5: va:='a';
  1996. grade is excellent
  1997. PL/SQL procedure successfully completed.
  1998. SQL> /
  1999. Enter value for va: 'b' old 5: va:=&va;
  2000. new 5: va:='b';
  2001. grade is very good
  2002. PL/SQL procedure successfully completed.
  2003. SQL> /
  2004. Database Systems Lab Manual
  2005. Enter value for va: 'c' old 5: va:=&va;
  2006. new 5: va:='c';
  2007. grade is good
  2008. PL/SQL procedure successfully completed.
  2009. 5) For Structure
  2010. SQL> 1 begin
  2011. 2 for emp_record in (select * from wer1) loop
  2012. 3 insert into wer1(name,ssn) values(emp_record.name,emp_record.ssn);
  2013. 4 end loop;
  2014. 5 commit;
  2015. 6 end;
  2016. 7 /
  2017. PL/SQL procedure successfully completed
  2018. Database Systems Lab Manual
  2019. CURSORS
  2020. The oracle server uses work areas, called private SQL areas, to execute SQL statement and to store processing information. This area is called cursor.
  2021. Cursor types:
  2022.  Implicit: queries returns only one row
  2023.  Explicit : queries returns more than one row
  2024. Explicit cursor
  2025. Active set: set of rows returned by multiple rows
  2026. Controlling explicit cursor
  2027. Open the cursor and execute the query associated with the cursor which identifies the result set.
  2028. Fetch
  2029. Retrieves the current row an advance the current row
  2030. Close the cursor
  2031. Syntax:
  2032. Cursor declaration
  2033. cursor cuname is select;
  2034. Open the cursor
  2035. open cursor name;
  2036. Close the cursor
  2037. Database Systems Lab Manual
  2038. close cursor name;
  2039. Fetch
  2040. fetch cname into variable or record
  2041. Explicit Cursor Attributes: To determine the status of the cursor, the cursor’s attributes are checked.Cursors have the following four attributes that can be used in a PL/SQL program.
  2042. %isopen -To check if the cursor is opened or not
  2043. %found-To check if a record is found and can be fetched from the cursor
  2044. %rowcount-To check for the number of rows fetched from the cursor
  2045. %notfound-To check if no more records can be fetched from the cursor
  2046. %isopen, %found,%notfound are boolean attributes which are set to either TRUE or FALSE.
  2047. A Simple Example:
  2048. 1 declare
  2049. 2 v_name wer1.name%type;
  2050. 3 v_ssn wer1.ssn%type;
  2051. 4 cursor emp_c is select * from wer1;
  2052. 5 begin
  2053. 6 open emp_c;
  2054. 7 for i in 1..5 loop
  2055. 8 fetch emp_c into v_name,v_ssn;
  2056. 9 dbms_output.put_line(v_name);
  2057. Database Systems Lab Manual
  2058. 10 end loop;
  2059. 11 close emp_c;
  2060. 12 end;
  2061. PL/SQL procedure successfully completed.
  2062. SQL> set serveroutput on;
  2063. SQL> / x
  2064. x
  2065. x
  2066. y
  2067. y
  2068. 2) %row count
  2069. 1 declare
  2070. 2 v_name wer1.name%type;
  2071. 3 v_ssn wer1.ssn%type;
  2072. 4 cursor emp_c is select * from wer1;
  2073. 5 begin
  2074. 6 open emp_c;
  2075. 7 for i in 1..5 loop
  2076. 8 fetch emp_c into v_name,v_ssn;
  2077. 9 exit when emp_c%rowcount>4;
  2078. 10 dbms_output.put_line(v_name);
  2079. Database Systems Lab Manual
  2080. 11end loop;
  2081. 12 close emp_c;
  2082. 13 end;
  2083. SQL> / x
  2084. x
  2085. x
  2086. y
  2087. PL/SQL procedure successfully completed.
  2088. 3) Cursor with record
  2089. It processes the rows of the active set by fetching values into a PL/SQL record.
  2090. 1 declare
  2091. 2 cursor emp_c is select * from wer1;
  2092. 3 emp_record emp_c%rowtype;
  2093. 4 begin
  2094. 5 open emp_c;
  2095. 6 for i in 1..5 loop
  2096. 7 fetch emp_c into emp_record;
  2097. 8 exit when emp_c%notfound;
  2098. 9 insert into wer(name,ssn) values(emp_record.name,emp_re
  2099. 10 end loop;
  2100. 11 commit;
  2101. 12 close emp_c;
  2102. Database Systems Lab Manual
  2103. 13 end;
  2104. 14 /
  2105. PL/SQL procedure successfully completed.
  2106. SQL> select * from wer;
  2107. NAME
  2108. SSN
  2109. ----------
  2110. ----------
  2111. x
  2112. 101
  2113. x
  2114. 101
  2115. x
  2116. 101
  2117. x
  2118. 101
  2119. x
  2120. 101
  2121. x
  2122. 101
  2123. x
  2124. 101
  2125. x
  2126. 101
  2127. x
  2128. 101
  2129. x
  2130. 101
  2131. y
  2132. 102
  2133. y
  2134. 102
  2135. 12 rows selected.
  2136. 4) Cursor with parameters
  2137. Database Systems Lab Manual
  2138. It passes the parameter values to the cursor in a cursor FOR loop. This means that you can open and close an explicit cursor several times in a block, returning a different active set on each occasion.
  2139. Example:
  2140. 1 declare
  2141. 2 v_number number;
  2142. 3 v_name varchar2(10);
  2143. 4 cursor c1(eno number,ename varchar2) is
  2144. 5 select ssn,name from emp where ssn=eno and name=ename;
  2145. 6 begin
  2146. 7 open c1(101,'x');
  2147. 8 fetch c1 into v_number,v_name;
  2148. 9 dbms_output.put_line(v_number);
  2149. 10 close c1;
  2150. 11 open c1(102,'y');
  2151. 12 fetch c1 into v_number,v_name;
  2152. 13 dbms_output.put_line(v_number);
  2153. 14 close c1;
  2154. 15 end;
  2155. 16 /
  2156. 101
  2157. 102
  2158. PL/SQL procedure successfully completed.
  2159. Database Systems Lab Manual
  2160. 5) Update
  2161. The update clause in the cursor query locks the affected rows when the cursor is opened.
  2162. Example:
  2163. declare
  2164. v_number number;
  2165. v_name varchar2(10);
  2166. cursor c1(eno number,ename varchar2) is select ssn,name from emp where ssn=eno and
  2167. name=ename for update of name nowait;
  2168. begin
  2169. open c1(101,'x');
  2170. fetch c1 into v_number,v_name;
  2171. dbms_output.put_line(v_number);
  2172. close c1;
  2173. open c1(102,'y');
  2174. fetch c1 into v_number,v_name;
  2175. dbms_output.put_line(v_number);
  2176. close c1;
  2177. end;
  2178. EXCEPTIONS
  2179. Database Systems Lab Manual
  2180. Syntax
  2181. When exception1
  2182. then Statement1
  2183. Statement2
  2184. ……..
  2185. When exception2
  2186. then Statement1
  2187. Statement2
  2188. ……..
  2189. When others
  2190. then Statement1
  2191. Statement2 ……..
  2192. Sample predefined exceptions:
  2193. NO_DATA_FOUND
  2194. TOO_MANY_ROWS
  2195. INVALID_CURSOR
  2196. ZERO_DIVIDE
  2197. DUP_VAL_ON_INDEX
  2198. Example:
  2199. 1)
  2200. 1 declare
  2201. Database Systems Lab Manual
  2202. 2 a number;
  2203. 3 b number;
  2204. 4 c number;
  2205. 5 begin
  2206. 6 a:=5;
  2207. 7 b:=0;
  2208. 8 c:= a/b;
  2209. 9 exception
  2210. 10 when zero_divide then
  2211. 11 dbms_output.put_line('zero divide error');
  2212. 12 end;
  2213. SQL> /
  2214. zero divide error
  2215. PL/SQL procedure successfully completed.
  2216. 2) Non-predefined error
  2217. Trapping a non-predefined exception
  2218. 1. Declare the name for the exception within the declarative section
  2219. 2. Associate the declared exception with the standard oracle server error number using the PRAGMA EXCEPTION_INIT statement
  2220. Syntax : PRAGMA EXCEPTION_INIT(exception, error_number);
  2221. 3. Reference the declared exception within the corresponding exception –handling routine.
  2222. Database Systems Lab Manual
  2223. Example:
  2224. 1 declare
  2225. 2 emp_remain exception;
  2226. 3 pragma exception_init
  2227. 4 (emp_remain,-2292);
  2228. 5 begin
  2229. 6 delete from emp where deptno=&deptno;
  2230. 7 commit;
  2231. 8 exception
  2232. 9 when emp_remain then
  2233. 10 dbms_output.put_line('cannot remove dept'|| 'employee exist');
  2234. 11end;
  2235. SQL> /
  2236. Enter value for deptno: 2
  2237. old 6: delete from emp where deptno=&deptno;
  2238. new 6: delete from emp where deptno=2;
  2239. cannot remove deptemployee exist
  2240. PL/SQL procedure successfully completed
  2241. SQL> /
  2242. Enter value for deptno: 8
  2243. old 6: delete from emp where deptno=&deptno;
  2244. Database Systems Lab Manual
  2245. new 6: delete from emp where deptno=8;
  2246. PL/SQL procedure successfully completed
  2247. 3) Functions for trapping exceptions
  2248. When an exception occurs, you can identify the associated error code or error message by using two functions.
  2249. SQLCODE: It returns the numeric value for the error code
  2250. SQLERRM: It returns character data containing the message associated with the error number.
  2251. Syntax:
  2252. declare;
  2253. v_error_code number;
  2254. v_error_messgage varchar2(255);
  2255. begin
  2256. when others then rollback;
  2257. v_error_code:=sqlcode;
  2258. v_error_message:=sqlerrm;
  2259. dbms_output.put_line(v_error_code||v_error_message);
  2260. end;
  2261. User defined function:
  2262. User defined PL/SQL exception must be
  2263. Database Systems Lab Manual
  2264. • Declared in the declare section of a PL/SQL block
  2265. • Raised explicitly with RAISE statements
  2266. Example:
  2267. 1 declare
  2268. 2 invalid_dept exception;
  2269. 3 begin
  2270. 4 delete from emp where deptno=&deptno;
  2271. 5 if sql%notfound then
  2272. 6 raise invalid_dept;
  2273. 7 end if;
  2274. 8 exception
  2275. 9 when invalid_dept then
  2276. 10 dbms_output.put_line('the deptnumber is not valid');
  2277. 11 end;
  2278. Enter value for deptno: 10
  2279. old 4: delete from emp where deptno=&deptno;
  2280. new 4: delete from emp where deptno=10;
  2281. the deptnumber is not valid
  2282. PL/SQL procedure successfully completed.
  2283. PL/SQL Block Types
  2284. A PL/SQL program comprises one or more blocks.
  2285. Database Systems Lab Manual
  2286. It is classified into two blocks
  2287.  Anonymous Blocks
  2288. It is unnamed blocks. It is declared at the point in an application where they are to be executed and are passed to the PL/SQL engine for execution at run time.
  2289.  Subprograms
  2290. Subprograms are named PL/SQL blocks that can accept parameters and can be invoked. It can be declared either as procedures or as functions.
  2291. Overview of subprograms
  2292. A subprogram is named PL/SQL block that ca accept parameters and be invoked from a calling environment.
  2293. Two types of subprograms
  2294.  A procedure that performs an action
  2295.  A function that computes a value
  2296. Benefits of subprograms
  2297.  Easy maintenance
  2298.  Improved data security and integrity
  2299.  Improved performance
  2300.  Improved code clarity
  2301. Procedure
  2302. 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.
  2303. Database Systems Lab Manual
  2304. Syntax for creating procedure:
  2305. Create [or replace] procedure <procedure_name>
  2306. [( parameter1 [mode1] datatype1,parameter2 [mode2] datatype2,..)]
  2307. Is| As
  2308. PL/SQL Block;
  2309. The replace option indicates that if the procedure exists, It will be dropped and replaced with the new version created by the statement. Parameter name of a PL/SQL variable whose value is passed to or populated by the calling environment.
  2310. Mode: type of argument
  2311. IN, OUT, IN OUT
  2312. IN : It is the default mode and value is passed into subprogram.
  2313. OUT : It must be specified and is returned to calling environment.
  2314. IN OUT: It is passed into subprogram and returned to calling environment.
  2315. IN parameter
  2316. IN parameters are passed as constants from the calling environment into the procedure.
  2317. Example:1
  2318. 1 create or replace procedure raise_salary
  2319. 2 (grade in job_grade.gra%type)
  2320. Database Systems Lab Manual
  2321. 3 is
  2322. 4 begin
  2323. 5 update job_grade set lowest_sal=lowest_sal*1.10 where gra= grade;
  2324. 6* end raise_salary;
  2325. 7 /
  2326. Procedure created.
  2327. SQL> execute raise_salary('a'); // executing procedure
  2328. PL/SQL procedure successfully completed.
  2329. SQL> select * from job_grade;
  2330. GRA LOWEST_SAL HIGHEST_SAL
  2331. ---- ---------- -----------------------------------------
  2332. a 13200 4000
  2333. c 3000 6000
  2334. d 4000 10000
  2335. e 2000 6000
  2336. IN, OUT parameter
  2337. Example:1
  2338. Database Systems Lab Manual
  2339. 1 create or replace procedure info
  2340. 2 (g in job_grade.gra%type,
  2341. 3 l_sal out job_grade.lowest_sal%type,
  2342. 4 h_sal out job_grade.highest_sal%type)
  2343. 5 is
  2344. 6 begin
  2345. 7 select lowest_sal,highest_sal into l_sal,h_sal from job_grade where gra=g;
  2346. 8* end info;
  2347. 9 /
  2348. SQL> edit g:\oracle\sql\info1.sql
  2349. SQL> @g:\oracle\sql\info1
  2350. Procedure created.
  2351. How to view the value of OUT parameters with sql *plus
  2352. 1.Run the sql script file to generate and compile the source code.
  2353. 2.Create host variables in sql*plus, using the variable command
  2354. 3.Invoke the procedure, supplying these host variables as the OUT parameters.: reference the host variables in the execute command.
  2355. 4.To view the values passed from the procedure to the calling environment ,use the print command.
  2356. SQL> variable g_sal number;
  2357. SQL> variable g1_sal number;
  2358. Database Systems Lab Manual
  2359. SQL> execute info('a',:g_sal,:g1_sal)
  2360. PL/SQL procedure successfully completed.
  2361. SQL> print g_sal;
  2362. G_SAL
  2363. ----------
  2364. 13200
  2365. SQL> print g1_sal;
  2366. G1_SAL
  2367. ----------
  2368. 4000
  2369. IN OUT parameter
  2370. Example:1
  2371. 1 create or replace procedure info
  2372. 2 (g in out number)
  2373. 3 is
  2374. 4 begin
  2375. 5 select lowest_sal into g from job_grade where highest_sal=g;
  2376. 6* end info;
  2377. 7 /
  2378. Procedure created.
  2379. SQL> variable g_sal number;
  2380. 1 begin
  2381. 2 :g_sal:=4000;
  2382. Database Systems Lab Manual
  2383. 3* end;
  2384. PL/SQL procedure successfully completed.
  2385. SQL> print g_sal;
  2386. G_SAL
  2387. ----------
  2388. 4000
  2389. SQL> execute info (:g_sal)
  2390. PL/SQL procedure successfully completed.
  2391. SQL> print g_sal;
  2392. G_SAL
  2393. ----------
  2394. 13200
  2395. Methods for passing parameters
  2396. Positional : List actual parameters in the same order as formal parameters
  2397. Named : List actual parameters in library order by associating each with its
  2398. corresponding formal parameter
  2399. Combination : List some of the actual parameters as positional and some as named.
  2400. Removing procedures
  2401. Drop a procedure stored in the database
  2402. Database Systems Lab Manual
  2403. Syntax:
  2404. Drop procedure procedure_name
  2405. Example:
  2406. Drop procedure raise_salary;
  2407. Functions
  2408. 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.
  2409. Syntax:
  2410. Create [or replace] function function_name
  2411. [(parameter1 [mode1] datatype1,
  2412. Parameter2 [mode2] datatype2,
  2413. ….)]
  2414. Return datatype
  2415. Is/as
  2416. PL/SQL block ;
  2417. Example:
  2418. declare
  2419. summation number;
  2420. Database Systems Lab Manual
  2421. average number;
  2422. function summa(m4 number,m5 number) return number is
  2423. begin
  2424. return(m4+m5);
  2425. end;
  2426. function aver( summ1 number) return number is
  2427. begin
  2428. return(summ1/2);
  2429. end;
  2430. begin
  2431. summation:=summa(&m1,&m2);
  2432. average:=aver(summation);
  2433. dbms_output.put_line('summation is:'||summation);
  2434. dbms_output.put_line('average is:'||average);
  2435. end;
  2436. Removing functions
  2437. Drop function function_name
  2438. Example:
  2439. Drop function summa;
  2440. Packages
  2441. Database Systems Lab Manual
  2442. Packages bundle are related PL/SQL types, items, and subprograms into one container.
  2443. A package usually has a specification and a body, stored separately in the database.
  2444. Package specification
  2445. It is the interface to the application. It declares the types, variables, constants, exceptions, cursors and subprograms.
  2446. A package specification can exist without a package body, but a package body cannot exist without a package specification.
  2447. Syntax
  2448. Create [or replace] package package_name
  2449. is| as
  2450. Public type and item declarations
  2451. Subprograms specifications
  2452. End package_name;
  2453. Example:
  2454. 1 create or replace package commp is
  2455. 2 g_comm number:=0.10;
  2456. 3 procedure reset_comm
  2457. 4 (p_comm in number);
  2458. 5 end commp;
  2459. Package created.
  2460. Database Systems Lab Manual
  2461. Package body
  2462. Syntax
  2463. Create [or replace] package body package_name
  2464. Is| as
  2465. Private type and item declarations
  2466. Subprogram bodies
  2467. End package_name;
  2468. Example
  2469. 1 create or replace package body commp
  2470. 2 is
  2471. 3 function validate_comm(p_comm in number)
  2472. 4 return boolean
  2473. 5 is
  2474. 6 v_max_comm number;
  2475. 7 begin
  2476. 8 select max(lowest_sal) into v_max_comm from job_grade;
  2477. 9 if p_comm>v_max_comm then return(false);
  2478. 10 else return(true);
  2479. 11 end if;
  2480. 12 end validate_comm;
  2481. Database Systems Lab Manual
  2482. 13 procedure reset_comm(p_comm in number)
  2483. 14 is
  2484. 15 begin
  2485. 16 if validate_comm(p_comm)
  2486. 17 then g_comm:=p_comm;
  2487. 18 else
  2488. 19 raise_application_error(-20210,'invalid commision');
  2489. 20 end if;
  2490. 21 end reset_comm;
  2491. 22 end commp;
  2492. 23 /
  2493. Package body created.
  2494. Invoking package constructs:
  2495. SQL> execute commp.reset_comm(0.15);
  2496. PL/SQL procedure successfully completed.
  2497. SQL> create or replace package global_con is
  2498. 2 a constant number:=2;
  2499. 3 b constant number :=3;
  2500. 4 end global_con;
  2501. 5 /
  2502. Package created.
  2503. SQL> execute dbms_output.put_line('20 miles='||20*global_con.a||'km');
  2504. Database Systems Lab Manual
  2505. 20 miles=40km
  2506. PL/SQL procedure successfully completed.
  2507. Referencing a public variable from a stand alone procedure:
  2508. SQL> ed
  2509. Wrote file afiedt.buf
  2510. 1 create or replace procedure me( x in number, y out number)
  2511. 2 is
  2512. 3 begin
  2513. 4 y :=x *global_con.a;
  2514. 5 end me;
  2515. SQL> /
  2516. Procedure created.
  2517. SQL> variable ya number;
  2518. SQL> execute me(3,:ya);
  2519. PL/SQL procedure successfully completed.
  2520. SQL> print ya;
  2521. YA
  2522. ----------
  2523. 6
  2524. Removing packages:
  2525. Database Systems Lab Manual
  2526. drop package package name;
  2527. drop package body package_name;
  2528. Overloading
  2529. It is the use of same name for different subprograms inside a PL/SQL block, a subprogram, or a package.
  2530. Example:
  2531. 1 create or replace package over
  2532. 2 is
  2533. 3 procedure add_dept(p_n in emp.ssn%type,p_na in emp.name%type);
  2534. 4 procedure add_dept(p_n in emp.ssn%type,p_na in emp.name%type,p_dept in emp.deptno%type);
  2535. 5 end over;
  2536. 6 /
  2537. Package created
  2538. 1 create package body overp is
  2539. 2 procedure add_dept(p_n emp.ssn%type,p_na emp.name%type)
  2540. 3 is
  2541. 4 begin
  2542. 5 insert into emp (ssn,name) values(p_n,p_na);
  2543. 6 end add_dept;
  2544. 7 procedure add_dept(p_n emp.ssn%type,p_na emp.name%type,p_dn emp.deptno%type)
  2545. 8 is
  2546. 9 begin
  2547. 10 insert into emp (ssn,name,deptno) values(p_n,p_na,p_dn);
  2548. Database Systems Lab Manual
  2549. 11 end add_dept;
  2550. 12 end overp;
  2551. Trigger
  2552. A trigger is aPL/SQL block or a PL/SQL procedure associated with a table ,view, schema, or the database. It executes implicitly whenever a particular event takes place.
  2553. It can be:
  2554. Application trigger: fires whenever an event occurs with a particular application
  2555. Database trigger: fires whenever a data event or system event occurs on a schema or database.
  2556. A triggering statement contains:
  2557.  Triggering timing
  2558. o For table: BEFORE, AFTER
  2559. o For view: INSTEAD OF
  2560.  Triggering event: INSERT, UPDATE, or DELETE
  2561.  Table name: on table, view
  2562.  Trigger type: row or statement
  2563.  When clause: restricting condition
  2564.  Trigger body: PL/SQL block
  2565. Trigger type
  2566. Statement trigger:The trigger body executes once for the triggering event. this is default. A statement trigger fires once, even if no rows are affected at all.
  2567. Row trigger:The trigger body executes once for each row affected by the triggering event. A
  2568. Database Systems Lab Manual
  2569. row trigger is not executed if the triggering event affects no rows.
  2570. Syntax:
  2571. CREATE [OR REPLACE] TRIGGER trigger_name
  2572. Timing
  2573. Event1 [OR event2 OR event3]
  2574. ON table_name
  2575. Trigger _body
  2576. Example:
  2577. create trigger ab
  2578. before insert or delete or update on a
  2579. for each row
  2580. begin
  2581. raise_application_error(-20000,'not accessible')
  2582. end
  2583. This program raises an error during insertion and deletion and update operation in a row.
  2584. _____________________________________________________________________
  2585. Database Systems Lab Manual
Add Comment
Please, Sign In to add comment