0% found this document useful (0 votes)
298 views246 pages

Oracle 11c Krishna Reddy Notes

notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
298 views246 pages

Oracle 11c Krishna Reddy Notes

notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 246
Gpp. Satyam Theatre, technologies Ameerpet, Hyderabad - 500 016. ssenmaie TRAINING BERENS ENT E-mail:[email protected] www.nareshit.com Ph:23746666, 23734842 Cell: 9000994007, 3000994008 Oracle 11g Material —————————— fhat is Database Actually? Database is a platform where we can place the data fro the future references. Database is a collection of interrelated data, i.e. database always stores data along with 's relationships. What js Database Management System? ‘A database Management System is essentially a collection interrelated data and a set of programs to access this data, This collection of data is called the Database. The primary objective of a DBMS is to provide a convenient environment to retrieve and store database information. Database System support single user and multi-user environment. While on one hand DBMS permits only one person to access the database at a given time, on the other RDBMS allows many users simultaneous access to the database. ‘A Database System consists of two parts namely, Database Management System and Database Application. Database Management System is the program that organizes and maintains the information whereas the Database Applications is the program that lets us view, retrieve and update information stored in the DBMS. + Database is a collection of data in one or more files for the future reference, * Database is a collection of interrelated data, i.e. database always stores data along with it’s relationships. Database Modeis: The main object'of the database is store the inter related data and maintain the data. The very basic elementary piece of data is called as ‘data item'.we assume that item cannot be subdivided into smaller data types and at the same time retain any meaning to the users of the data. The relationship among the data items, which shows how they are related, is called as Data model’. The database models are 1. File Management System(FMS) 2. Hierarchicla database System(HOS) 3. Network database System(NDS) 4, Relational database Management System (RDBMS). File Management System: The File Management System was the first method used to store data in a computerized database, Each data item is stored on disk sequentially in one large file. In order to locate one particular item the search starts at the beginning and each item checked subsequently till the match is found.A particular relationship cannot be drawn between the items other than the sequence in which it is stored. Drawbacks: + A particular record can not be located quickly. If the data has be stored, the whole file has to be read and rewritten in the new order, Tt will not support data types. It will not support to store or allocate memory dynamically, Data con not be shared with concurrent users. Data duplication. Very poor security: Operating system provide only a password mechanism for security, This is not sufficiently flexible to enforce security polices in which different users have permission to access different subsets of the data * Retrieving data from a file is not faster: We have to write special pragrams to answer each question a user may want to ask about the data, These programs are likely te be complex because of the large volume of data to be searched. Naresh i Technologies, Opp. Satyam Theatre, Anieerpet, Hyderabad, Ph: 23746666, 9000994008 Oracle 11g Material Hierarchical Database System(HDS): as Dent bag [on] (ioe | (amr (Cien ][om ] [Tn | I L aim fo own fof ae | waa Jol oe Jo ooo] Fig 1. Data storage is in form of a parent-child relationship.The origin of a data tree is the root,Data located at different levels along a particular branch from the root is called the node.The last node in the series is called the leaf.This model supports One-to-Many relationship.From the figure 1.0 it can be seen that the nodes in the third level are interrelated.Each child has pointer to nuierous and there is just one pointer to the parent thus resulting in a One-to-Many relationship. Suppose an information is required ,say ID 3.1, it is not necessary for the DBMS to search the entire file to locate the data.Insted, it first follows the Dept3 branch and fetches the data. Disadvantages: Tt Is not possible to enter a new level into the system. As and when such a need arises the entire structure has to be revamped. Another disadvantage is that this model does not support Many-to-Many relationship. In case this sort of relation is required then multiple copies of the same data have to made which result in redundancy. To overcome this drawback, tive Network Database Model was introduced. Note: The terminal points shows, for example below ID. 1.n.indicate that similar data are present at that point. Network Database Systems(NDS' The main idea behind the NDS model is to bring about Many-to_Many relationship. The relationship between the different data items is called as sets. This system also uses a pointer to locate a particular record(i.c called as Physical Links) Disadvantages: ‘The use of pointers leads to complexity in the structure, As a result of the increased complexity mapping of related data become very difficult. Relational Mode(RDBMS):- + The Model was first outlined by E.F Codd 1970, + The Components of Relation Model are: © Collection of objects or relations that stores the data © Aset of operations that can act on the relations to produce other relations. + Data integrity for accuracy and consistency. + Ithas only logical representations.( i.e in the form of table(rows and columns.) * Intersection of rows and columns gives single value. Naresh I Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 . Oracle 11g Material No data redundancy . No physical link relations are maintain logicaliy. Supports NULL values, integrity constraints. Provides high security. Supports unlimited size. supports to store any data types (number characters date, images audio text files.) Data can be stored among several users at time. * Data can also be shared across several plot forms. * Oracle 10g is proven to be the fastest database for Transaction processing Datawarehousing, and third party applications on servers of all sizes, + Use of Flashback Queries Alt queries the database by TIME or user specified SCN (System Change Number). 2)It uses Oracle's multi version read-consistency capabilities to restore data by applying UNDO as needed ENTITY RELATIONSHIP Model: « Inan effective system data is divided into discrete categories or entities. ‘An ER-Model is an illustration of various entities in a business and the relationships beti-een them. + ICs built during the analysis phase of the System Developing Life Cycle. * ER-Model separates the information required & the business from the activities performed. ER-MODEL Benefit: ‘It document information for the organization in a clear, precise format. * Provides a clear picture of the scope of the information requirement. + Provides an easily understood pictorial map for the database design. + Itoffers an effective framework for integrating multiple application. Key Components in ER-MODEL: * ENTITY: It is a thing of significance about which the information need to be know. + ATTRIBUTES: It is something that describes or qualifies an entity. ¥* Each attribute may be mandatory or optional but one attribute Mandatory. Relation among dat: + Arelationship is defined as “an association among entities. + Arelationship type is an association of entity types. + Several relationships may exist between the same entity. The three different types of relationships recognized among various data stored in the database are: © One-to One + Qne-to Many(or Many-to-One) + Many-to-Many ‘Naresh i Technologies, Opp. Satyam Theatre, Ameetpet, Hyderabad, Ph: 23746666, 9000994008 One-to-One: * Consider for example a set of students in a class. Each student can only one roll number. Similarly, each roll number can be associated only with one student, This is the case of One-to-One relationship Fig 1.2 illustrates this relationship. Student 1 ot Assigned > Rotlno 1 Student 2 Rollno 2 Many-to-One: One student can register for only one particular course at a time, where a number of students could register for the same course, This is illustrated with Fig1.3 Students |. Student2 Register Course Student 3 : ig 1.3 Many-to Many: A vendor can sell a number of items and many vendors can sell particular iter. This can be understand from Fig 1.4 given below. Vendor 1 Item 1 Vendor 2 Item 2 Fig 1.4 Relation Database Terminology: Row or Tuple + Terepresents all data required for a particular instance in entity, + Each row is an entity is uniquely identified by declaring it has PRIMARY KEY or UNIQUE. + The order of the rows is not significant, while retrieving the data. Column Or Attribute: «It represent one kind of data in a table. + The column order is not significant when storing the data. A Field: «It can be found at the Intersection of row and a column. + Afield can have only one value, or may not have a value at all, the al-ence of value in Oracle is represented as NULL. Relating Multiple Tables: ‘* Each table contains data that describes exactly only one entity. * Data about different entities is stored in different tables. * RDBMS enables the data in one table to be related to another table b* sing the Foreign keys. + AForeign Key is a column or a set of Column that refer to a Primary |. «in the same table or another table, Rational Database Properties: ‘+ Should not specify the access route to the tables, and should not rev-» he physical arrange. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Phi 23746666, 90°: 4008 "Oracle 11g Matertat —— eee ee «The Database is accessed using Structured Query Language(SQL) + The language is a collection of set operators. Communicating Wit! MS: + The Structured Query Language is used to Communicate with RDBMS. Structure Query Language: ‘* Structure Query Language and commonly pronounced, as “SEQUEL” (Structured English Query Language) * Dr E.f Codd published the paper on relational database model in June 1970. IBM Corporation , Inc. SEQUEL later become SQL. allows the user to communicate as the server. It is easy to learn and use. It is functionally complete, by allowing the use to define, retrieve and manipulate the data. Components of SQL: * Oracle SQL Complies with industry accepted standards. * The SQL Contains 5 Sub Language. zeData Retrieval/ Query Language( DRL/DQL) SELECT ‘* It used to retrieve the information from database objects for read only purpose, 4 Data Manipulation Language(DML). «It used to manipulate the data in database objects INSERT(new content) UPDATE(modify) DELETE(remove) 24Data Definition Language(DDL) «Used to define database objects creation modification removing CREATE = ALTER DROP TRUNCATE = RENAME x Data Control Language(DCL) * It used to share the information between users GRANT(give) REVOKE(cancel) © Transaction Control Language(TCL) "It used to save or cancel DML operations COMMIT ROLLBACK SAVEPOINT Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Phi: 23746666, 9000994008 -5 - Oracte Lig Material Oracle Architecture: User SQL * Net nnn Processes | Listener Multithreaded Server =I Shared Pool System Global Area | Program Global Area Private To distributed database nodes RECO . icen | [ ucwe__|[__cxer DBWR SHON nrchive Destination a ("seco | bogs j [Datat.dbf | ing redologs = * | ee [men Data abr Init.org Controt File | [> el 7 Fig 4.1 User Processes © When a user runs an application program, such as a Pro*C program, or an Oracle tool, such as Server Manager, Oracle creates a user process to run the user's application. -->user process will create in client side. -->SQL * Net Listener will run on server for particular port. --> Listener will listen for incoming request and service the request.(it will create a server process on server?) Dispatcher Processes(Dnnn). + The Dispatcher processes allow user processes to share a limited number of server processes. + Without a dispatcher, each user process requires one dedicated server process. Multithreaded Server(Shared server) > In dedicated server architecture each user process will create a Server process on the server where as in shared server architecture each server process will be shared by multiple user process. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 Oracte 11g Material —— ee Oracle SGA(System Global Area): * Oracle allocates @ memory area called the System Global Area(SGA) and starts ‘one or more Orarle processes. * A System Global Area(SGA) is group of shared memory structures that contain data and control information for one Oracle database instance, + Note: The combination of SGA and the Oracle processes is called an Oracle database instance. * The SGA, consists of several elements. Buffer Cache: ‘+ The buffer cache stores Oracle data in memory for users to view or change .In this way, user never make changes directly to disk files. Redo Log Buffer: * The log buffer stores special information called redo, which helps oracle reconstruct data changes in the event of system failure. Shared Poot + Components of the shared pool include the library cache, for storing parsed SQL statements for reuse by other users. Library Cache ‘The library cache includes shared SQL areas, private SQL areas, PL/SQL procedures and packages, and control structures such as locks and library cache handles. Dictionary Cache + The data Dictionary is a collection of database tables and views ,and its users. Data Dictionary stores Names of all tables and views in the database >Names and data types of columns in database tables > Privileges of all oracles users. Server Processes: «Server process created on behalf of each user’s application may perform one or more of the following: © Parse and execute SQL statements issued via the application. © Read necessary data blocks form disk(datafiles) into the shared database buffers of the SGA, if the blocks are not already presents in the SGA, Background Processes The background processes in an Oracle instance include the following Lock(LCKn) ‘+ With the parallel Server option, up to ten Lock processes(LCK0,....LCK9) provide inter-instance lacking. However, a single LCK process(LCK0) is sufficient for most Parallel Server Systems. Database Writer(DBWR_ + Database Writer process writes buffers to datafiles. + The primary job of the DBWR process is to keep the buffer cache “clean” by writing dirty buffers to disk. Log Writer Process(LGWR) + The Log Writer Process(LGWR) writer the redo log buffer to a redo fog file an disk, * LGWR writes one contiguous portion of the buffer to disk, LGWR writes a commit record when a user process commits a transaction. Recoverer Process(RECO) * The Recoverer process(RECO) is a process used with the distributed option that automatically resolves failures involving distributed transactions. * The remote server is not available or the network connection has not been re- established ,RECO automatically tries to connect again a timed interval. Checkpoint Process(CKPT) * When a checkpoint occurs, Oracle must update the headers of all datafiles vo record the details of the checkpoint, This is done by CKPT. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 -7 - Oracle Hg Material Cee Process Monit IN): ‘+ The process Monitor (PMON) performs process recovery when a user process fails. + PMON is responsible for cleaning up the cache and freeing resources that the process was using Ex; It resets the status of the active transaction table, release locks. Snapshot Refresh Processes(Snpn) + With the distributed option, up to ten Snapshot Refresh processes(SNPO,...SNP9) can automatically refresh table snapshots. + These processes wake up periodically and reftesh any snapshots that are scheduled to be automatically refreshed. ‘System Monitor(SMON) * The System Monitor. process(SMON) performs instance recovery at instance start up. + SMON is also responsible for cleaning up temporary segments that are no longer in use. Datafites. «This mandatory disk components is used for storing oracle dictionary and application database object. * Datafiles stores Oracle data. * Each datafile can be associated with only ane database. Redo Logs . ‘+ This mandatory disk components is used for storing redo infermation on disk. {ic rollback segment data). Control file + The Physical locations of both datafiles and redo logs in the server's files system are stored in your control files. Parameter Files(init.ora’ + This mandatory disk components is used for configuring how oracle operates while it is running . Sql * Plus Buffer: + SQL * Plus ORACLE has developed it’s environment tool. We can use directly SQL & PL/SQL statements in this environment tool. All commands of SQL are typed at the SQL prompt. Only one SQL Statement is managed in the SQL Buffer. The Current SQL statement replaces the previous SQL statement in the Buffer. + SQL statement can be divided into different lines within the SQL Buffer. * Only one line i,e., the current line can be active at a time in the SQL Buffer. + At SQL prompt, editing is possible only in the current SQL Buffer tine. + Every statement of SQL should be terminated Using(;}. + To run the previous or current SQL statement in the Buffer type’ at SQI. prompt. + To open the SQL Editor type ed at SQL prompt. * It provides. © SQL commands © PL/SQL block ‘i © It has own commands to set environment as reautirement. © To generate report. © To save SQL command as file(.sql) © Tosave PL/SQL command as file(.sq]) © To save output as file(.Ist) Naresh i Teeluologies, Opp. Satyom Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9900994008 y Oracle Lig Material reatin« Managing Tables: "A Oracle database can contain multiple data structures. «The different Database objects in Oracle are: TABLE: Used to store data, Sasic Unit VIEW: Logically represent subsets of data from one or more tables. ‘SEQUENCE: Used to Generate Primary Key values. INDEX: It is used to improve the performance of some queries. SYNONYM: Used to give alternate names to objects. Table in Oracle: + Table can be crated at any time, even when the users are using the database. «Size of the table need not be specified. For create table: 1)Table Name 2)Column Name 3)Data Type Table Restriction: + The user should have permission or CREATE TABLE command, and storage area, + Table name must be unique in schema «The Table name should begin with a letter and can be 1-30 characters long + Maximum 1000 calumns(8.0), 256 in 7.x * Names can contain: eA Z a — 2 0-9 $F + Names can not be duplicated for another object in the same ORACLE Server. «Name cannot be oracle server reserved words. * Names are not case sensitive, COLUMN NAME: ~The column name should begin with a letter and can be 1-30 characters long, + Column name is Unique in a table. + Column name can be renamed, + Maximum columns in table is 1000. Data Types in Oracle: * Each value in ORACLE is manipulated by a data type, + The values of one data type are different from another data type. ‘+ The data type defines the domain of values that each column can contain. "The Built-in-data types af ORACLE are Categorized as CHARACTER Data Types NUMBER Data Types LONG and RAW Data Types DATETIME Data Types ROWID Data Types Character Data Type: ‘They store character data which can Alphanumeric data. * The Information can be © Words Database Character set © National Character set They are less restrictive than other data types an have very few properties, + They data is stored in strings with byte values + The different character data types are: CHAR NCHARVARCHAR VARCHAR2 NVARCHAR2 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008» 9- Oracte Lig Material Dai t * It specifies fixed length character string. "The size should be specified. * If the data is less than the original size, blank pads are applied. * The default length is 1 Byte and the Maximum is 2000 Bytes. NCHAR Data Type: "Its first defined in ORACLE 9i, and contains Unicode data only. * The column's maximum length is determined by the National Character set definition. * The Maximum size allowed is 2000 Bytes and size has to be specified. * If the data short than the actual size then the blank pads are applied Varchar2 Data Type: - * A data type used for storing text data. + The Minimum size is 1 Byte and the Maximum size is 4000 Bytes. + It occupies only that space for which the data is supplied. + Any text character (including special characters, number, dashes, and so on) can be stored. Iv 2 Data Type: «tis first defined in ORACLE 9i, and contains Unicode data only, + The Minimum size is 1 Byte and the Maximum size is 4000 Bytes. Number Data Type: Number(Precision, Scale) + Number data type stores the numeric data, the precision is the total nc of digits required and scale stands for the rounding of decimal place. + Range of precision is from 1 to 38. + Range of Scale is -84 to 127. Integer Data Type: * Integer data type will converted as Number Data type with the maxim size 38 digit as precision . LONG: "This data type is used to store characters or numbers. + Maximum size limit is 2 GB. * only one Long column is valid per table. Date & Time Data Type: «Its used to store dates and time information. + The information revealed by date is: *Century —*Year *Month *Date *Hour *Minute — *Second «The default date format in ORACLE is DD-MON-YY. + The default time accepted by ORACLE date is 12:00:00 AM(Midni:ht), * The default date accept by ORACLE data is the First day of the Current month, + The Date range provide by Oracle is JANUARY 1,4712 BC to DECEMBER 31,9999 AD, estamp Date Type: + Itis an extension of the DATE data type. + Ttstores *Day *Month = *Year = *Hour *Minute . —*Seco nd Naresh i Technologies, Opp. Saiyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 10- Oracle Lig Material Syntax: TIMESTAMP(Fraciional-Seconds-Preci «Fractional -Seconds-Precision optional specifies the number of digits in the. fractional part of the SECOND datetime field, «= Itcan be a number in the range of 0-9, with default as 6. It stores binary information like Photos, Signature, Thumb impressions ect. Maximum length is 2000 Bytes. ‘The Oracle converts the RAW and LONG RAW data into Hexadecimal form. Each Hexadecimal character represent four bites of RAW data. + It stores the binary data similar to RAW but can store-more bytes than RAW, + Maximum length is 268. "No size is required. Large Object(LOB) Data Types: The Built in LOB data types are *BLOB *cLoB *NCLOB + These data types are stored inerally. + The Bfile is an LOB which is stored externally. ‘+ The LOB data type can store large and unstructured data like Text, Image, Video and Spatial deta. © The maximum size is upto 4GB. * LOB columns contains LOB locators, Which can refer to out-of-line to or in-line LOB values. + _LOB's selection actually return the LOB’s locator. BEILE Data Typ + Ttenables access to binary file LOB's which are stored in the systems outside ORACLE. + A BFILE column or the attributes stores the BFILE locator. + The BFILE locator maintains the directary alias and the filename. ‘+ The Binary File LOB’s do not participate in transaction and are not recaverable. + The maximum size is 4 GB. BLOB Data Type: + It stored unstructured Binary Large Objects, + They are Bit streams with no character set semantics. ‘+ They are provide with full transactional support. CLOB Data Type: + It Dynamic data type. + They are provide with full transactional support. + The maximum size is 4 GB. NCLOB Data Type: + Ie stores Unicode data using the National Character set ROWID Data Type: * Each row in the database has as address. + The rows address can be queried using the pseudo column ROWID. + ROWIO's efficient support partitioned table and Indexes. Codd’s Rules:- Dr E.F.CODD’s listed 12 rules for relational databases In 1985. 1, The Relational data base management rule: + Arelational data base management system must use Only its relational capabilities to manage the information stared in the database. 2. The Information rule: * All information in relational database must be represented as values within columns in rows. + Pointers are variables that contain address of the memory location where the data is stored. ‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008. - 11 - Oracle 11g Material 3, The Guaranteed Access rule: + Every item of data must be logically addressable with tne help of a table name, primary key value and column name. 4. The Systematic Treatment of NULL value rule: + Arelational database must support the NULL value for representing missing or inapplicable data. 5. The Dynamic On-line catalog Based on the Relational Model Rule: «The structure of the data base should be represented at Logical level in a tabular form. + The representation of database structure as a collection of tables is known as catalog or data dictionary. 6, The_Comprehensive Data sublanguage rule: * An RDBMS support at least one clearly defined language that can be used interactively as well as can be embedded in programs.(SQL). 7. The view updating rule: * All theoretically updatable views must be updatable in table. 8. The High-Level insert Update and delete rule: +” The date retrieval from a relational database must be possible in sets that may comprise data from multiple rows or multiple tables. The physical Data Independence rule: + The database user need not known about the physical Implementation of data storage and retrieval. 7 10. The Logical Data Independence rule: +” The data base user's view of a data should not be effected by any change in the database tables.(Materialized view). 11, The Integrity Independence rule: +. Data integrity rules must be defendable in the relational database and should be stored in data dictionary, 12. The Distribution Independence rule: + The system must be able to access or manipulate the data that is distributed in other systems. 13. Non-subversion Rule: * If a database management system has a low level language, then it cannot be used to violate the integrity rules or constrains that have been expressed using a higher-level language. To Create Table: Syntax: Sql>Create Table (,......); Not ‘The character ';’ is the terminator for SQL statement. Example: Sql>Create Table Emp_det (_ Empno Number(4), Ename Varchar2(15), Job Varchar(15), Mgr Number(4), Hiredate Timestamp, Sal Number(6,2), Comm Number(6,2}, Ephoto BLOB, Deptno Number(2) ); Sql>Create Table Student_Det (StudNo Number(4), Frame Varchar2(15), Lname Varchar2(15), DOB Date, DO) Date, Fees Number(6,2),Gender Char ); Naresh j Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 2374666: 969994008 - 12+ Oracte 11g Material Inserting Data in Tabi * Arow is inserted into a table by.using INSERT command. * Rows can insert into a Table Views Base Table. A partition of a Table. A Sub Partition of a Composite Partition Table. An Object Table. ‘An Object View’s Base Table. coooe Inserting of data into a table can be executed in two ways. «Conventional INSERT. « Direct-Path INSERT. In conventional Insert statement, Oracle reuses free space in the table into which the data in being Insert and. Maintains Referential Integrity Constraints, In Direct-Path insert, Oracle append the insert data after existing data in the Table, the free space is not reused. Syntai SqI>INSERT INTO
[list of columns] VALUES(list of values); Sql> INSERT Into Student_Det Values (1001, ‘THOMAS’, 'SIEBEL’, '30-DEC-81', “02-JAN-91', 30000, "M’ ); * In this case the values should be provided to all the columns that exists inside the table, + The order of values declared in the Values clause should follow the original order of the columns in the table. The Character and Date type data should be declared in single Quotes. Number information can be applied normally. Inserting Data into Required Columns: 5 Sql> Insert Into Student_Det( StudNo, Frame, Lname , DOJ ) Values (1002, DAN’, ‘SMITH’, '12-JAN-09" ); * In this case the Order of columns declared in insert need not be the same as that of the original table order. ‘+ The data values in the values caluse should match with that of INSERT list. ~ + The columns not supplied with data are filled with NULL values, Until the NOT NULL constraint is declared. Inserting NULL values into Table: © Null represent information that is not available. + Nyll Value is “o Unknown value Undefined value Not equal to 0 or blank space represented with ‘NULL’ keyword. Not allowed arithmetic, relational operation on Null, If performed it return Null only. o RDBMS must support NULL Values. * NULL values can be inserted in two ways. © Implicit->Omit the columns from list oracle supplies NULL. values. © Explicit->Specify the NULL keyword. Sql>Insert Into Student Det ( StudNo, Fname, Lname, DOB, DOI, Fees, Gender ) Values ( 1003, ‘RAMA’, NULL, '12-JAN-81', NULL, 30000, 'M'); Naresh i Techuologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 ~ 13- Oracle 11g Material Inserting special Values into Table: | SYSDATE FUNCTION + SYSDATE is Pseudo-column. + This function return the current date& time. ISER FUNCTION: + This function returns the user name of the user who has logged in. Example: SQL>CREATE TABLE Student (Stuid Number(4),Name Clob,DOB Date,DOJ Date, Fees Number(8,2),Gender char); Example: ‘SqI>INSERT INTO student VALUES(1001 user,'01-JAN-85',sysdate,2000,'M'); ‘Substitution Variables: + These variables are used to stored values temporaily + The values can be stored temporarily through Single Ampersand(&) | Double Ampersand(&&) “DEFINE and ACCEPT Commands ‘+ The Single Ampersand substitution variable applies for each instance when the SQL statement is create or execute. + The Double Ampersand substitution variable applies for all instances until that SQL statement is existing, USING SINGLE AMPERSAND SUBSTITUTION VARIABLE: ‘Sql> INSERT INTO dept VALUES(&Dno,'&Dname’,'&Loc’); Sql> INSERT INTO emp(Empno,Ename,Hiredate,Deptno) VALUES (f&Eno,'&Ename’,'&Hiredate', &dno); S Note: To run command is used for executing a previous command... >run or >/ USING DOUBLE AMPERSAND SUBSTITUTION VARIABLE: SqI>INSERT INTO student VALUES(8Sid,'&Name’,'&Dob' ,&Doj, &8fee,’&Gender’); DEFINING CUSTOMIED PROMPTS: ‘Sql>ACCEPT Deptno prompt 'Please Enter the deptnumber Sql>ACCEPT Dname prompt 'Please Enter the Deptname: Sq!>ACCEPT Location prompt 'Please Enter the Location:’ Sql> INSERT INTO dept VALUES(&Deptno,&Dname,&Location); (CREATING AN .LST FILE: + The List file is used to save all information which performed in SQL *Plus 1)In SQL’* Plus Navigation: File>Spool->Spool File 2) Give the file name 3) Performed all tasks. 4) Now Spoo! Off. CREATING AN SQL SCRIPT FILE: ‘The SAVE Command is used to store the current contents of the SQL Buffer. Steps: 1)At SQL prompt type the full name of the path where the file bas to be created. 2)Give the name of the file with .sql extension. 3)If the has to be replaced with the same existing name then use REPLACE ALL clause, Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 4110994008 - 14 Oracle 11g Material eS Example: Sql>SAVE E:\nitdir\ins Sal> SAVE E:\nitdir\ins REPLACE To Get Script: - Get used to display the script file . ‘Sq!>Get E:\nitdir\ins ‘To Run Scrip! Run is used to display the script and run the file. SqI>RUN E:\nitdir\ins To simple the script file. Sql>@ E:\nitdir\ins To Open the Script file in editor ‘Sqi>ed E:\nitdir\ins Data Retrieval Languages‘ ‘DI je QUERY: It is an operation that retrieves data from one or more table or view. ‘SELECT Statement: ‘+ Select used to retrieve data from one or more than table ,view, object tables. + It is for read only purpose. + The select is the most frequently used command as access to information is needed all the time. PREREQUISTIES: + The user ust have the SELECT privileges on the specified object. CAPABILITES OF SQL SELECT STATEMENT: The different types SELECT criteria. © SELECT: a It chooses the rows in a table that are expected to return by a query. - + PROJECTION: © It chooses the colurnns in a table that are expected to return by a query + JOIN: © It chooses the data in from one or more numbers of tables. Pata Retrieving Languag ‘Syntax: Sql>SELECT *|{[DISTINCT/UNIQUE] column | expression [Alias],....} FROM table. SELECT identifies what columns, specifies a list of column(one/more) FROM identifies which table DISTINCE — >Suppress Duplicates. * Select all Columns Columns/ Expression >Select the Named Columns or the expression. Alias Gives select columns different headings WRITING SOL STATEMENTS TO SELECT DATA FROM TABLES. The sample table. 1)DEPT Column Name Data Type DEPTNO NUMBER DNAME VARCHAR2 (14) Loc VARCHAR2 (13) Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph : 23746666, 9000994008 - 15 - 2)EMP Column Name EMPNO ENAME JOB MGR HIREDATE SAL coMM DEPTNO 3)SALGRADE Column Name GRADE LOSAL HISAL Dep! SQL> Select *From Dept; DEPTNO DNAME 10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS SQL> SELECT * FROM MY_EMP; EMPNO ENAME JOB MGR 7369 SMITH CLERK =—-7902 7499 ALLEN SALESMAN 7698 7521 WARD SALESMAN .7698 7566 JONES © MANAGER 7839 7654 MARTIN SALESMAN 7698 7698 BLAKE © MANAGER 7839 7782 CLARK = MANAGER 7839 7788 SCOTT ANALYST _ 7566 7839 KING PRESIDENT 7844 TURNER SALESMAN 7698 7876 ADAMS CLERK 7788 7900 JAMES CLERK_—-7698 7902 FORD = ANALYST 7566 7934 MILLER CLERK 7782 14 rows selected. SQL> Select *From Salgrade; GRADE LOSAL 1 700 1200 2 1201 1400 3 i401 2000 4 2001 3000 5 3001 9999 HISAL Oracle 11g Material Data Type NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7,2) MUMBER(7,2) NUMBER(2) Data Type NUMBER. NUMBER NUMBER Loc NEW YORK DALLAS CHICAGO BOSTON HIREDATE © SAL COMM DEPTNO 17-DEC-80 800 20 20-FEB-81 1600 300 30 22-FEB-81 1250 500 30 02-APR-81 2975 20 28-SEP-81 1250 1400 30 O1-MAY-81 2850 30 09-JUN-81 2450 10 09-DEC-82 3000 20 17-NOV-81 5000 10 08-SEP-81 1500 0 30 12-JAN-83 1100 20 03-DEC-81 950 30 03-DEC-81 3000 20 23-JAN-82 1300 10 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph : 23746666, 9000994008 - 16 - c Oracle 11g Materiat ES etrieving Data from All Columns: ‘Sql>SELECT *FROM Emp; Sql>SELECT *FROM Dept; Sql>SELECT *FROM Salgrade; * In this the '*’ is a projection operator. + It project data from all the columns existing in the table with all records, + The data is displayed in a table format. Retrieving Data from Specific Columns: ‘Sql> SELECT empno, ename, job, sal. FROM Emp; Sq!>SELECT toc, dname, deptno FROM Dept; Sql> SELECT Hisal,Losal,Grade FROM Saigrade; + The columns names need not be in the same order as table. + The columns should be separated using comma. + The column names can be separated into different lines within the ‘SQL Buffer. + The casing of coluinn names is not important. wh He ling Default: «The default justification of the data after it is retrieved from the table is... LEFT >Date and Character RIGHT Number Data « The default Columns Heading display in UPPER case : Applying Arithmetic Operations in Select Statements: ¢ Arithmetic Expressions can be implemented through SELECT statement. + Arithmetic Expressions can be implemented to o Modify the way the data is displayed. © Perform calculations. ADA metic Expression can contain: * Simple columns names: * Constant numeric values * Arithmetic operators. ARITHMETIC OPERATORS: + The Arithmetic operations can be used to create expressions on NUMBER and DATE data, + The Arithmetic operators supported are... o + Addition © => Subtraction © *9 Multiplication of > division. +The Arithmetic operators can be used in any clause of a SQL statement. except the FROM clause. + SQL * Plus ignores Blank Spaces before and after the Arithmetic operator. Sql> Select empno,ename,sal,sal+500 FROM Emp; Sql> Select empno,ename,sal,sal-1000 FROM Emp; Operator Precedence: * Multiplication and Division take priority over addition and subtractions(*/+-) + Operators of the same priority are evaluated from left to right. © To prioritize evaluation and to increase clarity parenthesis can be implemented. Sql> Select empno,ename,sal, 12*sal+100 from Emp; Sql>Select erpno,ename,sal,(12*sal) +100 from Emp; Sql>Select empno,ename,sal,12*(sal+500) fram Emp; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 17 Hal Ni es: NULL: Unknown value Undefined value Not equal to 0 or blank space. If @ row lacks the data for a particular column, than that value is said to be NULL or to contain NULL. + It represented with NULL keyword + No operations allowed on Null,/ if performed any arithmetic operations it return nul! only). + RDBMS must support NULL Values. ‘Sql>Select ename,job,sal,comm from emp; Sql> Select ename,job,sal,comm,12*sal+comm from emp; ener: inction: This functions work with any data type and pertain to using null value. NVL Function: ‘© The NVL function is used to convert a NULL value to an actual value. ‘Syntax: NVL(Exprl,Expr2) Expri: is the source value or expression that may contain NULL. Expr2; is the target value for converting NULL. NVL Conversions Data © NVL(Number_column, 6) © NVL(date_column, ‘01-JAN-09') © NVL(Character_column, "Unavailabie’) Note : If Expri is Character data then Expr2 may any Data type. ‘Sql>Select NVL(100,200) from dual; ‘Sqi> Select NVL(null,200) from dual; Sql> Select ename,sal,comm,sal+NVL(comm,0) from emp; Sql> Select ename,sal,comm,(sal*12)-+NVL(comm,0) from emp; Sql> Select ename,sal,comm,(sal+500)+NVL(comm,0) from emp; NVL2 Function: Syntax: NVL2(exprt expr2,expr3) © Ifexpri is aot null, NVL2 returns expr2.if expr is null, NVL2 returns expr3. Expr may any data type. ‘0 The data type of the return value is always the same as the data type of expr2_, unless Expr2 is character data . Example:- 1) select nvl2(comm,0,1000) from emp; 2) select sal,comm, sal+nvi2(comm,100,2000) from emp; SQL>select ename,sal,comm, nvi2(comm,'sal+comm’,'sal’) income from emp where deptno in(10,30); NULLIF Function: ‘Syntax NULLIF(expri,expr2) © Compares two expressions and returns null if they are equalor the first if there ate not equal. Example: sql>SELECT NULLIF(100,200) from dual; sql>SELECT ENAME,LENGTH(ENAME) “expri", JOB,LENGTH(JOB) "expr2", NULLIF(LENGTH(ENAME),LENGTH(JOB)) result from emp; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph; 23746666, 9000994008 - 18 - Oracle 11g Material Note: © The data type of the expri is same as the data type of expr2. o The NULLIF function is logically equivalent to CASE expression. COALESCE: ‘« It return first non-null expression ih the expression list. ‘Sql> SELECT coalesce(100,600,200) FROM dual; Sql> SELECT coalesce(null,600,200) FROM dual; Sql>SELECT Ename,Deptno,COALESCE(COMM,SAL,10) COMM FROM EMP OCP Questions : 1) The EMPLOYEE tables has these columns: LAST_NAME VARCHAR2(35) SALARY NUMBER(8,2) COMMISSION_PCT NUMBER(5,2) You want to display the name and annual salary multiplied by the commission_pct for all employees. For records that have a NULL commission_pct, a zero must be displayed against the calculated column, Which SQL statement displays the desired results? A, SELECT last_naize, (salary * 12) * commission_pct FROM EMPLOYEES; B. SELECT last_name, (salary * 12) * IFNULL(commission_pct, 0) FROM EMPLOYEES; C. SELECT last_name, (salary * 12) * NVL2(commission_pct, 0) FROM EMPLOYEES; D. SELECT last_name, (salary * 12) * NVL(commission_pct, 0) FROM EMPLOYEES; Defining a Column Alia : ‘+ An Alias is an alternate name given for any Oracle Object. * Aliases in Oracle are of two types. *Column Alias *Table Alias Column alias rename a Column Heading. * Alias Headings appear in uppercase By default. * Specify the alias after the column in the SELECT list using a space as a separator, + AS keyword between the column name and alias is optional. ‘+ The Alias contains spaces or special characters (such as # or $), or is case sensitive, enclose the alias in double quotation marks (" "). + Analias cannot be used, any where in the SELECT list for operational purpose. + Analias effectively renames the SELECT list item for the duration of the Query, Sql> SELECT Empno EmpNumber, Ename EmpName, Sal “EmpSalary” Job Designation FROM Emp; Sql> SELECT Grade AS “SalGrade", —_Hisal “High Salary Range", Losal “Lower Salary Range” From Salgrade; Sql> Select empno “EmpNumber", Sal “Basic’Sal*0.25 HRA, Sal*0,20 DA,Sal*0.15 "Pf", Sal+Sal*0.25+Sal*0.20-Sal*0.15 “Gross” FROM em| * The Concatenates operator concatenate columns or character strings or expressions or constant to other values or columns. * Is represented by two vertical bars (/|)- » The resultant column that is a character . Sql> SELECT empno||ename FROM Emp; : Sql> Select 'The Basic Salary of ‘||Ename|| ‘is Rs '||Sal Employee From Emp; Sql>Select Empno| |Ename||Ename||" ,Designation is ‘||job “Employees Information " From Emp; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 19- ' Oracle 11g Material ———————————————— LITERALS IN ORACLE: ‘+ A Literal and Constant value are synonyms to one another and refer to a fixed data value, + The types of Literals recognized by Oracle are Text Literals o Number Literals o Interval Literals Text Literals: It specifies a text ot character literal. It is used to specify values whenever ‘text’ or CHAR appear in *Expression *Condition *SQL Function * SQL Statements. + should be enclesed' in single quotes. + Atext literal can have a maximum length of 4000 Bytes, Example: ‘Employee Information’ ‘Manager's Specification’ ral Cl cter Strin: + Aliteral value is a character, a number, of a date that is included in the SELECT list. * Aliteral value not a column name or a column alias. * Aliteral is printed for each row returned, that is retrieved by the SELECT ‘statement, . Literal strings of free-format text can be included in the query. A free-format text treated the same as a column in the SELECT list. Date and character literal must be enclosed within the single quotation marks *". Litera} increase the readability of the output. Sql>Select Ename ||":'|| ‘Month Salary="|| Sal As Salaries From: Em; ‘Sqi>Select ‘The Designation of ‘|| Ename || is ‘|| job As Designation “rom Emp; Sql> Select ‘The employee name is: ‘|/Ename||' and *}]'Designa‘'on is :'{Liob from Emp; Sql> Select "The Annual Salary of ')\Ename|| is ‘||Sal*12 As Annual_ Salary From Emp; Sql> Select Dname||'Department is Located at ‘||Loc From Dept ; Sql> Select Ename| |" Joined the Organization on *}{ Hiredate Fram Emp; Sql> Select Ename||' Works in Department Number '||Deptno||" as ‘ ||job From Emp; Sql> Select ‘The Employee Name is: *||Ename||, Designation is *}}»b FROM Emp; Sql> SELECT 'The Gross salary of ‘jjEname\{' is '{{(Sal+Sal*.254S= °.20- Sal*,15) FROM Emp; Duplicate Rows: + Unless we indicate otherwise, iSQL*Plus displays the results c’ - query without eliminating duplicate rows. + To eliminate duplicate rows in the result, the DISTINCT keywe- . used. + We can specify multiple columns after the DISTINCT qualifier + The DISTINCT qualifier affects ail the selected columns, and — esult is, every distinct combination of the columns. Sql>Select DISTINCT Job From Emp; Sql> Select DISTINCT Job,Deptno From Emp; Sql>Select DISTINCT Deptno,Job From Emp; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90. '208. = 20- Gracie ig Material iter Of Re The number of rows returned by a query can be limited using the WHER clause, ‘+The method of restriction is the basis of the WHERE clause in SQL. + A WHRE Clause contains a condition that must be met and should directly follow the From Clause. SqI>SELECT *|{{DISTINCT] columnjexpression [alias],...} FROM table [WHERE condition(s)}; «The WHERE clause can compares ‘© Values in Columns © Literal Values o Arithmetic Expressions © Function ‘+ The components of WHER clause are © Coiumn Name 0° Comparison Operator © Column Name, constant or list of values. «The Character strings and dates should be enclosed in single quotation marks. «Character values are case sensate and Date vaiues are format sensitive (DD-MON-YY) «The Comparison operator are used in conditions that compare one expression to another. Relational Or_Coniparison operators: F< > AEST DEES Example: Sql>SELECT empno, ename, job, sal from emp; Sql>SELECT loc, dname, deptno from dept; Sql>SELECT * from emp; Sql>SELECT * from students; SqI>SELECT * from emp WHERE deptno=10; Logical Operators: « A togical condition combines the result of two component conditions to produce a single result, * Three logical operators are available in Oracle. AND OR NOT ND Operator: ‘* The AND operator allows creating an SQL statement based on two or more conditions being met. «It Returns FALSE if either is FALSE, else returns unknown, Truth Table: AND TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE Exampl Sql> Select Ename,Sal,Job Emp Where (Sal>=1500 AND Sal<=5000) AND Job="MANAGER’; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 21 - Ig Material ————————————————— OR Operator: ‘It return TRUE if either component conditions is TRUE. « Itreturns FALSE if both are FALSE, else return unknown. ‘Truth Table: OR TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE TRUE FALSE FALSE FALSE Sql>Select Empno,Ename,Sal,Deptno From Emp Where Sal>=2000 OR Deptno=20; Sql>Select Empno,Ename,Job,Hiredate From Emp Where Job=’MANAGER’ OR Deptno=30; Sql>Select Empno,Ename,Job,Deptno From Emp Where. (Deptno=10 OR Deptno=20) OR JOB="MANAGER’; Sql> Select Ename,Job From Emp Where (Job="CLERK' or Job='SALESMAN’ or ob='ANALYST'); Sql> Select Ename,Hiredate,Deptno From Emp Where Job=’MANAGER’ OR Deptno=30; Sql>Select Ename,Sal,Job From EmpWhere (Sal<=2500 OR Sal>=5000) 01 MANAGER’; NOT Operator: «It returns TRUE if the following condition is FALSE. * It returns FALSE if the following condition is TRUE. If the condition is Unknown, it returns Unknown. Combination of AND OR Operator Jol Sql> Select Ename,Sal From Emp Where (Job='CLERK' or Jot ‘And Sal>3000; ‘PRESIDENT’ or Jol ANALYST’) Sql> Select Empno,Ename,Job,Sal From Emp. Where (Sal>1500 OR Job='MANAGER') AND Deptno=10; Sql> Select Empno,Ename,Job,Sal From Emp Where (Deptno=20 OR Job='MANAGER’) AND Sal>=3000; Not Operator Example: Sql> Select Empno,Ename,Job,Sal From Emp Where NOT Ename='SMITH'; Sql>Select Empno,Ename,Jeb,Sal From Emp Where NOT Sal>=5000; Sql> Select Empno,Ename,Job,Sal From Emp Where NOT Job='CLERK'; Sql> Select Empno,Ename,Job,Sal From Emp Where NOT Sal<=5000; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hytlerabad, Phi: 23746666, 9000994008 - 22- ‘Sql> Select Empno,Ename,Job,Hiredate From Emp Where NOT Hiredate='17-DEC-80; Sql> Select Empno,Ename,Job,Hiredate From Emp Where NOT JOb="CLERK’ AND Deptno=20; Some Things To Note: Sql» Select Ename,Sal,Job From Emp Where Job>'CLERK'; Sql> Select Ename,Sal,Job From Emp Where Job<'CLERK'; ‘Sqi> Select Ename, Deptno,Hiredate From Emp Where Hiredate>'20- DEC-81'; Sql> Select Ename,Deptno,Hiredate From Emp Where Hiredate<'20- DEC-81'; Sql> Select Ename,Job,Hiredate From Emp Where Job*='CLERK’; Sql> Select Ename,Job,Hiredate From Emp Where NOT Job*= "CLERK; Sql> Select Ename,job, Hiredate From Emp Where NOT Job='CLERK'; Sql> Select Ename,Job,Hiredate From Emp Where NOT Hiredate='17-DEC-1980'; Sql> Select Ename,Job,Hiredate From Emp Where NOT Hiredate>'L8-DEC-1981'; Rules of Precedenc © The default Precedence order is All comparison operators NOT logical condition AND logical condition OR logical condition oo00 Note: * Override rules of precedence by using parentheses. Example: Sql> SELECT Ename,Job, SalFROM Emp WHERE Job = ‘CLERK’ OR Job = 'MANAGER' AND Sal> + Sql> SELECT Ename,Job, Sal FROM Emp WHERE (Job = 'CLERK' OR Job = 'MANAGER’) AND Sa!~ L_*Plus Operat: + BETWEEN .... AND.....; NOT BEWEEN ....AND.... + BETWEEN js used to o display rows based on a range of vz + The declared range is inclusive. + The lower limit should be declared first. Sql>Select Empno,Ename,comm. From Emp Where Comm, Between 500 AND 1000; ———— Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: Oracle 11g Material ————$—$—$—$—_[_$—[{—_—[—~_—_${_ {_{_—————————————————— Sql>Select Ename,Sal,Job From Where Sal NOT Between 1000 AND 1500; Sql?Select Ename,Sal,Job From Emp Where Job Between ‘MANAGER’ AND ‘SALESMAN’; Sql>Select Ename,Sal,Job From Emp Where Job NOT Between "MANAGER’ AND ‘SALESMAN’; sql>Select Ename,Sal,Job,Hiredate From Emp Where Hiredate Between '17-FEB-1981' AND '20-JUN-1983'; sql>Select Ename,Sal,Job,Hiredate From Emp Where Hiredate NOT Between '17-FEB-1981' AND '20-JUN-1983'; |OT IN Operator: + The Operator is used to test for values in a specified list. «The Operator can be used upon any datatype. Sql>Select Ename,Sal,Job From Emp Where Ename IN(FORD'/SMITH’); Sql>Select Empno,Job,Sal From Emp Where Ename NOT IN(FORD‘/SMITH’); Sql>Select Ename,Sal,Deptno From Emp Where Deptno IN(20,30); Sql>Select Ename,Sal,Deptno From Emp Where Deptno NOT IN(2C -~); Sql>Select Ename,Sal,Deptno From Emp Where Hiredate IN('20-FEB-1981'/09-JUN-1981'); Sql>Select Euame,Sal,Deptna From ‘Emp Where. Hiredate NOT IN(‘20-FEB-1981'/09-JUN-1981 ; LIKE Operator: NOT LIKE Operator: Use the LIKE condition to perform wildcard . ‘The LIKE Operator searches of valid search string values. Search conditions can contain either literal characters or numbers. The available wild cards are % - Itis represent any sequence of Zero or more character. _>Represent any single character, only at that position only, +The Wild Card symbols can be used in any combination with literal « .sracter. + For finding exact match for ‘%’ and '-' the ESCAPE option has to be » sed, which is ‘Y' symbol with ESCAPE option. SqI>SELECT Empno,fname From Emp Where Ename LIKE 'M%'; Sql> SELECT Empno,Ename From Emp WHERE Ename NOT UKEM%; ‘Sql>SELECT Empno,Ename From Emp WHERE Ename LIKE '_O%'; ‘Sql> SELECT Empno,Ename From Emp WHERE Ename NOT LIKE *_0%'; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90994008 - 24- Oracle 11g Material Sql> SELECT Empno,Ename From Emp WHERE Ename LIKE 'SM%'; ‘Sql> SELECT Empno,Ename,Job From Emp WHERE Job LIKE ‘____'; Sql> SELECT Ename,Hiredate From Emp WHERE Hiredate LIKE '%-FEB-1981'; Sql> SELECT Ename,Hiredate From Emp WHERE Hiredate LIKE “%JAN%"; ‘Sql> Select *From Dept Where Dname LIKE '_-\_%' ESCAPE (update dept set dname='SO_FT_WARE’ where deptno=50;) IS NULL Oper: yT NULL Opera’ * The Operator tests for NULL values. + Its the only operator that can be used to test for NULL’s. « NULL value means the value is unav ailable, unassigned, unknown, or inapplicable, SqI>SELECT Ename,Deptne,Comm From Emp WHERE Comm IS NULL; SqI>SELECT Ename,Deptno,MgrJob From Emp WHERE Mgr IS NULL; Sql> SELECT Ename,Deptno,Comm From Emp WHERE Comm>=0; Sq!>SELECT Ename,Deptno,Comm From Emp WHERE Comm IS NOT NULL; Sql>SELECT Ename,Deptno,Comm From Emp WHERE Mgr IS NOT NULL; ORDER BY Claus + The Order of rows returned in a query result is undefined, The ORDER BY clause can be used to sort the rows, ‘The ORDER BY clause must be the last clause of the SQL statement. An expression, or an alias, or calumn position as the sort condition. Default ordering of Data is Ascending. "Number 1-999 **Dates Earlist-Latest **String A-Z;NULLS Last. + Syntax: SELECT expr FROM table (WHERE condition(s) } [ORDER BY {column, expr} [ASC|DESC)]; + The default order upon column is Ascending, to change the default ordering DESC should be used after the column name. + Sorting can be implemented on column aliases and can also be implemented upon multiple columns. Sql>Select Ename,Job,Sal,Deptno From Emp ORDER BY Sal; Sq!>Select Ename,Job,Sal,Deptno From Emp ORDER BY Sal DESC; Sql>Select Ename,Job,Sal,Deptno From Emp Where Job=‘CLERK’ ORDER BY Sal; Sql>Select Ename,Job,Sal,Deptno From Emp Where Sal>=2000 ORDER BY Deptno,Ename DESC; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 25- Oraclé 11g Material Sql>Select Ename,Job,Sal,Sal*42 Annsal From Emp ORDER BY AnnSal; Sql>Select Ename,Job,Sal, Deptno From Emp ORDER BY Deptno,Job,Sal ; Sql>Select Ename,Job,Sal,Deptno From Emp ORDER BY 2 DESC; Sql>Select * From Emp ORDER BY 5 DESC; The single row functions can appear In: **SELECT List **WHERE List *#Start With Clause **CONNECT BY Clause The types of single row functions are ** CHARACTER “NUMBER. **DATE _- **CONVERSION Multiple Row Functions: + These function manipulate group of rows to give one result per group of rows. They are used to manipulate data items, «© They accept one or mare arguments and return one value far each raw returned by the query. + An argument can be User-supplied constant © Variable value © Column name o Expression Syntax: Func_Name(Column/Expr, [Arg1,Arg2,...-]) Features of single-row functions include: ‘Acting on each row returned in the query. Returning one result per row. Returning a data value of a different type than that referenced, Expecting one of more arguments, Can be used in SELECT, WHERE, and ORDER BY clauses. Can be nested. Specification Behavior of Function; + Character functions: Accept character input and can return both character and . number values, + Number functions: Accept numeric input and return numeric values. + Date functions: Operate on values of the DATE data type (All date functions return a value of DATE data type except the MONTHS_BETWEEN function, which returns a number.) + Conversion functions: Convert a value from one data type to another. ‘General functions: o NVL o NVQ co NULLIF © COALSECE o CASE o DECODE Naresh i Technotogies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90 994008 - 26- Oracle 11g Material —— Character Functions: + They return the data type VARCHAR2, limited to a length of 4000 Bytes. + If the return value length exceeds, then the return value is truncated, without an error. * Functions can be divided into Case-manipulation functions. © Character-manipulation functions. Character Function Purpose; LOWER(column|expression) * It converts alpha character values to lowercase . + The return value has the same data type as argument char type(CHAR or VARCHAR2) Syntax: LOWER(column | xpression) Sqi>Select LOWER( NARESH I TECHNOLOGIES ") From Dual; Sql>Select Ename,Job,LOWER(MY DATA’) From Emp; Sql>Select Ename,LOWER(Ename) From Emp Where Deptno=10; Sqi> Select The 'IiEname || "s Designation is ‘|| Job. from EmpWhere LOWER(Job)="manager’ pper Function: + Tt Converts the Alpha character values to Upper Case, + The return value has the same data type as the argument char. Syntax: UPPER(Column | Expression) Sq!> Select Upper{’Naresh’ i Technolagies ") From Dual; $q!>Select Ename,Job, Upper (‘My Data’) From Emp; Sql>Select Ename,Job, Upper (Ename), Upper (Job) From Emp Where Deptno=20; Sql> Select Ename,Job From Emp Where Job=Upper(*Manager’); Sql> Select Upper('E.F Codd’) "Capitalised" From Dual; Sql>Select ‘The "||Ename jj ""s Designation is '{| Lower(Job) From Emp Where Job=Upper(‘managet’} Order by Sal; Sql> Select Upper("The '||Ename|| ' Basic Salary is "||Sal) "Emp Salaries" ,Job From Emp Where Job In(Upper('Manager'),Upper(‘clerk’)) Order by Sal Desc; INSTCAP Function: © It returns a string with the first letter of each word in upper case, keeping all othered «letters in Lower case, Sql> Select initcap(Ename) From emp; Sal> Select Initcap(‘naresh i technologies ") From Dual; Sql>Select ‘The Job Title for'{{Inticap(Ename)||" is'|] Lower(Job) ‘Details From Emp; Sql>Select Ename,Upper(Ename), Lower(Ename),Initeap(Ename) From Emp; Sql>Select Empno,Initcap(Ename),Deptno From Emp — Where Ename=Upper(‘ford’); CONCAT Function: + It Concatenates the first characters value to the second character value. Only two parameters accept. + Itreturn the character data type, Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph; 23746666, 9000994008 - 27 Oracle 11g Material Syntax: CONCAT (Columni/Exp1, Column2/Exp2) ‘Sql>Select Concat(‘Oracle’,/Naresh Technologies’) From Emp; Sql>Select Ename,Job,Concat(Ename,Job) From Emp Where Deptno=: Sql> Select. Concat(Concat(Ename,Job),Sal) From Emp; Sql> Select Concat("The Employee Name is',Initcap(Ename)) As "Employee Names " From Emp Where Deptno in(10,20); Sql>Select Concat(Concat(Initcap(Ename),'is a’),Job) Job From Emp Where Deptno in(10,20); Sql>Select Concat(‘aFname’,’&Sname’) "Full Name” From Dual; 0; ‘SUB STRING Function: «Returns specified characters from character value, string from a specified position ‘m’ to 'n’ characters long. + To extract the portion of the string it is mainly used. Points to Remember. * If mis 0, it is treated as 1. * If mis positive, Oracle counts from the beginning of char to find the first character. If n is Omitted, Oracle returns all characters to the end of char. If nis less than. 1 or 0, A null is returned.Floating points numbers passed as arguments to substr are automatically converted to Integers. ‘Syntax: SUBSTR(Col/Exp,m,[n]) C>char to be searched. M> Starting position . N> Occurrence Number, Sql> Select Substr(‘SIVA RAMA KRISHNA’,1,4) From Dual; ‘Sql> Select Substr('SIVA RAMA KRISHNA’,6,4) From Dual; ‘Sqi>Select Substr('SIVA RAMA KRISHNA',11) From Dual; Sql>Select Substr('SIVA RAMA KRISHNA’,-7) From Dual; Sql> Select Substr('SIVA RAMA KRISHNA',-12,4) From Dual; Sql> Select Substr('SIVA RAMA KRISHNA',-12,4) From Dual; Sql> Select Ename,Job From Emp Where Substr(Job,6)=Upper(‘men'); Sql>SelectConcat(Initcap(Ename),Concat('is a ‘,Concat(Initcap(Substr(Job,1,3))," Eater.'))) From Emp Where Substr(Job,4,3)=Upper(’Age’); LENGTH Function: + Returns the number of characters in a value, + If the char has data type CHAR, the length includes all trailing blanks. * Ifthe char is NULL, if retrun NULL. Syntax: LENGTH(Column|Expression) Sql> Select Length(’E.F CODD’) From Dual; Sqi> Select Length(Ename)||' Characters exists in ‘|[Initcar’“name)||' "'s Name.'As "Names and Lengths " From Emp; Sql>Select Initcap(Ename),Job From Where Length(Ename)=5; Sal> Select Initcap(Ename),Job From Emp Where Substr(Job,4,Length(Substr(Job,4,3)))='AGE'; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666," 994008 -28- ‘ Oracle 11g Material Real Time flo INSTRING Function: + It returns the numeric position of a named character. ‘Syntax: INSTR(Column | Expression, ‘C’, [,m], [n] ) Searches for Column / Expression beginning with its ‘n’th character for the 'm’ th occurrences of character ‘C’, and return the position of the character , + ‘m’ can be positive or negative, if negative searches backward from the end of Column / Expression. + The value of 'n’ should be positive. * The default value of both ‘m’ and ‘n’ are 1. ‘+ If search is unsuccessful, the return value is zero. ‘Sql> Select Instr('SIVA RAMA KRISHNA’,'A',1,1) From Dual; Sql> Select Instr(’SIVA RAMA, KRISHNA’,‘A',17,2) From Dual; Sql> Select Instr('SIVA RAMA KRISHNA','MA',7,1) From Dual; Sql> Select Instr('SIVA RAMA KRISHNA’/'A',-1,1) From Dual; Sql> Select Instr(Job,'A’,1,2) From Emp Where Job="MANAGER’; Sql> Select Instr(3ob,'A',2) From Emp Where Job='MANAGER’ Sql> Select Instr(Job,'A’) From Emp Where Job="MANAGER'; LPAD Function: . + Pads the character value right-justified to a total width of n character positions. «The default padding character is space. Syntax: LPAD(Column | Expression, n, ‘C') «Fill extra spaces with char ‘C’ up to'n’ position on left side. Sql> Select Lpad('Page 1',20,'*) From Dual; Sql> Select Lpad('Page 1',20) From Dual; Sql> Select Lpad(Ename,20,'@") From Emp Where Deptno=10; RPAD Function Pads the character value left-justified to a total width of n character positions. ‘+ The default padding character is space. ‘Syntax: RPAD(Column | Expression, n, 'C’) Sql> Sal> Select Rpad('Page 1',20,"*") From Dual; Sq\> Select Rpad('Page 1',20) From Dual; Sql> Select Rpad(Ename,20,'@") From Emp Where Deptno=10 Sql>Select Ename,Lpad(Ename, 10),Rpad(Ename, 10, Deptno=10; Sql> Select Ename,Lpad(Rpad(Ename,10,'-"),15,'-') From Emp FromEmpWhere Real Time Scenario: . TRIM Function: * It enables to trim heading character from a character string. + All the left most characters that appear in the set are removed. Syntax: LTRIM(Char,Set) Sql> Select Ltrim(’xyxyORACLE 10g','xy') From Dual; Sql> Select Ltrim('MM KRISHNA','M') From Dual; RTRIM Function: + Itenables to trim heading character from a character string, + All the right mest characters that appear in the set are removed. —————————————————— Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 29 - rach: 1g Material Syntax: RTRIM(Char,Set) Sai> Select Rtrim(‘ORACLE 10gxyxy','xy') From Dual; Sql> Select Rtrim(’KRISHNA AAA\,‘A’) From Dual; Sql> Select Rtrim(Job,ER'),Job From Emp Where Ltrim(Job,'MAN') Like ‘GER’; TRIM Function: + Trims heading or trailing characters (o* both) from a character string. + If trim_character or trim_source is a character literal, you must enclose it in single quotes. If Leading is specified concentrates on leading characters. If Trailing is specified concentrates on trailing characters. If Both of none is specified concentrates both on leading and trailing. Returns the varchar2 type. ‘Sql> Select Trim( 'S' From 'MITHSS') From Dual; ‘Sql> Select Trim( 'S' From 'SSMITH') From Dual; Sql> Select Trim( 'S' From 'SSMITHSS') From Dual; Sql> Select Trim(Leading 'S"From 'SSMITHSS') From Dual Sql> Select Trim(Trailing 'S' From 'SSMITHSS') From Dual; Sql> Select Trim(Both 'S' From 'SSMITHSS') From Dual; REPLACE Function: + Tt return the every Occurrence of search string replace by the replacement string. = If the replacement string is omitted or null, all occurrences of serch string are removed + If substitutes one string for another as well as to remove character strings. Syntax: REPLACE(text,Search_string, [Replacement_string]) Sql> Select Replace('Led',’L','R’) From Dual; Sql> Select Replace('Led’,'L!,'Ra') From Dual; . Sql> Select Replace('Led’,‘Le','R') From Dual; Sql> Select Ename,Replace(Job,’MAN’,'DAM') From EmpWhere Job='MANAGER'; Sql> Select Job,Replace(Job,’P") From Emp Where Job="PRESIDEN Sql> Select Job,Replace(Job,'MAN','EXECUTIVE') From EmpWhere SALESMAN" Real Time Scenario: TRANSLATE Functio: + Used to Translate Character by character in a String, Syntax: TRANSLATE(char,From ,To) + returns a char with all occurrences of each character in ‘From’ replaced by corresponding character in ‘To’. * Characters in char that are not in From are not replaced. + The argument From can contain more characters than To. «If the extra characters appear in Char, they are removed from the return value. ‘Sql> Select Translate(Job,'P’,' ') From Emp Where Job='PRESIDENT'; Sql> Select Transiate(Job,’MN','DM') From Emp Where Job="MANAGER'; Sql> Select Job, Translate(Job,’A’,'0") From Emp Where Job="SALESMA Sal> Select Transiate('Led’,'Le',R') From Dual; Real Time Scenario: CHR Functic Tt returns a character having the binary equivalent to ‘n’. + It returns the equivalent for ‘n’ in database character set or national character set. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 30- Oracle 11g Material Syntax: CHR(n) Sql>Select Chr(75)||Chr(82)||Chr(73)||Chr(83)] |Chr(72)| |Chr(78)||Chr(65) Name From Dual; ASCII Functi + Tt returns the decimal representation in the character database set of the first characters of the Char, Syntax: ASCII(Char) Sql> Select Ascii('A') From Dual; Sql> Select Enarhe,Ascii(Ename) From Emp; Sql> Select Ascii(‘&name') From Dual; NUMBER Function: + These function accept number input and return numeric values. + Many functions return values that are accurate to 38 decimal digits. ROUND Function: Systax: ROUND(m.n) It returns ‘m’ round to ‘n’ places right of the decimal point. + If'n’ omitted , n is rounded to 0, places + ‘n’can be negative , and rounds off the digits to the left of the decimal point. + ‘n’ must be an integer. Sql>Select 19.637 Num1ROUND(19.637,1) Rounded From Dual; Sql>Select 19.637 Num-,ROUND(19.637,-1) Rounded From Dual; Sql>Select 7843.637 Nurt_ROUND(7843.637,2) Rounded, ROUND(7843.637,-1) Rounded, ROUND(7843,637,-2)Rounded, ROUND(7843.637,-3)Rounded, ROUND(7843.637,-4)Rounded From Dual; TRUNCATE Fun: Systax:TRUNC(m,n) * It returns ‘m’ Truncated to ‘n‘ decimal places. + If'n’ omitted , n is truncated to 0 decimal places. « ‘n’ can be negative to truncate 'm’ digits left of the decimal point. Sql>Select 19.637 Num1,TRUNC(19.637,1) Truncated From Dual; Sql> Select 19.637 Num1-, TRUNC(19.637,-1) Truncated From Dual; Sql> Select 7843.637 Numi, TRUNC(7843,637, 2) Truncated, TRUNC(7843.637,-1) Truncated, TRUNC(7843.637,-2)Truncated, TRUNC(7843.637,-3)Truncated, “TRUNC(7843.637,-4) Truncated From Dual; CEIL Function: Syntax:CEIL(n) + Returns the Largest integer greater than or equal to 'n’. «The adjustment is done to the highest Nearest decimal value, ‘Sql>Selectgl9.001 Num1,CEIL(19.001) Ceiled From Dual; Sql> Select 19.34 Num1,CEIL(19.32) Celled ,CEIL(19.2) Celled ,CEIL(19) Ceiled From Dual; FLOOR Func! Syntax: FLOOR(n) + Returns the smallest integer less than or equal than ‘n’, «The adjustment is dane to the lowest Nearest decimal value. $q|>Select 19.001 Num1, FLOOR(19.999) Floor From Dual; Sal> Select 18.34 Num1,FLOOR(18.34) Floor,FLOOR(18.9) Floor,FLOOR(18) Floor From Dual; MODULUS Function: Syntax; MOD(m,n) ‘+ ItReturns remainder of ‘m' + Itreturns‘m’ ifn’ is 0. vided by ‘n’. Sql> Select MOD(100,10) Modulus, MOD(17,4) Modulus From Dual; —————————————— Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 2374666, 9000994008 - 31 - Oracle 11g Material POWER Function: Syntax: POWER(m,n) «It Returns ‘m’ Raised to the ‘n’th power. The base ‘m’ and the exponent 'n’ can be any number. Sql> Select POWER(5,2) Power, POWER(-5,2)Power From Dual; Sql> Select POWER(S,-2) Power, POWER(-5,-2)Power From Dual; SQUARE Functi Syntax: SQRT(n) ‘+ It Returns Square Root of ‘n’ as Real Value. «The Value of 'n’ cannot be negative. Sql> Select SQRT(25) From Dual; ABSOLUTE Function: Syntax: ABS(n) + It Returns the Absolute value of ‘n’ Sql> Select ABS(-100) From Dual; Sql>Select Sal, Comm, Sal-Comm, ABS(Sal-Comm) FROM Emp; ‘SIGN Function: ‘Syntax: SIGN(n) + It Returns the SIGN, Specific o Ifn<0,returns -1 o Ifn=0,returns 0 o Ifn>0,returns 1 Sql> Select SIGN(-10), SIGN(10), SIGN(0) From Dual; Sql> Select Sal, Comm, SIGN(Sal-Comm), ABS(Sal-Comm) “ROM Emp Where SIGN(Sal-Comm Working With Dates: + Oracle stores dates in an internal numeric format. + The dates in Oracle range from January 1,4712 BC to Dr >mber 31,9999 AD. The default display and Input format for any date is DD-i. JN-YY. The numeric format represents **Century **Year —**Month = **Day_-—**Hours. **Minutes **Seconds SYSDATE: * Itis a date function that returns current date and time. + SYSDATE is generally selected upon a DUAL Table, Sql>Select SYSDATE From Dual; Date Arithmetic: + As database stores dates as numbers, it allows to perform <. ilations using arithmetic operators such as addition and subtraction. = We can perform the following operations....... o Date + Number Date Adds a number of days to a aor o Date-Number Date Subtracts a number of days’ a date. © Date- Date Number of days Subtracts one date nother. Date + Number/24 Date Adds a number of hours to uate. Sql>Select Sysdate From Dual; Sql>Select Sysdate,Sysdate+10 From Dual; Sql> Select Sysdate,Sysdate-+48/24 From Dual; Sql>Select Ename,Hiredate,Hiredate+10 From Emp; Sql>Select Ename,Hiredate,Hiredate-5 From Emp; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Phi: 2° "000994008 - 32- Oracle Ig Material eee Sql>Select Ename,Hiredate,Sysdate-Hiredate “ExofEmps" From Emp; Sql> Select Ename,Round((Sysdate-Hiredate)/7) Weeks From Emp; Sql>Select Empno, Hiredate, Round((Sysdate-Hiredate)/365) From Emp; DATE Function: ‘Add_ months Function: ‘Syntax: ADD_MONTHS(D, +(or)-N) + Adds ‘N’ number of calendar months to date. * The value of 'N’ must be an integer and can be negative. Sql> Select Sysdate, Add_months(Sysdate,1) From Dual; Sql> Select Ename, Sal, Hiredate, Add_months(Hiredate,1) From Emp Where Deptno=30; Months Between Functior Syntax: Months_between(D1,02) + It gives the different between dates D1 and D2 In months. « If D1 is later than D2, the result is Positive, else Negative. + IfD1 and D2 are either the same days of the months or both last days of the months, the result is always an integer. Sql>Select Ename, Hiredate, Round(Months_Between(Sysdate,Hiredate)/12) " Experience In Years" From Emp; Sql> Select Ename, Hiredate,Months_Between(Sysdate,Hiredate) From Emp Where Months_Between(Sysdate, Hiredate)<320, Next Day Fun: Syntax: Next_day (0, Char) "Tt returns the date of the first week day named by char, that is later than the data D. + The CHAR must be a day of the week in the sessions data language. + The day of the week can be full name or the abbreviation. Sql>Select Sysdate, Next_day(Sysdate,WED’) From Dual; Sql>Select Sal, Hiredate,Next_day(Hiredate, MONDAY’) From Emp; Last_Day Function: Syntax: Last_day(D) * It returns the date of the last day of the month that contains D. +. Mostly used to determine how many days are left in the current month. Sal> Select Sysdate, Last_day(Sysdate) Last, Last_day(Sysdate)-Sysdate Daysleft From Dual ; Real Time Scena Sql> Select Add_months(Last_day(Sysdate),-1)+1 From Dual; Rounding of Dates: Syntax: Round (Date,'Format’) = Returns Date rounded to the Unit specified by the format. = If format is omitted, Date is rounded to the nearest day. Sql> Select Round(Sysdate,'DAY’) From Dual; Sql> Select Round(Sysdate,'MONTH') From Dual; ‘Sql> Select Round(Sysdate, YEAR’) From Dual; Truncating Dates: ‘Synatx:Trunc(Date,'Format’) * Return Date with the time portion of the day truncated to the specified unit, «If format is omitted, data is truncated to the nearest day. Sql> Select Round(Sysdate,'DAY’), Trunc(Sysdate,'DAY') From Dual; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 -33- Oracle Lig Material aS Sql> Select Round(Sysdate,MONTH'), Trunc(Sysdate,'MONTH') From Dual; ‘Sql> Select Round(Sysdate,'YEAR'), Trunc(Sysdate,'YEAR') From Dual; Conversion Function: «The Conversation functions convert a value from one data type to another. + The Data type conversion in Oracle is. two types. -*Implicit_ Data type Conversion **Explicit Data type Conversion Implicit Data type Conversion: ‘+ Implicit Date type conversion work according to the convention specified by oracle. ‘+The Assignment succeeds if the Oracle server can convert the date type of value. CHAR to NUMBER conversion succeed only if the character string represent a valid NUMBER, + CHAR to DATES conversion succeed only if the character string represent the default format of DD-MON-YY. ignment Oy 7 © Varchar2/Char Number © Varchar2/Char >Date + Number Varchar2 * Date Varchar2 Explicit Data type Conversion: * SQl provided three function to convert a value from one data type to another. + The explicit conversation function are © TO_LCHAR > To Character Conversion. 0 TO_DATE — > To Date Conversion. © To_Number > To Number Conversion TO_CHAR Conversion: * This function can be used in two ways. © TO_CHAR(Number Conversion) © TO_CHAR(Date Conversion) TO _CHAR(Number Conversion) ‘Syntax: TO_CHAR(NUMBER,fmt) * Converts Number of Number data type to a value of VARCHAR2 data type. + ‘fmt’ is the optional number format, that can be used. O_CHAR(Date Conversion) ‘Syntax: TO_CHAR(DATE,fmt) * Converts Date of Date data type to a value of VARCHAR? data type in the format specified. “fmt! is the optional Date format, that can be used. al Indicator:D>99D99 It returns the specified position of the decimal character . The default decimal delimiter is period‘! Only one decimal indicator can be specified in a number format model. Deci Sql> Select 1234,TO_CHAR(1234,'9999D99") From Dual; Sql> Select 1234,TO_CHAR(1234,'999D99") From Dual; Scientific Notation Indicator:EEEE>9.9EEEE + Returns a Numeric value using scientific notation. Sql> Select TO_CHAR(5634,'9.9EEEE') From Dual; Group Separator: 6396999 ¢ Returns the specified position of the Group separator + Multiple Group separators can be specified. Sql> Select TO_CHAR(1234567,'99G99G9999") From Dual; Sql> Select Sal,TO_CHAR(Sal,'9G999') From Emp; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9994008 -34- Oracle 13x Materiat Local Currency Indicator: [1999 OR 9991. ‘+ Returns the specified position of the focal currency symbol. Sq/>Select 1234,TO_CHAR(1234,'L9999') From Dual; SqlSelect Sal,TO_CHAR(Sal,'(999999") Currency From Emp Where Deptno=10; ‘Sql> Select Sal,TO_CHAR(Sal,'L99G999D99",'NLS_CURRENCY=IndRupees’) Sal From Emp Where Deptno=20; Trailing Minus Indicator: MI>9999MI + Return negative value with a trailing mfnus sign’. + Returns positive value with a trailing Blank. + ‘MI’ Format shauld be declared as Trailing argument only. Sql?select -10000,TO_CHAR(-10000,'L99G999D99MI') From Dual ; Sq|> select Sal,Comm,Comm-Sal, TO_CHAR(Comm-Sal,'L99G999D99MI') From Empi Negative Number Indicator:PR>9999PR ‘Returns negative number in ‘<>’. + St Can appear only as trailing declaration. Sql select TO_CHAR(-1000,'L99G999D99FR’) From Dual; Sql> select Sal,Comm,Comm-Sal, 70_CHAR(Comm-Sal,'L9999PR’) From Emp; Roman Number Indicator: + RN-Returns Upper Roman Number. +m Returns Lower Roman Number. + The value can be an integer between 1 and 3999. ‘Sql> select 12,TO_CHAR(12,'RN'),TO_CHAR(12,"m') From Dual; Sign Indicator:S>S99999 OR 999995 + Returns Negative value with a ieading Minus Sign. + Returns Positive value with a leading Plus Sign, + Returns Negative value with Trailing Minus Sign. Returns Positive value with a Trailing Plus Sign, *S' can appear as First or Last value. Sql> select 1000,TO_CHAR(1000,'S9999'), TO_CHAR(-1000,'S9998") From Dual; Sql>select TO_CHAR(1000,'9999S'),T0_CHAR(-1000,'9999S") From Dual; Sql>select Sai,TO_CHAR(Sal,'S99999'),TO_CHAR(Sal,'99995') From Emp; Sqi>select Sal, Comm,TO_CHAR(Comm-Sal,'599999'), TO_CHAR(Comm-Sal,'9999S') From Emp; Hexadecimal Indicator: X>XXXX + Returns the Hexadecimal value of the specified number of Digits. + Ifthe Number is not an integer, oracle rounds it to an integer, + Accepts only positive values or 0. Sql>select 2000,TO_CHAR(2000,'XXXX') From Dual; Sql> Select Ename,Sal,TO_CHAR(Sal,'XXXX') Hexsal_ From Emp; Group Separator:>9,999 + Returns a comma in the specified position. + Multiple commas can be specified. Sql> select 20000,TO_CHAR(20000,'99,999.99') From Dual; Sql> Select Ename,Sal,TO_CHAR(Sal,'99,959.99') From Emp; Decimal Zacicator: 399.99 > Returns @ decimal point, at the specified position > Only one period can be specified in a number format model. Sql> Select 20000,TO_CHAR(20000,'L99,999,99") From Dual; Sql> Select Ename,Sal,TO_CHAR(Sal,'L99,999.99") From Emp; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 35 - Doll lar Indicator: $ >$9999 «Return value with a leading dollar sign. Sql> Select 20000,TO_CHAR(20000,'$99,999.99') From Dual; ‘Sql> Select Ename,Sal,TO_CHAR(Sal,'$99,999.99") From Emp; ‘Zero Indicator:0->0999 OR 9990 + Returns Lading OR Trailing Zeros. Sql>select 1000,TO_CHAR(1000,'0999999"),TO_CHAR(1000,'09999990') From Dual; Sql> select Ename,Sal,TO_CHAR(Sal,'$099,999.99") From Emp; Digit Place Marker: 939999 + Returns value with a specified number of digits with a Leading space when positive or Leading minus when Negative. ‘Sql> select 1000,600,TO_CHAR(1000-600,"29999"), TO_CHAR(600-1000,'99999') From Dual; Sql>select 20.25,20,TO_CHAR(20.55-20,'99999'), TO_CHAR(20.25-20,'99999') From Dual; ISQ Currency Indicator: C-9C3999 + Return specified position of the ISO Currency Symbol. ‘Sql>select 1000,TO_CHAR(1000,'C9999.99') Fram Dual; Sql>select Ename,Sal, TO_CHAR(Sal,'C9999.99") From Emp; Date Format Models: + The date format models can be used in the TO_CHAR function to translate a DATE value from original format to user format. Data Format “ements: ‘+ Aate format model is composed of one or more date format elements. ‘+ For input format models, format items cannot appear twice, and format items that represents similar information cannot be combined. * Capitalization in a spelled word, abbreviation, or roman numeral follows capitalization in the corresponding format element. * Punctuation such as Hyphens, Slashes, Commas, periads and Colons. AD or A.D./BC or B.C, Indicator: Indicator AD/BC with or without periods. ‘Sql> Select Sysdate,TO_CHAR(Sysdate,AD') From Dual; Sql>Select TO_CHAR(Sysdate,'B.C.’), TO_CHAR(Sysdate/A.D.’) From Dual; Sql>Select Ename,Sal,Hiredate, TO_CHAR(Hiredate/A.D.’) From Emp; Meridian Indicator: * It indicates meridian indicator with or without periods. Sql>Select Sydate,TO_CHAR(Sysdate,’A.M.’), TO_CHAR(Sysdate,PM" From Dual; ‘Sqi>Select Ename,Sal,Hiredate,TO_CHAR(Hiredate/AM’) From Emp Century Indicator: CC * Indicates the century. ‘Sql> Select Sydate,TO_CHAR(Sysdate/CC-AD') From Dual; a Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90° 94008 -36- ‘ Oracle 11g Material ——————— Numeric Week day indicator:03(1-7) * Returns the week day number. Sql>Select Sysdate,TO_CHAR(Sysdate/D’) From Dual; ‘Sql> Select Ename,Sal, Hiredate,TO_CHAR(Hiredate,D’) From Emp; Week day spelling indicator: Day. © Pads to a length of 9 characters. Sql> Select Sysdate,TO_CHAR(Sysdate,'DAY') From Dual; Sql> Select Ename,Hiredate,TO_CHAR(Hiredate,'DAN") Fram Emp Where ‘TO_CHAR(Hiredate,'DY')="MON'; Month day indicator:DD + It indicates the day of the Month(1-31) ‘Sql Select Sysdate,TO_CHAR(Sysdate,'DD-DAY') From Dual; Sql> Select Ename, Hiredate,TO_CHAR(Hiredate,'D0_DAY") From Emp; Sql> Select Ename,Hiredate,TO_CHAR(Hiredate,'DY') From Emp Where TO_CHAR(Hiredate, 'DD-DY")='28-MON'; Year day indicator:DDD + Itindicates the day of the Yaer(1-366) Sql> Select Sysdate, TO_CHAR(Sysdate,'DDD') From Dual; Sql> Select Ename, Hiredate,TO- CHAR(Hiredate,'DDD') From Emp; Sql> Select Ename,Hiredate,TO_CHAR(Hiredate,'DDD') From Emp Where TO_CHAR(Hiredate,'DY')='MON'; Abbreviated week day: DY + It indicates the day of the Yaer(1-366) Sql> Select Sysdate,TO_CHAR(Sysdate,'D-DY-DAY') From Dual; Sql> Select Ename,itiredate,TO_CHAR(Hiredate,'D-DY-DAY') From Emp Where Deptno in(10,20); ISO standard year week indicator: 1W + Specifies the week of the yaer(1-52 or 1-53) based on the ISO standard, Sql> Select Sysdate,1O_CHAR(Sysdate,"IW') From Dual; Sql>Select Ename,Hiredate,TO_CHAR(Hiredate,'IW’) From Emp; ISO standard 4 digit year indicator: IYYY + Specifies 4 digit year based on the ISO standard. + It can even be used in combination of IYY,1Y,I. Sql> Select Sysdate, TO_CHAR(Sysdate,'IYYY') From Dual; Sql>Select Ename,Hiredate,TO_CHAR(Hiredate,‘IYYY’) From Emp Where TO_CHAR(Hiredate,'DY")='MON'; Four Digit Year Indicator: YYYY or SYYY + Return four digit year,’S’ prefixes BC dates with '-'. + It can even be used in combination of YYY or YY or Y. + Y,YYY returns year with comma in that position, Sql>Select to_char(sysdate,'syyyy') from dual SqiSelect Hiredate,TO_CHAR(Hiredate,'YYYY'), TO_CHAR(Hiredate,'YYY') From Emp; Sql>Select TO_CHAR(Sysdate,"YYY"),TO_CHAR(Sysdate, YYY'), TO_CHAR(Sysdate,'YY') From Emy Spelled Year Indicator: YEAR or SYEAR + Returns the numerical year in spelling. Sql> Select SYSDATE, TO_CHAR(Sysdate,'Year'),TO_CHAR(Sysdate,"YEAR') From Dual; Sql>_ Select Empno,Ename,Miredate,TO_CHAR(Hiredate,'Year') From Emp; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 37- Oracle 11g Maieriat ——————————————— Week of the month indicator: W Specifies the week of the month(1-5). «Week starts on the first day of the month and ends on the seventh day. Sql> Select Sysdate,TO_CHAR(Sysdate,'W") From Dual; Sql> Select Empno,Ename,Hiredate,TO_CHAR(Hiredate,'W') From Emp; ‘Year week Indicator: WW + Specifies the week of the year(1-53) + Week 1 starts on the first day of the year and continues to the seventh day in that year. Sql> Select Sysdate,TO_CHAR(Sysdate,'WW') From Dual; Sql> Select Empno,Ename,Hiredate, TO_CHAR(Hiredate,, WW") From Emp; Quarter of the Year Indicator:Q ‘+ Returns the Quarter if the year. © Quarter starting with the month of Janvary and ending with every three months. Sql> Select Sysdate,TO_CHAR(Sysdate,'Q') From Dual; Sql> Select Empno,Ename,Hiredate, TO_CHAR(Hiredate,'Q') From Emp Where O_CHAR(Hiredate,'Q)=3;, Julian Day indicato¢: 3 ‘+ Returns the JULIAN Day of the given date, + This the number of day since January 1,4712 BC. + Number specified with ‘J’ must be integers. Sql> Select Sysdate,TO_CHAR(Sysdate,'J') From Dual; Sql> Select Empna,Ename,Hiredate,TO_CHAR(Hiredate,"J-DDD-DD-D') From Emp; Number Month Indicator:MM ‘Returns the numeric abbreviation of the month. Sql> Select Sysdate,TO_CHAR(Sysdate,'MM-YYYY') From Dual; ‘SqI> Select Ename,TO_CHAR(Hiredate,'DD-MM-YYYY') From Emp Where TO_CHAR(Hiredate,'MM‘)=12; Abbreviated Month Indicator:MON « Returns the abbreviated naie of the Month. Sql> Select Sysdate,TO_CHAR(Sysdate,'MON') From Dual; Sql> Select Hiredate,TO_CHAR(Sysdate,'MONTH') From Emp; ‘Twelve Hour Clock Mode: HH or HH12 ‘© Itis default clock mode. © Returns the hour of the day in twelve hour clock mode. Sql> Select Sysdate,TO_CHAR(Sysdate,'HH"), TO_CHAR(Sysdate,'HH12,PM") From Dual; Sql> Select Ename,Hiredate, TO_CHAR(Hiredate,'HH12:PM') From Em ‘Twenty Hour Clock Mode:HH24 «Returns the hour of the day in twenty four hour clock mode.(0-23) Sql> Select Sysdate,TO_CHAR(Sysdate,HH24") From Dual; RealTime Scenario: Minutes Indicator: MI Returns the minutes from the given date(0-53). Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Pl: 23746666, 900994008 38 - Oracle Hig Material Sql> Select Sysdate,TO_CHAR(Sysdate,'MM') From Dual; ‘Sqi> Select Ename,Hiredate,TO_CHAR(Hiredate,'HH:MM') From Emp Where Deptno=20; Roman Month Indicator: RM «Return the roman numeral month(I-X1!). Sql> Select Sysdate,TO_CHAR(Sysdate,'RM'), TO_CHAR(Sysdate,'DD-RM-YY') From Dual; Sql> Select Ename,Hiredate,TO_CHAR(Hiredate,'DD-RM-YY') From EmpWhere Deptno=20; Seconds Indicator: SS * Returns seconds from the given the dates(0-59) Sql> Select Sysdate, TO_CHAR(Sysdate,'SS'), TO_CHAR(Sysdate,'HH:MI-SS') From Dual; Sql> Select Sysdate, TO_CHAR(Sysdate,'RM'), TO_CHAR(Sysdate,'Day-Honth- Year HH24:MI:SS PM.") From Dual; Sql> Select Ename,Hiredate,TO_CHAR(Hiredate,'HH24-MI-SS") From EmpWhere Deptno=30; Date Format Punctwators: + The punctuation marks that can be used in date formats are. ss Date Format element suffices: TH or SP * THSuffixes the ordinal number with 'st’ or ‘nd’ or ‘rd or “th’, Example: Sql> Select Sysdate,TO_CHAR(Sysdate,'DDth,MONTH,YYYY') From Dual; Sql>Select Ename,Hiredate, TO_CHAR(Hiredate,'DDth,MONTH,YYYY') From Emp; ‘SP2Spells ordinal numbers. Sql>Select Sysdate,TO_CHAR(Sysdate,'DDsp,MONTH,YYYY") From Dual; Sql>Select Ename,Hiredate,TO_CHAR(Hiredate,'DDsp,MONTH,YYYY') From Emp; ‘Sqi>Select Ename,Hiredate, TO_CHAR(Hiredate,'DDspth,MONTH,YYYY") From Emp; ‘Sql>Select Sysdate,TO_CHAR(Sysdate,'DDspth Month YYYYSP") From Dual; Date Format Elements restrictions: «The suffixes when added to date return values always in English. * Data suffixes are valid only on output, hence cannot be used to insert a data into the database. Format Mode! Modifiers: Fill Mode Indicator :FM * It suppresses blank padding in the return value of the TO_CHAR function Sql> Select Sysdate,TO_CHAR(Sysdate,'DDSPTH MONTH YYYYSP'), TO_CHAR(Sysdate,'FMDDSPTH MONTH YYYYSP") From Dual; ‘O_NUMBER Function: Syntax:TO_NUMBER(Char,fmt) + It convert a char ,value of CHAR or VARCHAR2 data type containing a NUMBER in the format specified by the optional format model ‘fmt’, to a value of NUMBER data type. Sql> Select '$ 10,000.00',TO_NUMBER('$10,000.00','L99,999,99') From Dual; ‘Sql> Select '$10,000.00', TO_LNUMBER('$10,000.00','L99,999.99')+500 From Dual; TO_DATE function: ‘Syntax:TO_DATE(Char, fmt’) + Converts given char of Char or Varchar2 data type to a value of DATE data type. + The ‘fmt’ is optional Date format specified the format of CHAR. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 39- Oracle 11g Material Sql> Select TO_CHAR(TO_DATE('12-JAN-1980'),'DDSP") From Dual; Sql> Select Ename,Hiredate, ADD_MONTHS(TO_DATE ('1980-DECEMBER-17','YYYY- MONTH-DD'),3) FROM Emp WHERE Hiredate='17-DEC-1980'; Sql>Select Ename,Hiredate, ADD_MONTHS(TO_DATE('1980-DECEMBER-17", YYYY- MONTH-DO'),3) FROM Emp WHERE TO_CHAR(Hiredate,'FMYYYY-MONTH-DD')= "1980-DECEMBER-17; INSERT Statement With Invalid Number Sql>Create Table Temp ( Empno Number(8), Doj Date ); Sql>Insert into Temp Values(_ TO_NUMBER('1,23,456",'9G99G999"), SYSDATE % Sql> Insert into Temp Values TO_NUMBER('1,23,456-','9G99G999MI"), SYSDATE i Invalid Dates: ‘Sqi>Insert Into Temp Values(1001,'2-JAN-09 11:30:15’); Sql> Insert Into Temp Values(1001,TO_DATE('12-JAN-2009 11:30:15 P.M.’,'DD- MON-YYYY HH:MI:SS P.M’); Sql> Insert Into Temp Values(1001,TO_DATE('12-JAN-3712 B.C.',DD-MON-YYYY Ci Sql> Insert Into TempValues(1001,TO_DATE(100,"")); Sql>Select TO_DATE(10,’DD') From Dual; Sql> Select TO_DATE(10,'0D0") From Dual; Sqi>Select TO_DATE(1,'W’) From Dual; Sql> Select TO_DATE(1,'WW') From Dual; RR Date Format Elements: + The RR date format element is similar to the YY date format « nent. +. Te RR format elements provides additional flexibility for storing data values in other centuries. + The RR date format element allows to store the date to the prvious as well as the next centuries, + The RR format elements should be used in association with TO_DATE conversion function only, else the system treats it as YY format element. + The format can be used as either 'RR’ or ‘RRR’ format element. Century Identification: Last Two Digits of the year 1 managed by clock 07049 : 50 To 99_ | Returns the date in Current | Returns the ate In the | lL century previews Ce tury. Some Combinations Sql>Select TO_CHAR( ADD_MONTHS(Hiredate,1), 'DD-MON-YYY¥" ) "Next Month" From Emp Where Empno=778; Sql> Select Concat( Concat(Ename, ‘is a), Job )Designation From Emp Where Deptno=20; Sql> Select Trunc( TO_DATE('27-OCT-92','DD-MON-YY"), ‘YEAR’, New Year" From Dual; Sq!>Select TO_CHAR( ADD_MONTHS( LAST_DAY(Hiredate),5),'"-MON-YYYY' ) “Five Months" From Emp Where Empno=7788; Sql>Select MONTHS_BETWEEN(TO_DATE( '02-02-1995',MM-DD.. ‘Y"), TO_DATE( '02-02-1995/,MM-DD-YYYY" ))Months FROM Dual; Sql>Select NEXT_DAY('15-MAR-98',TUESDAY’) From Dual; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 0994008 -40~ Oracle ig Materia ‘Sq|>Select Ename,NVL(TO_CHAR(Comm),’Not Applicable’) “Commission” From Emp WHERE Deptno=30; Sql>Select Round(TO_DATE('27-OCT-92",/DD-MON-YY’), ‘YEAR’)"New Year"From Dual; Sql>Select TO_CHAR(Hiredate,’MONTH DD,YYYY’) From Emp Where~ Ename="FORD"; ‘Sql>Select Ename, TO_CHAR(Hiredate,’FMMonth,DD YYYY’) Hiredate From Emp Where Deptno=20; ‘Sql> Select TO_CHAR(TO_DATE('27-OCT-98',DD-MON-RR'), 'YYYY') Year From Dual; + Assumption: Queries are issued Between Year 1950-1999, Sql> Select TO_CHAR(Sysdate,FMDDTH')||' of ‘|| TO_CHAR(Sysdate, Month’)||" ‘|| TO_CHAR(Sysdate,'YYYY')Idea_From Dual; Sql>Select Ename,Job,NVL(TO_CHAR(MGR),'Supreme Authority’) "Managers" ' From Emp Order by Sal Desc; Spelling a Number Sql> Select TO_CHAR(TO_DATE('&GiveNumber','J'), "JSP" ) "Spelled Number" From Dual; Selecti Sql>Select TO_CHAR( TO_DATE(Hiredaua,‘DD-MON-RRRR’), ‘DD-MON-YYYY’ ) Hiredate From Emp; Text Encryption Sql>Select ‘KRISHNA REDDY’ OrgName,Translate(’KRISHNA REDDY’, *ABCDEFGHISKLMNOPQRSTUVINXYZ’ 1234567 8901@# $0" 8()- +in')Encryptedname From Dual; ‘ext Decryption: Sql> Select '!*9(8$1 *544;' Encryptedname, Translate("!*9(8$1 *544;", "1234567890!@#$%*&*()-=_+;,', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' )Encryptedname From Dual Aggregating or Group Functions: * Group functions operate on sets of rows to give one result per group. + Group functions can appear in select lists and in ORDER BY and HAVING clauses. + The Oracle Server applies the group functions to each group of rows and returns a single result row for each group. +. The group functions to return summary information for each group. ‘Syntax: group_function(DISTINCT/ALL Column) Guidelines for Using Group Functions: + The data types for the arguments can be CHAR, VARCHAR2, NUMBER, ar DATE. + All group functions except COUNT(*) ignore null values. To Substitute a value for null values, use he NVL function. COUNT returns either a number or zero. * The Oracle Server implicitly sorts the result set in ascending order of the grouping columns specified, when you use a GROUP BY clause. To override this default ordering, you can use DESCin an ORDER BY clause. + When a group function is declared in a SELECT list, on single row columns should be declared. Average Functi Synta \VG(DISTINCT/ALL Column) * It returns the Average value of column. + It ignores NULL values. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 41 - ‘Sql>Select Avg(Sal),Avg(DISTINCT Sal) From Emp; Sql> Select Avg(Comm),Avg(DISTINCT Comm) From Emp; ction: ‘Syntax: SUM(DISTINCT/ALL Column) + It returns the SUM value of column, + It ignores NULL values. Sql>Select SUM(Sal),SUM(DISTINCT Sal) From Emp; Sql> Select SUM (Comm), SUM (DISTINCT Comm) From Emp; Maximum Function: ‘Syntax: MAX(DISTINCT/ALL Column) © Tt returns the Maximum value of column. ‘+ Tt ignores NULL values. Sql>Select MAX(Sal), MAX{DISTINCT Sal) From Emp; Sql> Select MAX (Comm), MAX (DISTINCT Comm) From Emp; ‘Sql> Select MAX(Ename) From Emp; nection Syntax: MIN(DISTINCT/ALL Column) «- Ttreturns the Minimum value of column. * It ignores NULL values. Sql> Select MIN(Sal),MIN(DISTINCT Sal) From Emp; ‘Sql> Select MIN (Comm), MIN (DISTINCT Comm) From Emp; Sql> Select MIN(Ename) From Emp; Sql> Select MIN(Hiredate),Max(Hirdate) From Emp; Standard Deviation Function: Syntax: STDDEV(DISTINCT/ALL Column) ‘+ It returns the Standard Deviation of column. ‘+ Tt ignores NULL values. ‘Sql>Select STDDEV(Sal), STDDEV(DISTINCT Sal) From Emp; ‘Sql> Select STDDEV (Comm), STODEV (DISTINCT Comm) From Emp; Variance Function: Syntax: Variance(DISTINCT/ALL Column) © It returns the Variance of N. + It ignores NULL values. ‘Sql>Select VARIANCE(Sal), VARIANCE (DISTINCT Sal) From Emp; Sal> Select VARIANCE (Comm), VARIANCE (DISTINCT Comm) From Emp; Count Function: Syntax: COUNT(*/DISTINCT/ALL Column) * It Gives No of Rows in the Query. ‘+ Jf**’ used to returns all Rows, Including duplicated and NULLs + It can used to specify the count of all rows or only distinct values of column ‘Sql>Select COUNT(Empno) From Emp; ‘Sql> Select COUNT(Job),COUNT(DISTINCT Job) From Emp; Sql> Select COUNT(Sal),COUNT(DISTINCT Sal) From Emp; ‘Sql>Select Count(*) From Emp; Sql> Select COUNT(Empno),COUNT(DISTINCT MGR) From Emp; Sql>Select Select COUNT(3ob),COUNT(DISTINCT MGR) From Emp Where Deptno=20; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746665, 9000994008 - 42- Oracle 11g Material eating Groups of ‘The Group by clause is used to decide the rows in table into groups. Syntax1: Sql>SELECT columnnamet, Columnname2,.... ~ FROM table [WHERE condition(s)] [GROUP BY Column name(s)] [ORDER BY column(s)]; ‘Sql>SELECT columnnamei, GRP_FUN(Column) FROM table [WHERE condition(s)] [GROUP BY Columnname(s)] [ORDER BY column(s)]; idelines to use Group By Clause: All GROUP BY CLAUSE columns list may or may not used in SELECT clause. + The Extra non Group functional column should be deciared in the GROUP BY Clause. * If the GROUP Function is included in a SELECT clause, we should not use individual result columns. + Using WHERE clause, Rows can be pre excluded before dividing then into groups. + Column aliases cannot be used-used in GROUP BY CLAUSE. By default, Rows are sorted by ascending order of the columns included in the GROUP BY LIST. Example: ‘Sq\> Select Job From Emp GROUP BY Job; Sql> Select Deptno From Emp GROUP BY Deptno; Sql> Select Mgr From Emp GROUP BY Mgr; Sql> Select TO_CHAR(Hiredate,"YYYY') YearGroup From Emp GROUP BY TO_CHAR(Hiredate,'YYYY'); Sql> Select TO_CHAR(Hiredate,'Month') MonthGroup From Emp GROUP BY TO_CHAR(Hiredate,'Month'); Sql> Select TO_CHAR(Hiredate,'DD') DayGroup From Emp GROUP BY TO_CHAR(Hiredate,'DD'); Sql> Select TO_CHAR(Hiredate,'Month') MonthGroup From Emp Where TO_CHAR(Hiredate,'Mon’)<>’Dec’ GROUP BY TO_CHAR(Hiredate,'Month'); Creating Group wise summaries: Sql>Select Owner, COUNT(Object_Name) From dba_objects Group By Owner; Sql> Select Deptno,COUNT(*) From emp Group By Deptno; Sql> Select Deptno, AVG(Sal) From Emp Group By Deptno Oredr By AVG(Sal); Sql> Select Deptno,Min(Sal),Max(Sal) From Emp Group by Deptno; Sql> Select Ename, Max(Sal) From Emp Group By Deptno; Note: It will give error . Sql>Select Deptno,SUM(Sal) From Emp Group By Deptno; ‘Sql>Select Deptno,Job,SUM(Sal) From Emp GROUP BY Deptno,Job; Sql> Select Deptno,Job,SUM(Sal) From Emp GROUP BY Deptno,Job; Sql> Select Job,Min(Sal),Max(Sal) From Emp Where Deptno=30 GROUP BY Job; Sql>Select Deptno,Sum(Sal),Max(Sal) From Emp Where Job='CLERK' GROUP BY Deptno; OCP Questions: 1)Examine the description of the STUDENTS table: STD_ID NUMBER(4) COURSE_ID VARCHARD2(10) Naresh { Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9900994008 - 43 - Oracle 11g Material ———————————————————————————————— START_DATE DATE END_DATE DATE Which two aggregate functions are valid on the START_DATE column? (Choose two) A. SUM(start_date) _ B. AVG(start_date) C. COUNT(start_date) D. AVG(start_date, end_date) E, MIN(start_date) F. MAXIMUM(start_date) Having Clause: avi You may not want all the summary rows returned by a GROUP BY query. You know that you can use WHERE to eliminate detail rows returned by a regular query. With summary queries, you can use the HAVING clause to eliminate summary rows. + Tt used generally with GROUP BY Clause the having is useful for specifying a condition for the group. «The Clause is used to filter data that is associated with group function, SELECT [column,] group_function(column}. . . FROM Table [WHERE condition] [GROUP BY group_by_expression] [HAVING having_expression]; [ORDER BY Column/Alias]; ‘The HAVING Clause: * Groups are formed and group functions are calculated before the HAVING clause is applied to the groups. + The HAVING clause can precede the GROUP BY clause, but it is recommended that you place the GROUP BY clause first because it is more logical. * Steps when you use the HAVING clause: 1. Groups rows 2. Applies the group functions to the groups and displays the groups that match the criteria in the HAVING clause. GROUP BY Clause can used, Without a Group function in the SELECT list. HAVING Clause can used, Without a GROUP BY Clause in the SELECT Statement. + If rovis are restricted based on the result of a group function, we must have a GROUP BY clause as well as the HAVING Clause. « Existence of GROUP BY clause dose not guarantees the Existence of HAVING clause. Sql>Select Deptno,COUNT(Deptno) From Emp GROUP BY Deptno HAVING COUNT(Deptno)>3; Sql> Select Deptno,COUNT(Deptno) From EmpHAVING COUNT(Deptno)>3_ GROUP BY Deptno; Sql> Select Deptno,AVG(Sal) From EmpGROUP BY Deptno HAVING AVG(Sal)>2500; Sql> Select Job,SUM(Sal) Payroll From Emp Where Job<>'SAl Job HAVING SUM(Sal)>=5000 ORDER BY SUM(Sal) Desc; Sql> Select Deptno, MIN(Sal), MAX (Sal), SUM(Sal) From Emp Where Jo! GROUP BY Deptno HAVING MIN(Sal)<1000; Sql> Select Deptno,AVG(Sal),SUM(Sal),MAX(Sal), MIN(Sal) From Emp GROUP BY Deptno HAVING COUNT(Deptno)>3; Sql>Select Deptno,AVG(Sal),SUM(Sal) From Emp GROUP BY 2: ino HAVING AVG(Sal)>2500; Sql>Select Deptno,Job,AVG(Sal), SUM(Sal) From Emp GROUP BY!» 3,Job HAVING AVG(Sal? =? 20; ESMAN' GROUP BY LERK’ of Group Function * Group Functions can be Nested to Depth of two levels. Sql> Select MAX(AVG(Sal)) From Emp GROUP BY Deptno; Naresh i Technologies, Opp. Satyam Tieatre, Ameerpet, Hyderabad, Ph: 237466: 994008 - 44- . ; Oracle 11g Material EE Sql> Select MAX(SUM(Sal)),MIN(SUM(Sal)) From Emp GROUP BY Deptno; Sal> Select MAX(SUM(Sal)),MIN(AVG(Sal)) From Emp GROUP BY Deptno; Miscellaneo ion: GREATEST Function: ‘Syntax: GREATEST (Expr, Expr2,....) + Ttused to pick highest values from list of values. + All exprs after the first are implicitly converted to the data type of the first expr;before the comparison. * Character comparison is based on the value of the character in the data base character list. Sql>SELECT GREATEST ('SIBEL’/CODD;SCOTT’) FROM DUAL; ‘SqI>SELECT GREATEST(1000,2000,3000,4000) FROM DUAL; Sql> SELECT GREATEST(’10-JUL-05'/20-JUL-05") FROM DUAL; LEAST Function: Syntax: LEAST(Expri, Expr2,..) «It used to pick lowest value from list of values + All exprs after the first are implicitly converted to the data type of the first expr;before the comparison. ‘SqI>SELECT LEAST(‘M'/N'O"’X’,Y/Z') FROM DUAL; Sql>SELECT LEAST (1000,2000,3000,4000) FROM DUAL; Sql> SELECT LEAST ('10-3UL-05'/20-JUL-05"), FROM DUAL; SER jon: Syntax: USER * It returns the current oracle users names within the VARCHAR2 data type. + The function cannot be used in the condition of the CHECK constraint. ‘Sqi>Select USER from Dual; UID Function: ‘Syntax: UID «It gives a number that identified the user since oracle is used in a multi-user environment. * UID is the way identifying a user. Sql>Select USER, UID From Dual; USERENV Function: Syntax: USERENV(Option) ‘© Returns information of varchar2 data type above the current session. ‘The values in options are XISDBA’> Returns ‘TRUE! if DBA is enabled. ‘LANGUAGE’-)Returns the language and territory used in current Session. ‘TERMINAL’ Returns the OS identifier for the current sessions terminal. ‘SESSIONID’ Returns the auditing session identifier. ‘ENTRYID'>Retwrns the available auditing entry identifier. \LANG'=> Returns the ISD abbreviation for the language name. SINSTANCE'-)Returns the instance identification number of the current instance. Sql>Select USERENV("ISDBA’) From Dual; Sql> Select USERENV('LANGUAGE") From Dual; Sql> Select USERENV('TERMINAL’) From Dual; Sql> Select USERENV('SESSIONID') From Dual; : Sql> Select USERENV('LANG') From Dual; SqJ> Select USERENV("INSTANCE') From Dual; SIZE Func! Syntax: VSIZE + Ttreturns the NUMBER of bytes in th + _If Expr is NULL, Function returns NULL, Sql>Select Ename,VSIZE(Ename) From Emp; ternal representation of Expr. Naresh I Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 -45~- racte 11g Material ——————————— Sql>Select Deptno, VSIZE(Deptno) From Emp; Sql> Select Ename,Hiredate, VSIZE(Hiredate) From Emp; SOUNDEX Function: Syntax :SOUNDEX(CHAR) + Itreturns a character string containing the representation of CHAR. . It a comparison of words that are spelled differently, but sound alike in English. sal>Select Ename From emp Where SOUNDEX(Ename)= SOUNDEX (‘SMYTHE’); Sql> Select Ename,Job From EmpWhere SOUNDEX(Job)=SOUNDEX(‘manger" Sql> Select Job From emp Where SOUNDEX(Job)=SOUNDEX(‘CLRK'); ———— ee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90094008 - 46 Oracle 11g Material INTEGRITY CONSTRAINTS Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 47- Oracle 11g Material a > Introduction to Integrity Constraints > Implementation of Constraints All business of the world run on business data being gathered, stored and analyzed . Business managers determine a set of business rules that must be applied to their data prior to it being stored in the database/table of ensure its integrity. For instance, no employee in the sales department can have a salary of less than Rs.1000/-,Such rules have to be enforced on data stored, Only data, which satisfies the conditions set , should be stored for future analysis, The data, which is not obeying integrity constraints, is called inconsistent data. Every software must enforce integrity constraints, otherwise inconsistent data is generated. Remember: >It is used to impose business rules to DBs. >It allows to enter only valid data. Various types of Integrity Constraints: Domain Integrity: * ADomain means a set of permitted values. + These constraints set a range, enforcement of not null constraint in a table, + There are basically three types of Domain Integrity Constraints * Not Null Constraint + Check Constraint wt Default Constraint Entity Integrity: Entity integrity constraints are two types . * Unique Constraints «Primary key Constraints it defines a entity or column as a UNIQUE for a particular table: Primary key constraint avoids duplicate and null values. Referentia} Integrity: The referential Integrity constraint enforces relationship between tables it designates a column or combination of columns as a foreign key. The foreign key establish a relationship with a specified primary or unique Key in another table called the referenced key. When referential integrity is enforced, it prevents from + Adding records to a related table if there is no associated record in the Primary Table. * Changing values in a Primary Table that result in Orphaned records in a related table, * Deleting records from a Primary Table. if there are matching related records. ‘The table containing the foreign key is called the child table and the table containing the referenced key is called the Parent key. ‘As per Oracle these are Six Types of Constrains: 1) NOT NULL Constraint 2) UNIQUE Constraint 3) PRIMARY KEY Constraint 4) FOREIGN KEY(Self Reference) 5) CHECK Constraint Level of constrain’ 1)Column level > Used to define constraints next in column name “Define with each column. Composite key can not be defined 2)Table Level:~ Defining constraints after defining all columns. Not Null can not be defined The Constraint clause can appear in Note: ‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 43 - ‘ Oracle 11g Material SS ———————————— + CREATE Table «ALTER Table + CREATE View Oracle does not support Constraint on Column of attributes whose types is * USER_DEFINED OBJECT NESTED TABLE VARRAY REF A LoB ‘ Exceptions: ‘+ NOT NULL Constraint are supported for a column or attributes whose type is. USER_DEFINED object VARRAY, REF, LOB. NOT NULL Constrain! ‘* Used to suppress null values into columns. + Data must be entered. + Duplication values allowed, + NOT NULL should be defined only at COLUMN Level. + The default if specified is NULL. Example: Sql> CREATE TABLE branch_mstr (Branch_No Varchar2(10) Constraint Branchno_NN. NOT NULL,Name Varchar2(20) Constraint Name! NN NOT NULL); UNIOUE Constraints: Used to suppress duplicate values into columns. Accepts NULL values. + A table can have more than one UINQUE key which is not possible in Primary Key. Unique key can defined on more than one column.(ic composite unique key). A composite key UNIQUE key is always defined at the table level only. ‘One table can have more than one Composite UNIQUE Key. Oracle creates an indexed automatically. estrictions: + Unique key can not be implemented on columns having ... .LOB .LONG .LONG RAW .VARRAY .NESTED TABLE -OBJECT .BFILE .REF .TIMESTAMP . A composite UNIQUE key cannot have more than 32 columns. UNIQUE KEY Constraint Defined At Column Level ‘Syntax: () UNIQUE Example: CREATE TABLE branch_mstr (Branch_No Varchar2(10) Constraint Branchno_UNQ UNIQUE, Name Varchar2(20) Constraint Name_NN NOT NULL ); UINQUE Constraint Defined At the Table Level Syntax. CREATE TABLE tableName( (), (), UNIQUE(,{ColumnName2,.....])); Sql >CREATE TABLE Product Master ( Product_no Varchar2(6) , Des Varchar2(25), Qty_on_hand Number(8), Constraint prono_UNQ_UNIQUE(Product_no) ); Sql>CREATE TABLE FZ_SPDNOTE ( Fz_No Varchar2(i0) , Sp_No Varchar2(10), Empno Number, Constraint FzSpNo_CUNQ UNIQUE(Fz_No,Sp_No) ); PRIMARY KEY Constraint: Used to define key column of table. + It will not accepts Null Values and Duplicate values. + Ikis provided with an automatic index. + APrimary Key Constraint combines a NOT NULL and UNIQUE behavior in one declaration. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 49- Oracte 11g Material Restriction: + Only one Primary key Or Composite Primary Key is allowed per table. © PRIMARY KEY can not be implemented on columns having .... :LOB_.LONG .LONG RAW .VARRAY .NESTED TABLE () PRIMARY KEY Example: Sql>Create Table Incr(IncrId Number(4) Constraint Incr_Id_PK PRIMARY KEY, IncrDate Date NOT NULL, incrAmt Number(8,2) NOT NULL); PRIMARY KEY Constraint Defined At the Table Level CREATE TABLE tablentame( (), (), PRIMARY KEY(,[ColumnName2,....])); Example: Sql>CREATE TABLE Product_Master (Product_no Varchar2(6) ,Des Varchar2(25). Qty_on_hand Number(8), Constraint prono_PK PRIMARY KEY(Product:no) i SqlI> Create table SalesDet( Prodno Number(8), Custid Number(8), SalesDate Date NOT NULL, ‘SaleDesc Varchra2(20) NOT NULL,Constraint Prod_Cust_PK(Prodld,Custld) ); FOREIGN KEY (Or) REFERENTAIL INTEGRITY Constraint: + Foreign Key represent relationships between tables. + AForeign Key is @ column or group of columns whose values are derived from the Primary Key or Unique Key. * Foreign Key is column(s) that references a column(s) of a tatie and it can be the same table also. «The Table or View constraining the Foreign key is called the Child object. * Child may have duplicates and nulls but unless it is specified. + A Foreign Key constraint can be defined on a single key column either column level (In line) or Table level(Out of tine) column. + A composite Foreign Key on attributes should be declared at table level or out of line. + A Composite Foreign Key constraint, must refer to a composite unique key or a Composite Primary Key in the Parent Table. Restriction: ‘© Master table cannot be update if child record exists. The Foreign Key column cannot be applied on..... sLOB_ LONG LONG RAW .VARRAY .NESTED TABLE »DDD7>[>[[_[—— EE ‘ON DELETE Clause: + CASCADE option used to remove the child table record automatically , when parent record is removed. + Specify SET NULL if we want Oracle to convert dependent FOREIGN KEY values to NULL, to be Followed for Creating References Constraint: ‘Stepi: CREATE TABLE Dept (Deptno Number(2) Constraint Deptno_PK PRIMARY KEY, Dname Varchar2(20) Constraint Oname_NN NOT NULL, Loc Varchar2(20) Constraint Loc_NN NOT NULL); Step2: Create Detall/Child/Sub/Dependen + These are Tables which can contain Primary Key of their own as well as Foreign Key's referring to other Primary Master's or to themselves. ‘Sql>CREATE TABLE Emp( Empno Number(4) Constraint Empno_PK PRIMARY KEY, Ename Varchar2(20) Constraint Ename_NN NOT NULL, Job Varchar2(15) Constraint Job_NN NOT NULL, Mgr Number(4) Constraint Mgr_F_Self REFERENCES, Emp(Empno) ON DELETE SET NULL, Hiredate Date Constraint Hiredate_NN NOT NULL, Sal Number(8,2) Constraint Sal_NN’NOT NULL, Comm Number(8,2), Deptno Number Constraint Deptno_FkK REFERENCES Dept(Deptno) ON DELETE CASCADE ); orkin Cor ite PI RY KI Sql> CREATE TABLE FZ_SRV_Item( Fzno Varchar2(20) Constraint Fzno_PK PRIMARY KEY, Fatype Varchar2(20) Constraint Fztype_NN NOT NULL, Rdate Date Constraint Rdate_NNW NOT NULL ); Sql> CREATE TABLE FZ_SP_Item( Fzspno Varchar2(20) Constraint Fzspno_PK PRIMARY KEY,Fzstype Varchar2(20) Constraint fzstype NN NOT NULL, ‘Rspdate Date Constraint rspdate_NN NOT NULL ); Sql> CREATE TABLE FZ_DNote_Item( FznoRef Varchar2(20) Constraint Fznoref_FK REFERENCES FZ_SRV_Item(Fzno), FzspnoRef Varchar2(20) Constraint Fzspnoref_FK REFERENCES FZ_SP_Item(Fzspno), Dndate Date, Constraint fzref_Comp_PK PRIMARY KEY(F2noRef,FzspnoRef)); CHECK Constraint: + Used to impose a conditional rule on a table column, + Itdefines a condition that each row must satisfy, + Assingle columns can have multiple CHECK constraints that can reference the column in the definitions. «There is no limit to the number of CHECK constraints that can be defined ona column. + The CHECK constrains can be defined at the column level or Table level. Restrictions: + The constructs that cannot be include are © Queries to refer to values in other rows © References to the CURRVAL, NESTVAL,LEVEL or ROWNUM. © Calls to functions SYSDATE,UID,USER,USERENV, c Date constant that are not fully specified. Exampl: CREATE TABLE Dept( Deptno number(2) constraint dno_pk PRIMARY KEY constraint Deptno_Chk CHECK(Deptno BETWEEN 10 and 99), name varchar2(15) constraint dname_nn NOT NULL constraint Dname_Chk CHECK{Oname=UPPER(Dname)), Loc varchar2(15) default "NEW YORK’ constraint Loc_Chk CHECK (Loc IN('NEW YORK’, 'DALLAS', BOSTON','CHICAGO’)) ); Naresh i Technotogies, Opp. Satyam Theatre, Atwcerpet, Hyderabad, Ph: 23746666, 9000994008 - 51 - Oracle 11g Material ee CREATE TABLE Emp{ Empno Number(4) Constraint Empno_Pk PRIMARY KEY, Enamie Varchar2(20) Constraint ename_NN NOT NULL CHECK( SUBSTR(Ename,1,1) BETWEEN ‘A’ AND 'Z') AND Ename=UPPER(Ename)), Job Varchar2(15) Constraint Job_Chk CHECK(Job IN('‘ANALYST’,'CLERK','MANAGER','PRESIDENT','SALESMAN’)), Hiredate date DEFAULT SYSDATE, Sal Number(8,2) Constraint Sal_NN NOT NULL Constraint CHK_Sal CHECK(Sal BETWEEN 1000 and 10000), Comm number(8,2), Deptno Number(2), Constraint Tot_Sal_Chk CHECK(Sal+Comm<=100000) ) ; Default Option: * If values is not provided for table column default will be considered. + The options prevents NULL Values from entering the Columns, If a row is inserted without a value for a column. «The DEFAULT value can be a literal, an expression or a SQL Function. + The DEFAULT Expression must match the data type of the Column, Addin aint toa table: + A constraint can be added to a table at any time after the table was created by using by ALTER TABLE Statement, using ADD Clause. Syntax: Sql>ALTER TABLE
ADD [Constraint ] « Cons_Type(Column_Name,{ Column_Name,..]); Ae + The Constraint Name syntax is optional, but recommended. + Table Constraints are applied to table if data previously placed in the table violated such constraints. + We can ADD,DROP, ENABLE, or DISABLE a Constraint, but modify the structure. « NOT NULL,DEFAULT can be added to existing column by using the MODIFY Clause of the ALTER TABLE statement. ‘SqI>ALTER TABLE Emp ADD Constraint Empno_PK PRIMARY KEY(empno); SqI>ALTER TABLE Emp ADD Constraint Emp_Mgr_FK FOREIGN KEY(Mgr) REFERENCES Emp(empno); SqI>ALTER TABLE Emp ADD CONSTRAINT Dept_Dno_Fk FOREIGN KEY(Deptno) REFERENCES Dept MODIFY(Deptno NOT NULL); Sql> ALTER TABLE Emp MODIFY Empno number(3) Constraint empno_NN NOT NULL; Sql> ALTER TABLE Emp MODIFY Hiredate date default sysdate; Dl NG straints: To drop a constraint identify the constraint name the USER_CONSTRAINTS and USER_CONS_COLUMNS Data dictionary views. + The ALTER TABLE Statement is used with the DROP Clause. * The CASCADE Option of the DROP Clause causes any dependent consisaints also to be dropped. + When a constraint is dropped, the constraint is no longer enforced and is no longer available in the data dictionary. yntax: ‘ALTER TABLE
DROP PRIMARY KEY/UNIQUE(Column)/ CONSTRAINT Constraint_Name[CASCADE]; Note: When drop the PRIMARY KEY/UNIQUE Constraints the related ! DEX will drop automatically. SqI>ALTER TABLE Emp DROP PRIMARY KEY; SqI>ALTER TABLE Dept DROP UNIQUE(Dname); SqI>SELECT index_name from user_indexes WHERE table_nam EMe; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000" 08. 52- Oracle 11g Material ——_—_——>_—————————— DI: sLIN' straint: + The constraint can be disabled without dropping it or recreating it. + The ALTER TABLE statement Is used with the DISABLE Clause. ‘Syntax; ALTER TABLE DISABLE CONSTRAINT[{CASCADE]; Guideline: + The CASCADE clause disable dependent integrity constraints. Example: ‘Sql> ALTER TABLE Emp DISABLE CONSTRAINT Empno_PK CASCADE; ENABLE Constraint: © The constraint can be eriabled without dropping it or recreating it. * The ALTER TABLE statement is used with the ENABLE Clause. Syntax: ALTER TABLE
ENABLE CONSTRAINT ; * Enabling a Constraint applied to all the data in the table. + When an UNIQUE or PRIMARY KEY Constraint is ENABLED , the UNIQUE or PRIMARY KEY Index is automatically created. Sql>ALTER TABLE Emp ENABLE CONSTRAINT Mgr_FK; VIEWING Constraints: * To View all Constraints on table by Query the USER_CONSTRAINTS table, + The Codes that are revealed are.... o P-Primary U-Unique 7 ° R-References C-Check & Not Nutt ‘Sql> SELECT owner,constraint_name,constraint_type FROM user_constraints : WHERE table_name='FZ_SRV_ITEM'; VIEWING The Columns Associated with Constraints: ‘+ The Names of the columns that are involed in constraints can be know by ~ querying the USER_CONS_COLUMNS Date Dictionary View. ‘Sql>SELECT constraint_name,column_name FROM USER_CONS_COLUMNS WHERE table_name=" Z_SRV_ITEM'; Note: When drop the table all corresponding Integrity Constrains will droped automatically. gee: 1)Examine the structure of the EMPLOYEES table: EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25) Which three statements inserts a row into the table? (Choose three) A. INSERT INTO employees VALUES (NULL, 'JOHN','SMITH'); B, INSERT INTO employees( first_name, last_name) VALUES (‘JOHN','SMITH'); C. INSERT INTO employees VALUES ('1000', JOHN’, NULL’); D. INSERT INTO employees(first_name,last_name, employee_id) VALUES ('1000', john','Smith’); E. INSERT INTO employees (employee _id) VALUES (1000); E. INSERT INTO employees (employee_id, first_name, last_name) VALUES ( 1000,'john',’*); 2) Which syntax turns an existing constraint on? ‘A. ALTER TABLE table_name ENABLE constraint_name; Naresh i Technologies, Opp. Satyau Theatre, Ameerpet, Hyderabad, 3746666, 9000994008 - $3- ' 1 Gracte 11g Material _—e B, ALTER TABLE table_name STATUS = ENABLE CONSTRAINT constraint _ name; C.ALTER TABLE table_name ENABLE CONSTRAINT constraint _ name; D.ALTER TABLE table_name STATUS = ENABLE CONSTRAINT constraint _ name; E.ALTER TABLE table_name TURN ON CONSTRAINT. constraint _ name; F. ALTER TABLE table_name TURN ON CONSTRAINT constraint _ name; 3) You need to modify the STUDENTS table to add a primary key on the STUDENT_ID column. The table is currently empty. Which statement accomplishes this task? A. ALTER TABLE students ADD PRIMARY KEY student_id; B. ALTER TABLE students ADD CONSTRAINT PRIMARY KEY (student _ id); C. ALTER TABLE students ADD CONSTRAINT stud_id_pk PRIMARY KEY (student _ id); D.ALTER TABLE students ADD CONSTRAINT stud _ id _pk PRIMARY KEY student _ id; E. ALTER TABLE students MODIFY CONSTRAINT stud _ id _pk PRIMARY KEY (student _ id); 4)Which SQL statement defines the FOREIGN KEY constraint on the DEPTNO columi: of the EMP table? ‘A.) CREATE TABLE EMP (empno NUMBER(4), ename VARCNAR2(35), deptne NUMBER(7,2) NOT NULL CONSTRAINT emp_deptno_fk FOREIGN KEY deptno REFERENCES dept deptno); . 8) CREATE TABLE EMP (empno NUMBER(4), ename VARCNAR2(35), deptno NUMBER(7,2) CONSTRAINT emp_deptno_fk REFERENCES dept (deptno)); C) CREATE TABLE EMP (empno NUMBER(4) ,ename VARCHARZ(35), deptno NUMBER(7,2) NOT NULL, CONSTRAINT emp_deptno_fk REFERENCES dept (deptno) FOREIGN KEY (deptno)); 0. CREATE TABLE EMP _(empno NUMBER(4), , ename VARCNAR2(35), deptno NUMBER(7,2) FOREIGN KEY CONSTRAINT emp_deptno_fk REFERENCES dept (deptno)); 5)Updating a Primary key value will be allowed by Oracle when it he: dependent records, A)True B)False ©)None 6)The allows for automatic make it null value of child record when a parent record is deleted. A) Add constraint B) Drop Constraint ©} On delete cascade D) None Naresh i Teclmologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 906: 008° ~54~ Oracle 11g Material DISPLAYING DATA FROM MULTIPLE TABLE ‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008. - 55 - Oracle 11g Material JOINS: When data from more than one table in the database is required, a join condition is used. Rows in one table can be joined to rows in another table according to common values existing in corresponding columns, that is, usually primary and foreign key columns. To display data from two or more related tables, write a simple join condition in the WHERE clause. * Use a join to query data from more than one table. * AJoin is Query that combines rows from two or more tables, Views, or Materialized Views. © A Join is performed whenever multiple table appear in the Queries FROM clause Sql>Select Empno,Ename,Dname,Loc From Emp,Dept ; ‘Sql>Select Empno,Ename,Sal,Grade From Emp,Salgrade; Sql>Select Empno,Ename,Dname,Loc,Grade From Emp,Dept,Salgrade Sql> Select Empno,Ename,Emp.Deptno,Oname,Loc From Emp,Dept + The Applied condition is called a JOIN CONDITION. + To Execute a join... + Oracle combines pairs of rows, each containing one row from each table, for which the JOIN condition evaluates to TRUE. + The column in the join condition need not be part of the SELECT list. + The WHERE clause of join Query can also contain other conditions that refer to columns of only one table. + Ifa join involves over two tables then oracle joins the first two based on the condition and then compares the result with the next table and so on Table1 | ——> Join 01. . <—- Table 2 + Result 01 ————> Join 02 <———Table | Result 02 + The oracle optimizer determines the order in which ORACLE should join thetables based on..... * Given JOIN condition(s) + INDEXES upon the tables. * The LOB columns cannot be specified in the WHERE clause, when t!:c WHERE clause contains any JOINS. + The LOB columns cannot be specified in the WHERE clause, when the WHERE clause contains any JOINS. Syntay WHERE tablel.columni = table2.column2; * When writing a SELECT statement that joins tables, precede the coiimn name with the table name for clarity and to enhance database access. * If the same column name appears in more than one table, the c. mn name must be prefixed with the table name, + To join n tables together, you need a minimum of n-1 join conv‘'tions. For example, to join four tables, a minimum of three joins is required. "rule may not apply if your table has a concatenated primary key, in which case more than one column is required to uniquely identify each row.For more information, Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000" 108 - 56. : Oracle 11g Materiat —————————— ui Join or Simple Joins or Inner Joins: * Based on equality. condition tables are joined, * Only matching records are displayed. * . Joining tables must have at least one common column with same data type and same values. (not column name same.) Qualifying Ambiquous column names: + The name of the columns names should be qualified in the WHERE caluse with the table name to. voied ambiguity. + If there are no common column names between the two tables,the qulifiction is not necessary but it is better. Syntax: Sql> Select colt ,col2,c0l3... From ,. Where .=. And (This is join condition) Sql>Select_ Emp.Empno Empno, Emp .Ename Ename, Emp.Deptno Deptno, Dept.Deptno Deptno, Dept.Oname Dname, Dept.Loc Lac Fram Emp,Dept Where Emp,Deptno=Dept.deptno; Sal> Select Empno ,Ename,Emp.Deptno Deptno, name From Emp, Dept x‘ Where Emp.Deptno=De}:*.deptno Empno=&eno; Sql> Select Empno ,Ename,Emp.Deptno Deptno,Dname From Emp,Dept Where Emp.Deptno=Dept.deptno Job=UPPER('clerk’); SqI> Select Empno ,Ename,Sal*12 AnnuSal,Emp,Deptno,Loc From Emp,Dept ‘Where Emp.Deptno=Dept.deptno And. Oname="SALES’ Using Table Aliase: Qualifying column names with table names can be very time consuming, particularly if table names are lengthy. You can use table aliases instead of table names. Just as a column alias gives a column another name, a table alias gives a table another name. Table aliases help to keep SQL code smaller, therefore using less memory. The table name is specified in full, followed by a space and then the table alias. The EMP table has been given an alias of ‘e’, and the DEPT tabie has an alias of 'd’ Guidelines: * Table aliases can be up to.30 characters in length, but the shorter they are the better, + Ifa table alias is used for a particular table name in the FROM clause, then that table alias must be substituted for the table name throughout the SELECT statement. + Table aliases should be meaningful. + The table alias is valid only for the current SELECT statement. Sql> Select £.Empno ,E.Ename,D.Deptno D.Dname From Emp E,Dept D Where E.Deptno=D.Deptno; Sql> Select E.Empno ,E.Ename,E.Job,D.Deptno D.Oname From Emp E,Dept D Where E,Deptno=D.Deptno E.Job IN('MANAGER’/SALESMAN’); Sql> Select £.Empno ,£.Ename,£.Job,O.Deptno D.Oname From Emp E,Dept O Where €.Deptno=D.Deptno AND D.Oname<>’SALES'; Non Eq: ‘A non equi-Join specifies the relationship between columns belonging to different tables by making use of the relational operations other than =, * Itis used to join table if value of one column a table falls the range of two column values of other table. * It used between operator, it called as Between join. Naresh i Technologies, Opp. Satyam Theatre, Amcerpet, Hyderabad, Ph: 23746666, 9000994008 - $7- Oracle t1g Material cocaine Syntax:- Select COl1,COlZ,.nnnee From
,
Where .Between
.and
.; ‘Sq|> Select E.empno,£.Ename,E.Sal,S.Grade,S.Losal,S.Hisal From Emp E,Salgrade S Where E.Sal Between S.Losal and S.Hisal; Sql> Select E.empno,£.Ename,E.Sal,S.Grade,S.Losal,S.Hisal From Emp E,Saigrade S Where E.Empno=&Eno And E.Sal Between S.Lesal and S.Hisal; ‘Sql> Select E.empno,£.Ename,E,Sal,S.Grade From Emp E,Salgrade S Where (E.Sal>=S.Losal And E,Sal<=S.Hisal) And S.Grade=1} Self Joins: Self Joini- It indicates joining the table to itself. * The same table appears twice in the FROM clause and is followed by table aliases. The table alias2s must qualify the column names in the join condition. It is used on seme table the table must have at least 2 column with same. o Data type. o Value + To perform a self join, oracle combines and returns rows of the table that satisfy the join condition. ‘Syntax: ‘ Sql>Select Columns From Table? T1,Table1 12 Where T1.Columni =T2,Column2; Example: ‘Sql>Select E.Ename “Emp Name",M.Ename "Manager Name” From Emp €,Emp M Where E.Mgr=M.Empno; Sql> Select E.Ename “Emp Name",M.Ename “Manager” From Emp E,Emp M Where E.Mgr=M.Empno And E.Hiredate Select E,Ename| |'Emp Name’,M.Enamel| ‘Manager Name’ From Emp E, Emp M Where E.Mgr=M.Empno; Sql> Select E.Ename ||'Works for'|| M.Ename "Employees and Managers" From Emp E,Emp M Where (E.Mgr=M.Empno); Sql> Select E.Ename ||""s Works for'|| M.Ename "Employees and Managers" From Emp E,Emp M Where (E.Mgr=M.Empno) And E.Job='CLERK' Cartesian Product: « A Cartesian product results in all combinations of rows displayed. This is done by either omitting the WHERE clause or specifying the CROSS JOIN clause. + During Cartesian product oracle combines each row of one table with each row of the other. + Ittends to generate a large number of rows and the result is rarely useful. * A Cartesian product is formed when: © Ajoin condition is omitted. © Ajoin condition is invalid. + All rows in the first table are joined to all rows in the second table. + To avoid a Cartesian product, always include a valid join condition in a WHERE clause. Sql>Select Ename,Job,Dname From Emp,Dept; Sql>Select Ename,Job,Dname From Emp,Dept Where Job="MANAGER’; Quter Joins: Used to retrieve all the rows from one table but matching rows from other table. * An Outer join extends the result of a simple or inner join. + An OUTER join returns all rows that satisfy the join condition and also Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 907994008 - $8- Oracle 11g biatesial ——————_—_—[_—___—————————— those rows from one table for which no rows from the other satisfy the Join condition. + This use an operator (+},{t called join operator. + (4) used with the table which missing the data. + To perform an outer join of table ‘A’ and °B’ and returns all rows from ‘A’, apply the outer join operator (+)'to all columns of table’. + For all rows in ‘A’ that have no matching rows in ‘B oacle returns null for any select list expressions containing columns of ‘8’. Sql>Select Tablel.Column,Table2.Column From Tablet, Table2 Where Table1.Column(+)=Table2,Column; Sql>Select Tablel.Column,Table2.Column From Tablet ,Table2 Where Tablel.Column=Table2.Column(+); “Dept” “emp” “The Outer table” “The Outer table” corresponding ORACLE ae table will returned even if no Record exists in outer table, Output in SOL* PLUS Rules And Restrictions: ‘* The (+) operator can appear only in the WHERE clause. + If'A’ and 'B’ are joined by multiple join conditions, we must use the (+) operator in all of these conditions, * (+) used only with one table. * A condition cannot use the IN comparison operator to compare a column marked with the(+) operator with an expression, + Accondition cannot compare any column marked with the (+) operator with a sub Query, Sql> Select €.Ename,O.Deptno,D.Dname From Emp E,Dept D Where E.dentno(+)=0.deptno ORDER BY E.Deptno; Sql> Select E.Ename,D.Deptno,D.Oname From Emp E,Dept D Where E.deptno=D.Deptno(+) E.deptno(+)=10 ORDER BY E,Deptno; Sql> Select E.Ename "Employe", NVL(M.Ename,’ Supreme Authority’) “Manager"From Emp E,Emp M Where E.MGR=M.Empno( +); Joining Data From More than Two Table: : « JOINS can be establish on more than two tables. «The Join is First executed upon the two most relevant tables and then the result is applied upon the Third Table. Sql>Select E.Ename Enam2,£.Deptno,M.Ename Manager, M.deptno From Emp €,Dept D,Emp M Where E.Mgr=M.Empno And E.deptno=D.Deptno; Naresh i Technologies, Opp. Satyam Theatre, Amzerpet, Hyderabad, Phi: 23746666, 9000994008 - 39 - Oracle 11g Material ———————————————————— Sql> Select E.Ename Ename, M.Ename Manager, D.Dname Dname, E.Sal Esat, SE.Grade Egrade,M.Sal Msal, SM.Grade Mgrade From Emp E,Dept D,Emp M,salgrade SE, Salgrade SM Where (E,Deptno=D.Deptno) And (E.Mgr=M.Empno) And “(E,Sal BETWEEN SE.Losal And SE.Hisal) And (M.Sal BETWEEN SM.Losal And SM.Hisal); Categories Of Join: Oracle Proprietary Joins(8i And Prior) Equi Join Non-Equi Join Outer Join Self Join Cartesian Join 999 Compliant Joins: Inner Join Cross joins Natural Join Using Clause Full Or Two Sided Outer Join Arbitrary Join conditions for outer joins 180 or ANSI Joins: Cross join: ‘+ CROSS JOIN Returns a Cartesian product from the two tables, Sql>Select Ename,Dept.Deptno,Dname,Loc From Emp CROSS JOIN Dept Where Emp.Deptno=Dept.Deptno; ‘Natural Join: Sql>Select Empno,Ename,Sal,Deptno,Dname,loc From Emp Naturat Join Dept; ANSI Note:-Natural not accept a alias names, Creating Joins with the USING Clause : + If several columns have the same names but the data types do not match, the NATURAL JOIN, * Clause can be modified with the USING clause to specify the columns that: should be used for an equi join, Use the USING clause to match only one column when more than ane column * matches. Dornot use a table name or alias in the referenced columns. The NATURAL JOIN and USING clauses are mutually exclusive. ‘Sql> SELECT e,ename, d.dname FROM Emp e JOIN dept d USING (deptno) WHERE deptno =10 Inner Joi Sql>Select e.Empno,e.Ename,e.Sal,e.Deptno, d.Dname,d.Loc From Emp e INNER JOIN Dept d ON(e,Deptno=d.Deptno); Sql>Select e.Ename "Employee Name",m.Ename "Manager" From Emp e INNER JOIN Emp m ON(e.mgr=m,empno); Join on more than two tables: Sql> Select Ename,e.Sal,Grade,D.Deptno,Dname From Emp £ JOIN Dert D ON E.Deptno=D.Deptno JOIN Salgrade ON E.Sal BETWEEN sal And Hisal; Sqi> Select E.Ename,M.Ename,Sal,Grade,D.Deptno,Dname From Er © INNER JOIN Dept D ON E.Deptno=D,Deptno INNER JOIN Emp M ON E.MGR=M.Empn: INNER JOIN Salgrade S ON E.Sal BETWEEN Losal . ...d Hisal; Left Outer Join: Sql>select a.empno,a.ename,a.sal,b.deptno, b.dname,b.loc from “mp a left outer join dept b on(a.deptno=b.deptno); Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90005 "98-60 Gracie 11g Material Rigth Ourter Join: Sql>select a.empno,a.ename,a.sal,b.deptno, b.dname,b.loc from emp a right outer join dept b on(a.deptno=b.deptna); Full outer Join ‘Sqi>select a.empno,a.ename,a.sal,b.deptno, b.dname,b.loc from emp a full outer join dept b on(a.deptno=b.deptno); Note:- Full outer join=left outer join+Right outer join. ‘Some Special Example: Sql>Select ¢.Ename “Employee Name",m.Ename "Manager" From Emp e LEFT OUTER JOIN Emp m ON(e,mgr=m.empno) Order by 2; 1)What is the out put of the following Query. >Select e,ename,e.deptno,e,sal,d.d/iame,d.loc From emp e,dept d Where e.deptno(+)=d.deptno(+); 2) Display all the employees who earn more than their manager's salary >SELECT A.EMPNO FROM EMP A,EMP B WHERE B.EMPNO=A,MGR AND A.SAL>B.SAL; 3)Examine the data in the EMPLOYEES and DEPARTMENTS tables. EMPLOYEES : 0 LAST_NAME DEPARTMENT_ID SALARY Getz 10 3000 Davis 20 1500 Bill 20 2200 Davis 30 5000 Kochhar 5000 DEPARTMENTS : DEPARTMENT_ID DEPARTMENT_NAME 10 Sales 20 Marketing 30. ‘Accounts 40 Administration You want to retrieve all employees, whether or not they have matching departments in the departments table. Which query would you use? A. SELECT last_name, department_name FROM employees , departments(+); B.SELECT last_name,department_nameFROM employees JOIN departments(+); C. SELECT last_name, department_name ON(e. department_ id = d. departments_id); FROM employees(+) € JOIN departments d D. SELECT last_name, department_name FROM employees e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id); E, SELECT last_name, department_name — FROM employees(+) , departments ‘ON(e.department_id=d.department_id); F, SELECT last_name, department_name FROM employees e LEFT OUTER JOIN departments d ON(e. department _ id = d, department _id); \ | 4)Joining of a table to itself is called ‘A)Outer Join B)Full Outer Join C)Codd Join D) Self Join eee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 61 ~ Join a Oracle Lg Material 5)Table aliases are used to make multiple table queries shorter and readable. ATrue B)False None 6)To retrieve rows which do not satisty a query, the outer join concept can be used, A)True B)False C)None 7)Examine the description of the EMPLOYEES table: MP_ID NUMBER(4) NOT NULL LAST_NAME VARCHAR2(30) NOT NULL FIRST_NAME VARCHAR2(30) DEPT_ID NUMBER(2) JOB_CAT VARCHAR2(30) SALARY NUMBER(8,2) Which statement shows the department ID, minimum salary, and maximum. salary paid in that department, only of the minimum salary is less then 5000 and the maximum salary Is more than 15000? A. SELECT dept_id, MIN(salary(, MAX(salary) FROM employees WHERE MIN(salary) <5000 AND MAX (salary) > 15000; B. SELECT dept_id, MIN(salary), MAX(salary). FROM employees WHERE MIN(salary) < 5000 AND MAX(salary) > 15000 - GROUP BY dept_id; C. SELECT dept_id, MIN(salary), MAX(salary) FROM employees HAVING MIN(salary) <5000 AND MAX (salary) > 15000; D. SELECT dept_id, MIN(salary), MAX(salary) FROM employees GROUP BY dept_id HAVING MIN (salary) < 5000 AND MAX(salary) E. SELECT dept_id, MIN(salary), MAX(salary) FROM employees ‘GROUP BY dept_id, salary HAVING MIN (salary) <5000 ‘AND MAX (salary) > 15000; 8)Examine the structure of the EMPLOYES, DEPARTMENTS, and LOCATIONS tables. EMPLOYEES EMPLOYEE_ID NUMBER NOT NULL,Primary Key EMP_NAME VAR CHAR2 (30) JOB_ID VAR CHAR2 (20) SALARY NUMBER MGR_ID NUMBER References EMPLOYEE_ID column DEPARTMENT.ID NUMBER Foreign key to DEPARTMENT_ID column of the DEPARTMENTS table DEPARTMENTS DEPARTMENT_ID NUMBER NOT NULL, Primary Key DEPARTMENT_NAME VARCHAR2 (30) MGR_ID NUMBER References NGR_ID column of the EMPLOYEES table LOCATION ID NUMBER Foreign key to LOCATION_ID column of the LOCATIONS table LOCATIONS LOCATION_ID NUMBER NOT NULL, Primary Key CITY VARCHAR2 (30) Which two SQL statements produce the name, depariment name and the city of ali the employees who earn more then 10000? (Choose tw. } A, SELECT emp_name, department_name, city FROM employees e JOIN departments d USING (department_id) JOIN locaticns 1 USING (location_id) WHERE salary>1000 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 900099: - 62. Oracle 11g Maieriat ———— B, SELECT emp_name, department_name, city FROM employees e, departments d, locations 1 JOIN ON (e.department_id = d.department id) AND (d.location_id =1.location_id) AND salary > 10000; C. SELECT emp_name, department_name, city FROM employees e, departments d, locations 1 WHERE salary > 10000; D. SELECT emp_name, department_name, city FROM employees e, departments d, locations 1 WHERE e.department_id = d.department_id AND d.location_id = L.location_id AND salary > 10000; , SELECT emp_name, department_name, city FROM employees @ NATURAL JOIN departments, locations WHERE salary > 10000; 9)Examine the following output from SQL*Plus: PRODUCT.ID PRODUCT.NAME BOX.LOCATION 57-X WIDGET IDAHO 456-Y WIDGET TENNESSSEE Which of the following choice identify the type of query that likely produced this result, A).Full outer join B)Left outer join C) Rigth outer join D)Equijoin Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 63 - Oracle 11g Material TYPES OF QUERY Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90005 8 - 64 ‘ Oracle 11g Material ——————————————————— Types of Query: ‘© Root Query ‘+ Parent Query(or)Outer Query (or)Matn Query + Child Query(or)Inner Query(or) sub Query Root Query:~ + The query which is not depend on any other query for its conditions value. (er) Independent query. Example:- ‘Sql>Select ename,sal from emp Where Deptno= 10; Parent Query: ‘The query which depend on any other query for its condition value. ‘Sub Query :- © The query which provides, conditional values to its parent query. + Assub Query in the WHERE clause of a SELECT statement is called as NESTED ‘SUBQUERY. \ + Assub Query in the FROM clause of a SELECT statement is called as INLINE\ VIEW. « Assub Query can be part of a column, in the SELECT list Sub Query can contain another sub query + Oracle imposes no limit on the number of sub query levels in the FROM clause of the Top-Level Query. 8G Within the WHERE clause up to 255 sub queries can be nested. To make the statement easier for readability ,qualify the columns in a Sub Query with the table name or table alias. Note: parent query and sub query both are combined, Purpose of a Sub Query: To define the set of rows to be inserted into the target table of an INSERT or CREATE TABLE statement. + To define the set of rows to be included in a View or a Materialized INSERT or CREATE TABLE statement. * To define one or mozre values to be assigned to existing rows in UPDATE statement. + To provide values for condition in a WHERE clause, HAVING clause, START WITH clause of SELECT,UPDATE, and DELETE statements. SUB QUERY Principle: * Solve a problem by combining the two queries, placing one query inside the other Query. * The inner query or the sub query returns a value that is used by the outer query upon the main query. su age: + A Sub Query is a SELECT statement that is.embedded in a clause of another SELECT statement. + We can build powerful statements out of simple ones by using Sub Queries. + They can be very useful when you need to select rows from a table with a condition that depends on the data in the table itself. Syntax; Sql>SELECT select_list FROM table WHERE Column name/expr operator(SELECT select_list FROM table); Comparison conditions fall into two classe: + Single -row operators (>, =, >=, <, <>, <=) + Multipte-row operators (IN, ANY, ALL). Single row sub Query: ‘* These queries returns only one row from the Inner SELECT statement. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 65 - i Oracle 11g Material Multiple row sub query: * These queries returns more than one column from the Inner SELECT statement. Guidetin ing Subqueries: + Enclose Sub Queries in parentheses. + "Place Sub Queries on the right side of the comparison condition., + The ORDER BY clause in the Sub Query is not needed unless you are performing top-nanalysis. + Only one ORDER BYclause can be used for a SELECT statement. + Two classes of comparison conditions are used in Sub Queries: © Single-row operators ~ © Multiple-row operators, ‘Simple Sub Que! elated Sub Query a parent query will be executed first and based on the out put of outer query the inner query execute, If Parent Query returns N rows inner query executed for N times. Simple Sub Query with Single Row: Sql>Select Empno,Ename,Sal,Deptno From Emp Where Sal<(Select Sal From Emp Where Empno=7566 ); Sql> Select Empno,Ename,Job From Emp Where Job=(Select Job From Emi: Where Ename=UPPER(‘ford’) ) and Ename='FORD'; Sql> Select Empno,Ename,Hiredate,Sal,Job From Emp Where Hiredate> (Select Hiredate From Emp Where Ename="MILLER' ) Order by Sal; Sql> Select Empno,Ename,Sal,Job From Emp Where Deptno=(Select Deptno From Dept Where Dname="SALES' ); Sql> Select Empno,Ename,Sal,Job From Emp Where Deptno=(Select Deptno From Dept Where Loc='NEW YORK’ )'And Job='CLERK’; Sql> Select Empno,Ename,Sal,Job From Emp Where Deptno=(Select Deptno From Dept Where Dname='SALES' ); ‘Sql> Select Empno,Ename,Sal,Comm,Sal+NVL(Comm,0) From Emp Where Deptno=(Select Deptno From Dept Where Loc="CHICAGO' ); Sql>Select *From Emp Where Deptno=(Select Deptno From Emp Where Ename='FORD')AND Job IN(Select Job From Emp Where Deptno=(Select Deptno From Dept Where Dname='SALES')); Appling GROUP functions in SUB QUERIES: « The data from the main query can be displayed by using a Group Function is a Sub Query. * As a Group Function returns a single row, the query passes the success state.The inner sub query should not have a GROUP BY Clause in this scenario. Examples: SqI>SELECT ename,job,sel FROM emp WHERE sal= emp )i. Sql> SELECT ename,job,sal FROM emp WHERE sal=(SELECT Min(sal) FROM emp ‘SELECT Max(sal) FROM Sql>SELECT ename,job,sal FROM emp WHERE sal>(SELECT Avg(sal) FROM emp vi Sql>SELECT ename,job,sal FROM emp WHERE sal<(SELECT Varlance(sal) FROM emp); Appling #AVING Clause With SUB QUERIES: + ASub Query can be also applied in HAVING Clause. + The Oracle server executes the sub query, and the result are returned into the HAVING Clause of the Main Query. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph:'23746666, 9000994008 - 66- racte 1g Material Examp! ‘Sql>SELECT deptno,Min(sal) FROM emp GROUP BY deptno HAVING Min(sal)> (SELECT Min(sal) FROM emp WHERE deptio=20 ); ‘Sql>SELECT job,Avg(sal) FROM emp GROUP BY job HAVING Avg(sal)= (SELECT Min(Avg(sal)) FROM emp GROUP BY job ); ‘Sql> SELECT job,Avg(sal) FROM emp GROUP BY job HAVING Avg(sal)< (SELECT Max(Avg(sal)) FROM emp GROUP BY job ); Sub Query Returns more than one row: « Subgueries that return more than one row are called Multiple-row Sub Queries, + We use a multiple-row operator, instead of a Single-Row operator, with a Multiple -row Sub Query. The multiple-row operator expects one or more values, Use multiple-row comparison operators IN Equal to any member in the list co ANY/SOME >Compare value to each value returned by the Sub Query. o ALL > Compare value to every value returned by the Sub Query. Sql>SELECT ename,sal,deptno FROM emp WHERE sal IN(SELECT MAX(sal) FROM emp GROUP BY deptno ); Sql>SELECT ename,sal,job,deptno FROM emp WHERE sal IN(SELECT MAX(sal) FROM emp GROUP BY job ); Sql>SELECT ename,sal,deptno FROM emp WHERE sal IN(SELECT MIN(sal) FROM ‘emp GROUP BY deptno); ANY Operator Sql> SELECT ename,sal,deptno FROM emp WHERE sal SELECT ename,sal,deptno FROM emp WHERE sal SELECT ename,sal,deptno,Job FROM emp WHERE sal 'MANAGER’); Sql>Select Empno,Ename,Sal,Deptno From emp Where Sal>ANY(Select Sal From Emp where deptno=16 );, rte NY /SOME. ans less than the Maximum vaiue in the list. Sql> SELECT ename,sal,deptna FROM emp WHERE sal >SOME(1250,1500,1600); SqI>SELECT ename,sal,deptno FROM emp WHERE sal >ANY(SELECT sal FROM emp Where Job=/SALESMAN’); lote:>ANY/SOME mi is More than the Mini value in the list Sql> SELECT ename,Job,Deptno FROM emp WHERE sal =ANY(SELECT sal FROM emp Where Job='MANAGER' —_) Note =ANY it is equivalent to In operator. All Operator: Sql> Select Ename,Job,Sal,Deptne From Emp Where Sal>ALL(Select Sal From Emp Where Deptno=30); Sql> Select Ename,Job,Sal,Deptno From Emp Where Sal>ALL(Select AVG(Sal) From Emp Group by Deptna); Note:>ALL >it means more than the maximum in the list, Sql> Select Ename,Job,Sal,De; Emp Group by Deptno); Note:it means less than the minimum value in the list, Sub Query Returnin Itiple Columns: * In sub Queries muitiple columns can be compared in the WHERE clause, by writing a compound WHERE clause using logical operator. mno From Emp Where SalSelect Columnt,Column2,... From Table Name Where (Column a, Column b,.....) IN(Select Column a, Column B,... From TableName Where Condition); + The column comparisons in a multiple column sub Query can be. Pair wise comparison. Non pair wise comparison. + Pair wise comparisons Each candidate row in the SELECT statement must have both the same values associated with each column in the group. + The Non pair wise comparison, the candidate row must match the multiple conditions in the WHERE clause but the values are compared individually. Pair wise Comparison or compound WHERE clause based SubQuery Sql>Select Ename, Sal, Deptno From Emp Where (Deptno,Sal) IN(Select Deptno,Max(Sal) From Emp Group by Deptno) And Deptno<>10; ir wise Comparison or compound WHERE clause based Sub Quer: Sql>Select Ename,Sal,Deptno From Emp Where Deptno IIN(Select Deptno From Emp Group by Deptno) And Sal IN(Select Max(Sal) From Emp Group by Deptno) ‘And Deptno<>10; Null Vaiucs in a Sub Query: + One of the values returned by the inner query is a null value, and hence the entire query returns no rows. The reason is that all conditions that compare a null value result in a null. * So whenever NULL values are likely to be part of the results set of a Sub Query, do not use the NOT IN operator. The NOT IN operator is equivalent to <> ALL operator, Sql> Select E.Ename From Emp E Where E.Empno IN(Select M.Mgr From Emip M ); * A Sub Query in the from clause is equivalent to a view. * The Sub Query in the from clause defines a Data source for that particular ‘SELECT statement. Sql>Select d.Deptno,d.Oname,v.cnt From Dept d, (Select Deptno,Count(*) cnt From Emp Group by Deptno ) v Where d.Deptno=v.Deptno And cnt>3; Sql>Select__ E.Ename,E.Sal,E.deptno,S.Salavg From Emp __E,(Select Deptno,AVG(Sal) Salavg , From Emp Group By Deptno) S Where E,Deptno=S.Deptno AND E.Sal>S.Salavg; Sql> Select Deptno,SUM(Sal), SUM(Sal)/Tol_Sal*100"Salary%" Fro::. Emp, (Select SUM(Sal) Tol_Sal From Emp ) Group by Deptr:: Tol: Sal; Sql> Select E.EmpCount,D.DeptCount From(Select COUNT(*) EmpCount From Emp) E, (Select COUNT(*) DeptCount From Det )D; Sql>Select E.EmpCount,D.DeptCour'.5.GradeCnt, E.Empcount +D.DeptCount+S.GradeCnt TotalRecCnt From(Select COUNT(*) EmpCount From Emp) E, (Select COUNT(*) DeptCount From Dept )D, (Sel ’ COUNT(*) GradeCnt From Salgrade)S; 4 Sql>Select A.Deptno "department Number", (A.NumEmp/B.TotalCo.:)*100 “9@Employees", (A.SalSum/B.TotalSal)*100 "%Sala NumEmp, From(Select Dept >unt(*) Naresh i Tecinologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90: “008 - 68 - Oracle 11g Material SUM(Sal) SalSum From Emp Group By Deptno) A, (Select COUNT(*) TotalCount, — SUM(Sal) TotalSalFrom Emp)B; ‘Sub Select Statements: © These are SELECT statements declared as part of the SELECT list. Sql>Select Ename,Sal, (Select SUM(Sal) From Emp) “organizaton TolSal’ From Emp; Sql> Select Ename,Sal,(Select MAX(Sal) From Emp) “organizaton Maximum Salary", (Select MIN(Sal) From Emp ) “organizaton Lowest Salary" From Emp; Co-related Sub Queries: + It is another way of performing Queries upon the data with a simulation of Joins. ‘Syntax Sql> SELECT column1, column? FROM tablet T_Aliast WHERE columni operator (SELECT colum3, column2 FROM table2 t_Alias2 WHERE T_Aliasi.Column Operator T_Alias2.Column di ‘Steps Performed ; Parent Query processed first, Passes the Qualified column value to the sub query WHERE clause. Get a candidate row (fetched by the outer query), Execute the inner query using the value of the candidate row. Use the values resulting from the inner query to qualify or disqualify the candidate + Repeat until no candidate row remains. © Returns true if inner query is success other wise False Sql> Select Empno,Ename,Sal,Deptno From Emp Where Deptno=10 AND EXISTS (Select COUNT(*) From Emp Where Deptnc 0 AND Job="ANALYST’ Group By 3ob Having COUNT(*)>5); Note: In the case Group by clause become as dummy clause so without using group by we can use having. Sql> Select Empno,Ename,Sal,Deptno From Emp Where Deptno=30 AND EXISTS(Select COUNT(*) From Emp Where Deptno=10 AND Job='SALESMAN' Having COUNT(*)>3); ‘Sql>Select Deptno,Dname From Dept D Where EXISTS (Select * From Emp E Where D.Deptno=E,Deptno); Sql>Select Deptnc,Oname From Dept D Where NOT EXISTS(Select * From Emp £ Where D.Deptno=E.Deptno ); Sql> Select P.Ename From Emp P Where EXISTS(Select *From Emp C Where C.Empno=P,MGR); ‘Sql> Select P.Ename From Emp P Where NOT EXISTS(Select * From Emp C Where C.Empno=P.MGR ); Sql> Select P.Ename From Emp P Where EXISTS(Select * From Emp C Where C.MGR=P.Empno ); eee ‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 69 - Oracle 11g Material ‘Sql> Select P.Ename From Emp P Where NOT EXiSTS(Select * From Emp C Where C.MGR=P.Empno); ‘Sql>Select Empno,Ename,£.Deptna,Sal,MGR From Emp E Where E.Sal>ANY (Select M,Sal FROM Emp M Where M.Empno=E.MGR }; Examine the data in the EMPLOYEES table: LAST_NAME DEPARTMENT_ID SALARY Getz 10 3000 Davis 20 1500 Bill 20 2200 Davis 30 5000 ‘Which three subqueries work? (Choose three) ‘A. SELECT * FROM employees where salary > (SELECT MIN(salary) FROM employees GROUP BY department _ id); 8. SELECT * FROM employees WHERE salary = (SELECT AVG(salary) FROM employees GROUP BY department _ id); C. SELECT distinct department_id FROM employees Where salary > ANY (SELECT AVG(salary) FROM employees GROUP BY department _ id); D. SELECT department_id FROM employees WHERE SALARY > ALL (SELECT AVG(salary) FROM employees GROUP BY department _ id); E. SELECT last_name FROM employees Where salary > ANY (SELECT MAX(salary) FROM employees GROUP BY department _ id); F. SELECT department_id FROM employees WHERE salary > ALL (SELECT AVG(salary) FROM employees GROUP BY ANG (SALARY); 2)Examine the description of the EMPLOYEES table: EMP_ID NUMBER(4) NOT NULL \AST_NAME VARCHAR2(30) NOT NULL FIRST_NAME VARCHAR2(30) DEPT_ID NUMBER(2) JOB_CAT VARCHARD2(30) SALARY NUMBER(8,2) Which statement shows the maximum salary paid in each job category’ of each department? : ‘A. SELECT dept_id, job_cat, MAX(salary) FROM employees WHERE salary > MAX (salary); B, SELECT dept_id, job_cat, MAX(salary) FROM employees GROUP BY dept_id,job_cat; C. SELECT dept_id, job_cat, MAX(salary) FROM employees; D. SELECT dept_id, job_cat, MAX(salary) FROM employees GROUP BY «' at_id; E. SELECT dept_id, job_cat, MAX(salary) FROM employees GROUP BY dept _ id job _ cat salary; 3)Examine the structure of the EMPLOYEES and DEPARTMENTS tables: EMPLOYEESColumn name Data type Remarks EMPLOYEE_ID NUMBER NOT NULL, Primary Key EMP_NAME VARCHAR2 (30) JOB_ID VARCHAR2 (20) SALARY NUMBER MGR_ID NUMBER References EMPLOYEE_ID COLUMN DEPARTMENT ID NUMBER Foreign key to DEPARTMENT ID column of the DEPARTMENTS table DEPARTMENTSColumn name Data type Remarks, DEPARTMENT_ID NUMBER NOT NULL, Primary Key DEPARTMENT_NAME VARCHAR2(30) MGR_1D NUMBER References MGR_1D column of the EMPLOYEES table Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Phi:23746666)90009° "8-79. Oracle 11} Material ———[—[—[_—_—_——————————— Evaluate this SQL statement: SELECT employee_id, e.department_id, department_name, salary FROM employees’ e; departments d WHERE e. department_id = I d.department_id; Which SQL statement is equivalent to the above SQL statement? A, SELECT employee_id, department_id, department_name, salary FROM employees WHERE department_id IN (SELECT department_id FROM departments); B. SELECT employee _id, department_id, department_name, salary FROM employees NATURAL JOIN departments; C. SELECT employee_id, d.department_id, department_name, salary FROM employees e JOIN departments d ON e.department _ id = d. department_id; D. SELECT employee_id, department_id, department_name, Salary FROM employees JOIN departments USING (e.department_id, d.department_id); Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 71- Oracle 11g Material Using SET Operators Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90009940, 72 : . Oracle 11g Material —— eee SET Operators «The SET operators combine the results of two or more component queries into one result. Queries containing SET operators are called compound queries. + The number of columns and the data types of the columns being selected must be identical in all the SELECT statements used in the query. The names of the columns need not be identical. + All SET operators have equal precedence. If a SQL statement contains multiple SET operators, the Oracle server evaluates them from left (top) to right (bottom) if no parentheses explicitly specify another order. + Different types of SET operators are UNION Operator o UNION ALL Operator o INTERSECT Operator o MINUS Operator Note: whenever these operators are used select statement must have + Equal no of columns. + Simar datatype eatumns OD “ee “O) The Generic Syntax: cerry query> {UNION| UINON ALL |MINUS| INTERSECT} UNION: * The UNION operator returns all rows selected by either query. Use the UNION operator to return all rows from multiple tables and eliminate any duplicate rows. Guidelines: +” NULL values are not ignored during duplicate checking. + By default, the output is sorted in ascending order of the first column of the SELECT clause, + The IN operator has a higher precedence than the UNION operator. UNION ALL: * Combines the results of Two SELECT statement into one result set including the duplicates. | Guldenines: . oe UNION, duplicate rows are not eliminated and the output is not sorted by lefault. © Use the INTERSECT operator to return all rows common to multiple queries. A B INTERSECT Guidelines; + Reversing the order of the intersected tables does not alter the result. + _ INTERSECT does not ignore NULL values. MINUS: «The MINUS operator returnis rows from the first query that are not present in the second query. Naresh j Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabid, Ph: 23746666, 9000994008 - 73 - Oracie Lig Material MINUS Notes: ‘The Queries are all executed independently but their output is merged. Only final query ends with a Semicolon. Example: Sql>Select Job From Emp Where Deptno=10 UNION Select Job From Emp Where Deptno=20; Sql> Select Deptno,Job From Emp Where Deptno= 10 UNION Select Deptno,Job From Emp Where Deptno=20; Sql> Select Empno,Ename From Emp Where Deptno=10 UNION Select Empno,Ename From Emp Where Deptno=20 Order by 2; Sql>Select Empno,Ename,Job From Emp Where Deptno=(Select Deptno From Dept Where Dname='SALES') UNION Select Empno,Ename,Job From Emp Where Deptno=(Select Deptno From Dept Where Dname='ACCOUNTING'); Sql>Select Deptno,Job From Emp Where Deptno=10 UNION ALL Select Deptno,Job From Emp Where Deptno=20; Sql> Select Job Fram Emp Where Deptno=10 INTERSECT Select Job From Emp Where Deptno=20; ‘Sql>Select Job From Emp Where Deptno=10 MINUS Select Job From Emp Where Deptno=20 Sql>Select Deptno,Job From Emp Where Deptno=10 UNION Select Deptno,Job From Emp Where Deptno=20; ‘Sql> Select Deptno,Job From Emp Where Deptno=10 INTERSECT Select Deptno,Job From Emp Where Deptno=30 Sql>Select Deptno,Job From Emp Where Deptno=10 INTERSECT Select Deptno,Job From Emp Where Deptno=20 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666; 90009940": 74. Oracle 1g Material CONTROLLING USER ACCESS ‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 75 - Oracle 11g Material — And Data Base Security: ‘Used to share the data, data base objects with other users. Users can also cancel the permission, «Use the GRANT and REVOKE statements to grant and revoke object privileges Privileges: Privileges are the right to execute particular SQL statements. The database administrator (DBA) is a high-level user with the ability to grant users access to the database ahd its objects. The users require system privileges to gain access to the database and object privileges to manipulate the content of the objects in the database. Users can also be given the privilege to grant additional privileges to other users or to roles, which are named groups of related privileges. ‘Schemas: ‘A schema is a collection of objects, such as tables, views, and sequences. The schema is owned by a database user and has the same name as that user. Grant: ‘¢ The GRANT command is used to allow another schema access to a privilege. GRANT command can be issued not orily on TABLE OBJECT, but also on \VIEWS,SYNONYMS,SEQUENCES Etc, + The users are GRANTED at time all four(i.e. INSERT,UPDATE,DELETE,SELECT) by using ALL, Sql>GRANT TO [, user| role, PUBLIC...]; Creating Users: Login as User--system Passward--manager Syntax: ‘Sql>Create User Identified By ; Sql>Grant Connect,Resource To ; Illustrate: ‘Sql> Create User UserA Identified By userA; Sql>Grant Connect To user; Login as Scott ‘Sql>Grant ALL_ON Emp TO userA; Sql>Grant INSERT,SELECT, DELETE ON Dept TO userA; Grant columns: Sql>Grant INSERT(Empno,Ename,Sal,Deptno) ON Emp TO userC; Note: ‘+ Only insert and update permission are allowed Sql>Grant Select ON Student TO userA,userB; Sql>Grant Delete ON Supp TO Public; lic * Public Keyword represents all users in database. All users can Delete on Supp table. We cannot give permission at time on more than one data base object Steps To Be Performed: + Connect to the required user using the USER Name and Password. + Execute the required SQL statement using the object hierarchy Login as userA Sql>Select * From Scott.emp; Sql>Insert Into Scott.Dept values(50,’SW’,'Hyd"); Sql>Select * From scott.Student; ‘* At time DML,DRL operation we have to mention owners name. a SE Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90009°1008 - 76. Oracle 11g Material —S——————————————————— REVOKE Command: + Itused to remove the access allowed by GRANT. * REVOKE privileges is assigned not only on TABLE OBJECT, but also on VIEWS, SYNONYMS,SEQUENCES Etc. Sql>REVOKE FROM [, user| role, PUBLIC...]; Sql>Revoke Select ON Student From userA,userB; ‘Sql> REVOKE ALL ON Emp From userA; Types of Privileges: System Privileges: + They allow a user to perform certain action within the Database. Object Privileges: An object privilege allow a user to perform certain actions on Database Objects. Checking the object privileges grante « The schema object that stores that stores the information about the frivileges granted is USER_TAB_PRIVS_MADE. The columns of USER_TAB_PRIVS_MADE, GRANTEE m TABLE_NAME GRANTOR PRIVILEGE GRANTABLE HIERARCHY Sql> Select GRANTEE, TABLE_NAME,GRANTOR, PRIVILEGE From USER_TAB_PRIVS_MADE Where TABLE_NAME='EMP'; ISER COL PRIVS + This table query to view the object privileges granted to the user on specific columns Sql>Select Grantee,Grantor,Column_Name From USER_COL_PRIVS Where Table_Name='EMP'; ‘Sql>Select GRANTEE From All_Tab_Privs Where Grantor='SCOTT' AND Table Name="EMP); Chee! t ileges Re ed: + The schema object that stores that stores the information about the privileges that are received is USER_TAB_PRIVS_RECD. ‘The columns of USER_TAB_PRIVS_RECD. OWNER GRANTEE TABLE_NAME GRANTOR PRIVILEGE GRANTABLE HIERARCHY ‘Sq!> Select OWNER, TABLE_NAME,GRANTOR, PRIVILEGE From USER_TAB_PRIVS_RECD; Roles In Oracle: © Arole is a named group of related privileges that can be granted to the user. ————————————————— Naresh i Technologies, Opp. Satyam Theatre, Ameetpet, Hyderabad, Ph: 23746666, 9000994008 = 77~ Oracle 11g Material ——S Advi les: + Rather than assigning Privileges one at a time directly to s USER, we can CREATE a ROLE, assign PRIVILEGES to that ROLE, and then GRANT that ROLE to Multiple USERS and ROLES. + When you add or delete a privilege from a role, all users and roles assigned that ROLE automatically receive or lose those privileges. + We can assign multiple roles to a single USER or ROLL to another ROLE. + Arole can be assigned with a psssword. ROLE’S Creation: «To creation a role we should have the CREATE ROLE SYSTEM privilege. «The steps in implementing the roles + Role creation * Granting privileges to roles * Granting ROLES TO USERS OR OBJECTS Sql>CREATE ROLE [IDENTIFIED BY ]; Sql> CREATE ROLE Sales_manager Identified By SalesAudit; Note: We can alter the ROLE for password and new password, Sql> Alter ROLE Sales_manager identified by salesAudit; Grant a ROLE to a USER: Sql>Grant Sales_manager TO Scott; Granting Multiple ROLES to another ROLE ‘Sql>Grant ROLE ROLE2,... TO ; Checking ROLES Granted To A user: ‘* The schema object USER_ROLE_PRIVS specifies the ROLES granted to a USER. * The column of USER_ROLE_PRIVS © USERNAME © GRANTED_ROLE o ADMIN_OPTION o DEFAULT_ROLE 0 _OS_GRANTED ‘Sql> Select USERNAME,GRANTED_ROLE From USER_ROLE_PRIVS; System privilege: ited to. a ROLL: «The schema object ROLE_SYS_PRIVS specifies the SYSTEM PRIVILEGES granted to a ROLE, * The columns of ROLE_SYS_PRIVS o ROLE 0 PRIVILEGE o ADMIN_OPTION ° Object privileges Granted to a ROLL: «The schema object ROLE_TAB_PRIVS specifies the SYSTEM PRIVILEGES granted toa ROLE, «The columns of ROLE_TAB_PRIVS ROLE COLUMN_NAME OWNER PRIVILEGE TABLE_NAME GRANTABLE Sql>Select ROLE,PRIVILEGE From ROLE_TAB_PRIVS; ————— 5; Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 237466 Revoking a ROLE; Sql>Revoke Sales_Manager From Scott; Sal> Revoke ALL ON Emp From Sales_Manager; Dropping A ROLE: ‘Sql>Drop ROLE; Sql>DROP ROLE Sales_manager; To change the password of user wt IST BE UNDER your jin. ‘Sql>Alter user krishna identified by wisdom; Sql>Revoke connect,tesource from krishna; Sql>Drop user krishna; Qcp; 1) You need to give the MANAGER role the ability to select from, insert into, and modify existing rows in : the STUDENT_GRADES table. Anyone given this MANAGER role should be able to pass those privileges on to others. Which statement accomplishes this? A. GRANT select, insert, update ON student_grades TO manager B, GRANT select, insert, update ON student_grades TO ROLE manager C. GRANT select, insert, modify ON student_grades TO manager WITH GRANT OPTION; D, GRANT select, insert, update ON student_grades TO. manager WITH GRANT OPTION; E. GRANT select, insert, update ON student_grades TO ROLE manager WITH GRANT OPTION; F.GRANT select, insert, modify ON student_grades TO ROLE manager WITH GRANT OPTION; 2) Which data dictionary table should you query to granted to the user on specific columns? w the object privileges A. USER_TAB_PRIVS_ MADE B, USER_TAB_PRIVS C, USER_COL_PRIVS_MADE D. USER_COL_PRIVS 3) Which two statements accurately describe a role? (Choose two.) A, Arole can be given toa maximum of 1000 users, B, A user can have access to a maximum of 10 roles. C. Arole can have a maximum of 100 privileges contained in it. D. Privileges are given to a role by using the CREATE ROLE statement, E. A role is a named group of related privileges that can be granted to the user. F. A.user can have access to several rales, and several users can be assigned the same role. 4) When should yau create a role? (Choose two) A. To simplify the process of creating new users using the CREATE USER xxx IDENTIFIED by ‘statement. 8. To grant a group of related privileges to a user, C. When the number of people using the database is very high. D. To simplify the process of granting and revoking privileges. £. To simplify profile maintenance for a user who is constantly traveling. 5) Scott issues the SQL statements: CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14), lac VARCHAR2(13)}; GRANT SELECT Naresh i Technologies, Opp. Satyatt Theatre, Ameerpet, Hyderabad, Ph: 23746666. 90m004008 | - 70 Oracle 11g Material ON DEPT TO SUE; If Sue needs to select from Scott's DEPT table, which command should she use? A, SELECT * FROM DEPT; B. SELECT * FROM SCOTT. DEPT; C, SELECT * FROM DBA.SCOTT DEPT; D. SELECT * FROM ALL_USERS WHERE USER_NAME = ‘SCOTT’ AND TABLE NAME = ‘DEPT’; 6) What is true about the WITH GRANT OPTION clause? ‘A, It allows a grantee DBA privileges. B, It is required syntax for object privileges. C. It allows privileges on specified columns of tables. D. It is used to grant an object privilege on a foreign key column. E, It allows the grantee to grant object privileges to other users and roles. 7) The DBA issues this SOL command: CREATE USER scott IDENTIFIED by tiger; What privileges does the user Scott have at this point? A. No privileges. B. Only the SELECT privilege. C. Only the CONNECT privilege. _D. All the privileges of a default user. 8) You are the DBA for an academic database. You need to create a role that allows a group of users to modify existing rows in the STUDENT_GRADES table, Which set of statements accomplishes this? A. CREATE ROLL registrar; GRANT MODIFY ON student_grant TO registrar; GRANT registrar to user 1, user2, user3 B. CREATE NEW ROLE registrar; GRANT ALL ON student_grant TO registrar; GRANT registrar to user 1, user2, user3 C. CREATE ROLL registrar; GRANT UPDATE ON student_grant TO registrar; GRANT ROLE to usert, user2, user3 D. CREATE ROLL registrar; GRANT UPDATE ON student_grant TO registrar; GRANT registrar to user 1, user2, user3; E. CREATE registrar; GRANT CHANGE ON student_grant TO registrar; GRANT registrar; 9) Which describes the default behavior when you create a tabie? A, The table is accessible to all users. B, Tables are created in the public schema. C. Tables are created in your schema. D. Tables are created in the DBA schema, E. You must specify the schema when the table is created. 10) The user Sue issues this SOL statement: GRANT SELECT ON sue. EMP TO alice WITH GRANT OPTION; The user Alice issues this SQL statement: GRANT SELECT ON sue, EMP TO reena WITH GRANT OPTIO ‘The user Reena issues this SQL statement: GRANT SELECT ON sue. EMP TO timber; The user Sue issues this SQL statement: REVOKE select on sue. EMP FROM alice; For which users does the revoke coramand revoke SELECT privilec-- on the ‘SUE.EMP table? ———— eS ‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746665, 900099- 2. 89 Oracle 11g Material ——————————— A. Alice only B. Alice and Reena C. Alice, Reena, and Timber D. Sue, Alice, Reena, and Timber 11) Examine the statement: GRANT select, insert, update ON student_grades TO manager WITH GRANT OPTION; Which two are true? (Choase two.) A. MANAGER must be a role. B, It allows the MANAGER, ta pass the specified privileges on to other users. C. It allows the MANAGER to create tables that refer to the STUDENT_GRADES table. D. It allows the MANAGER to apply all DML statements on the STUDENT_GRADES table: E, It allows the MANAGER the ability to select from, insert into, and update the STUDENT_GRADES table. F, It allows the MANAGER the ability to select from, delete from, and update the STUDENT_ GRADES table. 12). The user Alice wants to grant all users query privileges on her DEPT table. Which Sgt statement accomplishes this? A. GRANT select ON dept TO ALL USER; B. GRANT select ON dept TO ALL; C, GRANT QUERY ON dept TO ALL_USERS D. GRANT select ON dept 10 PUBLIC; 13) Examine these statements: CREATE ROLE registrar GRANT UPDATE ON dtudent_grades TO registrar; GRANT registrar to user, user2, user3; ‘What does this set of SQL statements do? A, The set of statements contains an error and does not work. B. It creates a role called REGISTRAR, adds the MODIFY privilege on the STUDENT_GRADES object to the role, and gives the REGISTRAR role to three users. C. It creates a role called REGISTRAR, adds the UPDATE privilege on. the STUDENT_GRADES object to the role, and gives the REGISTRAR role to three users. D. It creates a role called REGISTRAR, adds the UPDATE privilege on the STUDENT_GRADES object to the role, and creates three users with the role. E, It creates a role called REGISTRAR, adds the UPDATE privilege on three users, and gives the REGISTRAR role to the STUDENT_GRADES object. F. It creates a role called STUDENT_GRADES, adds the UPDATE privilege on three users, es the UPDATE role to the registrar. Technologies, Opp. Satyam Theatre, Ameerpet, : 23746666, 9000994008 : Oracte 11g Material a VIEWS IN ORACLE Naresk ¢ Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90009° ‘708 - 82- «Oracle 11g Material —— After a table is created and populated with data, it may become necessary to prevent all users from accessing all column of a table, for data security reasons. This would mean creating several tables having the appropriate number of columns and assigning specific users to each table, as required, This will answer data security requirements very well but will give rise to a great deal of redundant data being resident in tables, in the database. To reduce redundant data to the minimum possible, Oracle allows the creation of an object called a View. ‘+t can be defined as an stored select statement. + Itwill not hold data or store data by itself. + Itisa logical table based on one or more tables or views. + View can be created based on a table called a BASE TABLE. + View can be created as Object Views or Relational Views. + The Object Views support *LOBs *Object Types *REFS *Nested Tables *Varray + _DML,DESC,SELECT allowed on views. PREREQUISITE: Should have CREATE VIEW System privilege. + To create a subview, we need UNDER ANY VIEW system privilege + The OWNER of the Schema should have SELECT, INSERT,UPDATE or DELETE Rows from all tables or Views on which the VIEW is based. ‘+ The above privileges must be granted the privileges directly, rather than a role. Advantages of Views: * Provides high security while sharing data between users + USER-VIEWS hold the details of views. (date dictionary table). + View can be used to make simple queries _to retrieve the result of complicated quires: * Views provide groups of users access to according to their particular criteria. Syntax: CREATE (OR REPLACE] [FORCE | NOFORCE ] VIEW view name [{(AliasName[,AliasName.....])] As SudQuery [WITH {CHECK OPTION/READ ONLY} CONSTRAINT ConstraintName]; *OR REPLACE: co Re-creates the view if it already exists, FORCE: © Specifies the View Should not be create if the base table does not Exist, which is default. NOFORCE: © Creates the view only if the base tables exist, Which is the default, s_Name: © Specifies names for the expressions selected by the view query. WITH CHECK OPTION: © Specifies that only rows accessible to the view can be INSERTED or UPDATED or DELETED. CONSTRAINT: © Constraint is the name assigned to the WITH CHECK OPTION or READ ONLY constraint. WITH READ ONLY: insures that no DML operations can be performed on this view Naresh j Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 83 Oracle 11g Material TYPES OF VIEWS: Simple Views: + The view which is created without following clauses. ° Join condition: Group by Having clause Set operators Distinct Complex View + The view which is created with any restriction clause is called complex view. * Complex Views can contain Sub Queries . + The SubQuery can contain, Queries © That Retrieve from multiple Base Tables © Group Rows using a GROUP BY or DISTINCT Clause, © Contain a Functional call. ‘Sql>Create VIEW Employees As Select Empno "Emp Id", Ename Name, Sal "Basic Salary", Job Designation From Emp; Selecting Data From A View: Sql> Select Name,Job From Employees; Sql> Select “Emp Id”, name,"Basic Salary"*12 From Employees; Sql>select "Emp Id” ,Name,To_char( "Basic Salary",'99,99,999.99") Monthly, "Basic Salary"32 Annual From Employees Where "Basic Salary">2500; Complex View: Example: Sql>Create VIEW EmpInfo As _Select E.Empno EmployeeNo,£.Ename Name, D.Deptno Departmentld, D.Dname DeparatmentName From Emp E,Dept D Where D.deptno=E,Deptno ORDER BY D.Deptno; Sql>Create VIEW EmpGrades As Select E.Ename Name, E.Sal_ Basic, S.Grade Garde From Emp E,Salgrade S Where E.Sal BETWEEN S,Losal AND S.Hisal ORDER BY S.Grade; Sql>Create VIEW EmpManagers As Select Rownum SerialNo, Initcap(E.Ename)||'Works Under'|| M.Ename "Employee And Managers’ From Emp E,Emp M Where E.Mgr=M.Empno; Sql> Create or Replace VIEW EmpAccount As Select Ename,Deptno,Sal Monthly, Sal*12 Annual From Emp Where Deptno=(Select Deptno From Dept Where Dname="ACCOUNTING') ORDER BY Annual; Sql>Create VIEW PayInfo As Select Empno Ecode,Sal Basic, ‘Sal*0.25 Da, Sal * 0.35 HRA Sal * 0.12 PF, Sal + Sal *0.25 + Sal *0.35-sal *0.12 GROSS From Emp; Sql> Create VIEW Dept_Analysis As SELECT Deptno,count(*) NoEmp,MIN (Sal) Low_PayiMAX(Sal) High_Pay, SUM(Sal) Tot Pay, AVG(Sal) Avg_Pay FROM Emp Group By Deptno; Sql> Create or Replace VIEW CumSum As Select B.Sal,SUM(A.Sal) As Cum_Sal From Emp’A, Emp B Where A.Rowld<=B>Rowld GROUP BY B.Rowld,B.Sal; _Sql>Create or Replace VIEW OrgDesignations As Select Job From Emp Where Deptno=10 UNION Select Job From Emp Where Deptno IN(20,30); ——————————————————— Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 84- Oracle 11g Material VIEW in Data Dictionary: * Once the View has been created, we can query upon the DATA DICTIONARY table called USER_VIEWS to see the Name and definition of the View. « The TEXT of the SELECT statement that constitutes the VIEW is stored in a LONG Column. Retrieving Data from a View: + Retrieves the VIEW definition from the Data Dictionary table USER_VIEWS. + Check the Access privileges for the view. + We can retrieve data from a view as you would from any table. + We can display either the contents of the entire view or just specific rows and columns, ‘Sql> Select GRANTEE From All_Tab_Privs Where Grantor='SCOTT’ AND Table_Name=' OrgDesignations'; Modify A View : ‘+ OR REPLACE Option is used to Modify an existing VIEW with a new definition. + AVIEW can be altered without Drapping, recreating, and regranting object privileges, + The assigned column Aliases in the CREATE VIEW Clause, are listed in the me order as the column in the SubQuery. . ‘© When a VIEW is being created, we can specify the Names of the Columns, that it can project, along with the VIEW’s definition. Sql>CREATE OR REPLACE VIEW EmpV (id_number, name, sal, department_id) AS SELECT empno, ename, sal, deptno FROM emp WHERE -deptno =30; Sql>Select *From EmpV; Sql>Create VIEW DeptSalSummary (DepartmentName, MinimumSalary, MaxSalary, Averag-Salary, SalarySum) As Select D.Danem,Min(E.Sal), Max(E.Sal) ,Avo(E-Sal),Sumn(E.Sal) From Emp E , Dept D Where E.Deptno: .Deptno Group By D.deptno; Sql>Create View VDept20 AS__ Select *Fram Emp Where Deptno=20; Ins The Tot ata of Em) es From Department 20 Usin' Sql>Create Table Dept20.As Select *from VDept20; Sq[> Create Table EmpGrades(Employee, Designation, BasicSalary, Garde )As Select Ename,Job,Sal,Grade From Emp E, Salgrade S Where E.Sal BETWEEN ‘S.Losal AND S.Hisal; ‘DROPING A VIEW: + A VIEW can remove without losing data ,because a view is based on underlying tables in the database. + The DROP VIEW statement is used to remove a View permanently. + Dropping a View has no affect on the tables upon which the View is created. * VIEWS or APPLICATIONS based on deleted Views become invalid. + We need DROP ANY VIEW privileges to remove the VIEWS, Syntax: >DROP VIEW view; Example: ‘Sql >OROP VIEW EmpGrades; INLINE Views: + AN INLINE view is a subquery with an alias (or correlation name) that you can use ‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 85- Cracle 11g Material a within a SQL statement. + Aninline view is not a schema object. + Aninline view is placing a subquery in the FROM clause and giving that subquery an alias. Sqi>Select E.Ename, E.Sal, E.Deptno, I. maxsal FROM Emp E,(SELECT Deptno, max(Sal) maxsal FROM Emp GROUP BY Deptno) 1 WHERE E.Deptno = I.deptno AND E,Sal < I,maxsal; Rules for Performing DI erations On A Vier + DML operations can be performed upon a table through VIEW * Arow can be removed from a VIEW unless it contains, JOIN Condition. GROUP By Clause HAVING Clause SET Operators DISTINCT/UNIQUE Key Word © The Column defined by Expressions * Data can be added through a view, unless it contains any of the above rules and there are NOT NULL Columns. Example: eo000 Sql>Create View Vsalval As Select Empno,Ename,{iai,Job From Emp Where Sal>7000; Sql>Des¢ Vsalval; + Byexecuting this statement empno,ename, sal,job will be displayed because the Vsalval view contains four columns only. Using the WITH CHECK OPTION Clause; To ensure that DML operations on the view stays within the domain of the VIEW by using the WITH CHECK OPTION clause. It is possible to perform referential integrity checks thraugh views. Using VIEWS we can enforce constraints at the database level. ‘The view can be used to protect DATA 1NTEGRITY, but the use is very limited. The WITH CHECK OPTION clause specifies that INSERTs and UPDATEs performed through the VIEW cannot create rows which the VIEW cannot SELECT. ‘+, VIEWS allows integrity constraints and data validation checks to be enforced on data being Inserted ar Updated, M Sql>Create Or Replace VIEW Empvu20 As Select * From Emp Where Deptno=20 WITH CHECK OPTION CONSTRAINT Empvu20; Sql> Create Or Replace VIEW EJobsman As Select *From Emp Where SALESMAN! WITH CHECK OPTION CONSTRAINT EJobsman; @ WITH READ ONLY. » We can ensure that no DML operations occur on your view by creating it with the WITH READ ONLYoption. © Any attempt to perform a DML on any row in the view results in an Oracle server error, Example: Sql>Create Or Replace View empvu10 (employee_number, employee_name, job_title)AS Select employee _id, last_name, job_id from employeesWhere department_id = 10 WITH READ ONLY; w On Views * We can create view on there view, ‘Naresh i Technologies, Opp. Satyam Theatre, Ameerper, Hyderabad, Ph: 23746666, 9000994008, ~86- Oracle 11g Material Sql>Create View V1 As Select *from emp; Sql> Create View v2 As Select Empno,Ename,Job,Sal*0.22 Bonus From v1; Sql> Drop view Emp; Note: + V1,V2 Views will become invalid. + View will get the component and not to maintain, + When we create an view with out a base table. {message:-view created with compilation’ errors.) + As soon as create the base table Invalid become as Valid View. vas Ss" INT: + In practically Oracle does not enforce View constraint, but operations on VIEW are subject to the INTEGRITY CONSTRAINT defined on the underlying base tables. + CONSTRAINTS on VIEWS can be enforces through CONSTRAINTS on base table. estricti in View Constr: + The VIEW Constraints are subset of TABLE CONSTRAINTS. + Only UNIQUE,PRIMARY KEY And FOREIGN KEY CONSTRAINTS can be specified on VIEWS, + The CHECK CONSTRAINT is imposed using WITH CHECK OPTION. As VIEW CONSTRAINTS are not enforced directly, we cannot specify INITIALLY DEFERRED or DEFREEABLE. + _ VIEW CONSTRAINTS are supported only in DISABLE NOVALIDATE mode. INITIALLY DEFERRED: + It indicated that Oracle should check this CONSTARINT at the end of + SUBSEQUENT transactions. Note: * INITIALLY DEFERRED is not valid if the CONSTRAINT is declared to be NOT DEFERRED. » NOT DEFREEABLE CONSTRAINT is AUTOMATICALLY INITIALLY IMMEDIATE and can never be INITIALLY DEFERRED. VALIDATE/NOVALIDATE: «The Behavior of VALIDATE and NOVALIDATE always depends on whether the CONSTRAINT is ENABLED/ DISABLED ,cither EXPLICTLY or by DEFAULT. DE BLE Clause: * The DEFERRABLE and NOT DEFERRABLE parameters indicate whether oF not, in the subsequent transaction, constraint checking can be deferred until the end of the transaction using the SET CONSTRAINT statement. + The default is NOT DEFERRABLE. NOT DEFERRABLE: + The checking of a NOT DEFERRABLE CONSTRAINT can Never be DEFERRED to the end of the transaction. DEFERRABLE: + TRindicate that in subsequent transactions we can use the SET CONSTRAINT(s) Clause to defer checking the CONSTRAINT until after the transaction is committed. «The setting is effect lets the user to disable the CONSTRAINT temporarily while making changes to the database that might violate the CONSTRAINT until all the changes are complete. + To alter the CONSTRAINT Deferability, we must DROP the CONSTRAINT and recreate it. Initially Immediate: + It indicated that Oracle should check this CONSTRAINT at the end of each SQL statement. —————————— ee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 87 Oracle 11g Materiat + VIEW CONSTRAINT cannot be defined on attribute of an object column. + Constraint State specifies how and when ORACLE should enforce the CONSTRAINT. . + The constraint state clauses can be specified in any order, but each state can be Specified only once. Sql>Create View EmpSalary (Empl, Ename,Email UNIQUE RELY DISABLE NOVALIDATE, Constraint 10_PK PRIMARY KEY(Empld) RELY disable NOVALIDATE) ‘As Select Empno,Ename,Email From Emp; Examp! Sql>Create table FZ_SRV_ITEMS(Status number Constraint chk_sta Check (Status in(0,1,2,3,4)) ; Note: In the above case the default constraint is NOT DEFERRABLE INTITALLY IMMEDIATE Constraint CHECK, Sql>Create table FZ_SRV_ITEMS( Status number Constraint chk_sta check (Status in(0,1,2,3,4)) DEFERRABLE ); Sql>Alter Table FZ_SRV_ITEMS Modify Constraint chk_sta INITIALLY DEFERRED SNAPSHOT: SNAPSHOT is Data Base object. + Itisa static picture of data.. + SNAPSHOT has o Structure © Data ‘+ No DML possible on snapshot. + Only select is possible on it. + Performance is fast. Syntay CREATE SANPSHOT AS. SELECT *FORM .@; Not When create SANPSHOT On oracle 8i we get message is ‘Materialized view created *. 5 * When delete the date in table, but the SNAPSHOT data not will be delete Drawback: * It static, we do any changes on base table there is no effected in SANPSHOT. MATERIALIZED VIEWS: «Its introduced in Oracle (8i) . + Itholds data. + No DML allowed, + Equivalent to snap-shop(DBA object) + Materialized Views are used in DATA WAREHOUSES. + They are used to increase the speed of queries on Very large databases. uery Rew! + Materialized Views improve query performance by PRECALCUTING Expensive JOIN and AGGREGATION operations on the DATABASE PRIOR to Execution time and stores the resuits in the DATABASE. * The Query OPTIMIZER can make use of MATERIALIZED VIEWS by automatically recognizing when an Existing MATERIALIZED VIEW can and should be used to satisfy a Request. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 88- Oracte 11g Material —— eee + After above process is completed then QUERY OPTIMIZER transparently rewrites the request to use the MATERIALIZED VIEW. + QUERIES are then directed to the MATERIALIZED VIEWS and not to the underling DETAIL TABLES or VIEWS, + REWRITING QUERIES to use MATERIALIZED VIEWS rather than detail relations, results in a significant performance gain. PREREQUISITES FOR MATERIALIZED VI IVILEGES: + Needs create materialized view privilege. «Grant Query rewrite to scott; + Alter Session Set QUERY_REWRITE_ENABLED=TRUE; Set the Initsid.ORA File: + OPTIMIZER_MODE=CHOOSE JOB_QUEUE_INTERVAL=3600 JOB_QUEUE_PROCESSES=1 QUERY_REWRITE_ENABLED=TRUE QUERY_REWRITE_INTEGRITY=ENFORCED Syntax: ‘Sql> Create MATERIALIZED VIEW [ENABLED QUERY REWRITE] [Refresh On Commit] As
; Sql> Select Decode(Deptno,10,'ACCOUNTING’,20,'RESEARCH’,30, SALES’, 40,/0PERATIONS', OTHER’) Departments Fram Emp; the table. Grouping()With DECODE(): + The DECODE() function can be used to convert 1 and 0 returhed through Grouping() into a meaningful output. Sql> Select Decode(Grouping(Deptno), 1,'All Departments', Deptro) Departments, Sum(Sal) From Emp Group By ROLLUP(Deptno);, Sql>Select Decode(Grouping(Job), 1,’All Designations’, Job)Designations, Sum(Sal) From Emp Group By ROLLUP(Job); Decode() and Groupina() to converting multiple column values: Sql> Select Decode(Grouping(Deptno), 1,’All Departments’, Deptno)Departments, Decode(Grouping(Job), 1,'All Designations’, Job)Designations, Sum(Sal) From Emp Group By ROLLUP(Deptno,Job); Groupina() With Decode() and CUBE: Sql> Select Decode(Grouping(Deptno), 1,'All Departments’, Deptno)Departments, Decode(Grouping(Job), 1,'All Designations’, Job)Designations, Sum(Sal) From Emp Group By Cube(Deptno,Job); Appling Grouping SETS Clause: + ‘The GROUPING SETS clause is used to get the SUBTOTAL rows. Sql> Select Deptno,Job,Sum(Sal) From Emp Group By Grouping Sets(Deptno,Job); Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 107- Oracle 11g Materi Working With CASE Expressions: * The CASE expression can be used to perform IF-THEN-ELSE logic in SQL. * It can be used even for Executing conditions on range based comparison. ‘Case expressions are of two types © SIMPLE CASE Expressions o SEARCHED CASE Expressions. Sit iE ressi Tt accepts more than one column expression’. These Expression are used to determine the returned value. They work with equatity comparison only, almost all similar to DECODE. It has a select which associates to the compared value either fram the column or constraint, * The value in the select is used for comparison with the expressions used in the WHEN clause. ‘Synt Sql>CASE Search_expr WHEN Expr THEN Result 1 WHEN Expr2 THEN Result 2 ELSE Default_Result END; Example: Sql>Select Empno,Ename,Job,Sal, Case Job When 'MANAGER' THEN ‘Man' When ‘CLERK’ THEN ‘Clk’ When 'SALESMAN' THEN 'Sman’ Else ‘Other Job’ End Gjob From Emp; Sql> Select Empno,Ename,Deptno, Case Deptno When 10 THEN ‘ACCOUNTS’ When 20 THEN ‘RESEARCH’ When 30 THEN 'SALES' When 40 THEN ‘OPERATIONS’ Else 'Not Found" End. From Emp; eat CASE Expres: + The statement uses conditions to determine the returned value, It helps in writing multiple conditions for evaluation Helps in range analysis of values also. ‘Syntax: Sql>CASE WHEN Condition 1 THEN Result 1 WHEN Condition 2 THEN Result 2 WHEN Condition n THEN Result 1, ELSE Default_Result END; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 900099400 - 108 - Oracle 11g Material ————————————— i Example Sql> Sclect empno,ename,job,sal, Case when job="MANAGER’ then ‘Mag! when sal=3000 then ‘Mpay' when jol SALESMAN’ then 'Sman'~ Else ‘Not Specified’ end Gjob From emp Sql> Select Empno,Ename,Deptno, Case When Deptno=10 THEN 'ACCOUNTS' When Deptno=20 THEN ‘RESEARCH! When Deptno=30 THEN 'SALES' When Deptno=40. THEN ‘OPERATIONS’ Else ‘Not Specified ' End From Emp; Sql> Select Ename,Sal, Case When Sal>= 800 AND Sal< When Sal>=2001 AND Sal Else 'High pay ' End From Emp; GROUPING ID() Function: + The function is used to Filter Rows using A HAVING Clause to exclude rows that do not contain a subtotal OR Grand Total. + The function accepts one or more columns and returns the decimal eq} the GROUPING BIT VECTOR. * The GROUPING BIT VECTOR is computed by combining the results of a call to the GROUPING() function for each column in order. Computing the GROUPING BIT VECTOR: * GROUPING() Function returns 1 when the column val returns 0,Based on this concept. GROUPING_ID() Returns O,When Deptno and Job are is NOT NULL, GROUPING_ID() Returns 1,If Deptno is NOT NULL and Job is NULL. GROUPING_ID() Returns 2,If Deptno is NULL and Job is NOT NULL. GROUPING_ID() Returns 3,1f Deptna is NULL and Job is NULL. Sq|> Select Deptno,Job,Grouping(deptno) GDPT,Grouping(Job) GJOB, GROUPING_ID(Deptno,Job) GRPID, SUM(Sal) From Emp Group By ROLLUP(Deptna,Job); Sql> Select Deptno,Job, Grouping (deptno) GDPT,Grouping(Job) GJOB, GROUPING_ID(Deptno,Job) GRPID, SUM(Sal) From Emp Group By CUBE(Deptno,Job); 000 THEN ‘Lowest Pay’ 000 THEN ‘Moderate Pay" lent of GROUPING_ID() and HAVING Clause: Sql> Select Deptno,Job, GROUPING_ID(Deptno,Job) GRPID, SUM(Sal) From Emp Group By CUBE(Deptno,Job) Having GROUPING_ID(Deptno,Job)>0; Representing Column multiple Times in a P_BY Clause: ‘Sql>Select Deptno,Job,SUM(Sal) From Emp Group By Deptno,ROLLUP(Deptno,Job); Sql> Select Deptno,Job,SUM(Sal) From Emp Group By Deptno,CUBE(Deptno,Job); Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 | - 109 - Oracle 1g Material Hi P_ID Function: * The GROUP_ID Function is used to remove the duplicate rows returned by GROUP BY Clause. + The GROUP_ID() Does not accept any parameters, IFN’ duplication exits for a particular Grouping,GROUP_ID() returns numbers in the range 0 To N-1. Sql> Select Deptno,Job,GROUP_ID(),SUM(Sal) From Emp Group By Deptno, CUBE(Deptno,Job) having group_id()=0; Sql>Select Deptno,Job,GROUP_1D(),SUM(Sal) From Emp Group By Deptno, CUBE(Deptno,Job) Having GROUP_ID=0 Sql> Select Deptno,Job,GROUP_ID(),SUM(Sal) From Emp Group By Deptno,CUBE(Deptno,Job) Having GROUP_ID()=0; nhancing the Power of using Analytic Euncti ‘+ Analytic function are designed to address problems such as Calculate a running total. Find percentages with in a Group. Top “N” Queries ‘Compute “Moving Averages". ‘+ Analytic functions add greater performance to the standard query processing. How analytic Functions work? * Analytic functions compute an aggregate value based on a group of rows. + The group of rows are called as “WINDOW” and is defined by the Analytic clause. + The Group of rows are called as "WINDOW" and is defined by the Analytic Clause. + The window define the range of rows used to perform the calculation for the current row. + Window sizes can be based upon either a physical number of rows or a logical * Analytical function can appear only in the SELECT list OR ORDER by clause. Synta Analytic Function(Arg1,Arg2,Arg3) Over(Partition Clause ORDER BY Clause Windowing Clause) * Analytic function takes 0 or 3 arguments. + The PARTITION by clause logical breaks a Single result set into 'N’ ¢ vups. ‘+ The Analytic function are applied for each group independently ,ané hey are. reset for each group. «The ORDER BY Clause specifies how data is stored within each GROUP(partition). * The Output of Analytical function is affected by ORDER BY clause. + The windowing clause gives us a way to define a Sliding (OR) Analy'‘cal function will operate, within a Group. Analytic Function Categories: Ranking Function: «They enable us to calculate Ranks, percentiles and N-Tiles. Inverse percentile Functions Enable to calucate the value corresponding to a per Window Functions: * Enable to calculate Cumulative and moving aggregates. Normal Ranking: Sq|>Select Ename,Deptno,Sal, __ RANK() OVER(ORDER BY Sal)EmpRe From Emp Group By Oeptna,Ename,Sal ORDER BY Empri Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90009948 - 110- Oracle 11g Material Sql> Select Ename,Deptno,Sal, DENSE_RANK() OVER(ORDER BY Sal Desc)EmpRank From Emp Group By Deptno,Ename,Sal ORDER BY Emprank; Ranking With Partion: Sal> Select Ename,Deptno,Sal, RANK() OVER(PARTITION BY Deptno ORDER BY Sal Desc)"TOP Sal" From Emp ORDER BY Deptno,Sal DESC; Ranking with Partition and Filters: Sql>Select * From(Select Ename,Deptno,Sal,RANK() “OVER(PARTITION BY. Deptno ORDER BY Sal Desc) TOPSal From Emp) WHERE TOPSAL<=: ORDER BY Deptno,Sal DESC; Appling Windows: + The Windowing clause give a way to definé a SLIDING or ANCHORED WINDOW of data, upon which the ANALYTIC FUNCTION will operate, with A GROUP. + The default Window is an ANCHORED WINDOW that simple starts at the FIRST ROW of a GROUP and continues to the CURRENT ROW. Window can be based on RANGES of data values, Existences of an ORDER BY in an analytic function will add a DEFAULT WINDOW clause of ‘RANGE UNBOUNDED PRECEDING’, which gets all rows in the partition that came befare the ORDER BY clause. Row WINDOW: Sql>Select Deptno,Ename,Sal, SUM(SAL) OVER(PARTITION BY Deptno ORDER BY Ename ROWS 1 PRECEDING) "Sliding Total" From Emp ‘ORDER BY Deptno,Ename; Sql>Select Deptno,Ename,Sal, SUM(SAL) OVER(PARTITION BY Deptno ORDER BY Ename ROWS 2 PRECEDING) "Sliding Total" From Emp ORDER BY Deptno,Ename; Range Window: + RANGE WINDWO collect ROWS together based on a WHERE clause. + The RANGE UNITS can either be numeric comparisons OR date comparisons. + Range units are not valid if data type is other than number or dates. Sql> Select Ename, Sal,Count(*) OVER(ORDER BY Sal ASC RANGE 5000 PRECEDING) Salent From Emp; Sql> Select Ename, Sal,sum(Sal) OVER(ORDER BY Sal ASC RANGE 5000 PRECEDING) SalTot From Emp; NULLS FIRST NULLS LAST Sql>Select Empno,Sum(Sal), RANK() OVER(ORDER BY SUM(Sal) DESC NULLS LAST)Rank,DENSE_RANK() OVER(ORDER BY SUM(Sal) DESC NULLS LAST)Dense_Rank From Emp Group By Empno Order by Empno Sql>Select Empno,comm,RANK() OVER(ORDER BY comm DESC NULLS LAST)Rank, DENSE_RANK() OVER(ORDER BY comm DESC NULLS LAST)Dense_Rank From Emp Group By Empno,comm. Sql>Select Empno,comm,RANK() OVER(ORDER BY comm DESC NULLS FIRST)Rank, DENSE_RANK() OVER(ORDER BY comm DESC NULLS FIRST)Dense_Rank From Emp Group By Empno,comm.; The default is NULLS FIRST. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 111 - Oracle 11g Material LOCK TABLE STATEMENT Naresh i Technologies, Opp. Satyam Theatre, Amecrpet, Hyderabad, Ph: 23746666, 9000994008 - 112 Oracle 11g Material Locks: Locks are the mechanisms used to prevent destructive interaction between users accessing the Same resources simultaneously, + Aresource can either table or a specific row in a table. * Thus locks provide a high degree of data concurrency. joncurrent user:- * Multiple users using same resource at same time. + Locking system of oracle prevent concurrent users to do destructive transactions. + Locks can be acquired at two different levels. Row level lock (for specific rows )> © Table level lock (for entire table) Row level locks: + Inthe row lock, a row Is locked exclusively so that others users cannot modify ‘the row until the transaction holding the lock is committed of rollback, Example: Sql>select *from emp where empno=7788 for update of hiredate; Sql>Update emp set hiredate='12-Jan-06" Where empno=7788; Table Level lock: + A table level lock will protect table data thereby guaranteeing data integrity when data is being accessed concurrently by multiple users. A table 'ock can be in several modes, Share lock Share update lock Exclusive lock Syntax: * Lock table in ; ‘Share lock: * Asshare lock locks the table allowing other users to only query but not insert, update or delete rows in a table. xample: Sql>lock table emp in share mode; Share u| loci * It locks rows that are to be updated in a table. + It permits other users to concurrently query,insert, update or even lock other rows in the same table, + It prevents the other users from updating the row that has been locked. Example: ‘Sql>Lock table emp in share update mode; (scott) Scott: ‘Sql>Update emp set sal=3000 Where deptno=10; (As scott cannat update 10 but can be update 20,30.) Exclusive Lock:- * When issued by one user, it allows the other user to only Query but not insert, delete or update rows in a table.-> + itis almost similar to @ share lock but only one user can place an exclusive lock ona table at a time, where as many users can place a share lock on the same table at the same time. Example: Sql>lock table emp in exclusive mode; ‘Note: + Locks can be released by issuing either? rollback or commit; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 ~ 113 - Oracle 11g Material ——————— + Addeadlock occurs when two users have a lock, each On a separate object , and, they want to acquire a lock on the each object. When this happens, the first user has to wait for the second user to release the lock, but the second user will not release it until the lock on the first user’s object Is freed ‘+ At this point ,both the users are at an impasse and cannot proceed with their business. In such a case, Oracle detects the deadlock automatically and solves the problem by aborting one of the two transactions, Roles In Oracle: + Arole is a named group of related privileges that can be granted to the user. Advantages: Rather than assigning Privileges one at a time directly to s USER, we can CREATE 2 ROLE, assign PRIVILEGES to that ROLE, and then GRANT that ROLE Working With SYNONYMS: * Itis Data Base Object , which acts as an alternate name for an existing object, Next to View. + The CREATE Synonym privileges is necessary to execute the creation of a Synonym. + Simplify access to objects by creating a synonym(Snother name for an object). With synonyms, you can: © Base referring to a table owned by anoti.er user. Shorten lengthy abject names. * DML, Description, Select allowed on SYNONYM provides security. + USER_SYNONYMS tables holds details of synonyms. ‘Synonyms are two types: Private synonym: * Created by user. * Used by specific users which have permission, ‘Syntax: CREATE [PUBLIC] SYNONYM FOR [user name]. [@database link]; Example: Sql>CREATE SYNONYM EmpDet FOR Emp; Sql>CREATE SYNONYM emp_syn FOR Scott.Emp; (if you are in different user.) Sql> Insert into EmpDet(Empno,Ename,Job,Deptno) Values(1001,’KRISHNA’ ,"MANAGER',20); Sql> Select *from EmpDet; Sql> Delete From EmpDet Where Deptno=10; Sql>Grant all on EmpDet to scott; ‘Sql>Select *From Scott.EmpDet; Sql> Select Synonym_Name From User_Synonyms Where Table_Nam EMP’; Public synonym: + Created by Data Base Administrators, + We should have CREATE PUBLIC SYNONYM privilege, and it can accessed by all USERS. ee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 900099405 114 Oracle 11g Materia Sql» Create PUBLIC SYNONYM EmpDet FOR SCOTT.Emp; Sql>Select Synorym_Name From All_Synonyms Where Table_Name="TEMP'; + Itis created for : ‘Table **View **Procedure **Function **Package 4 It is used for hiding the information as © User Name © Object Name © Database Link For security purpose. + Itcan be also use to provide short name to object. + It takes minimum space only for name. Remove: * If drop the table the SYNONYM of that table become as Inv: Sql>Drop SYNONYM EmpDet; ocr: 1)The database administrator of your company created a public synonym called HR for the HUMAN_RESOURCES table of the . GENERAL schema, because many users frequently use this table. As a user of the database. you created a table called HR in your schema. What happens when you execute this query? SELECT * FROM HR; ‘A. You obtain the results retrieved from the public synonym HR created by the database administrator. 8, You obtain the results retrieved from the HR table that belongs to your schema. C. You get an error message because you cannot retrieve from a table that has the same name as a public synonym. D. You obtain the results retrieved from both the public synonym HR and the HR table that belongs to your schema, as a Cartesian product. E, You obtain the results retrieved from both the public synonym HR and the HR table that belongs to your schema, as a FULL JOIN. 2.)Mary has a view called EMP_DEPT_LOC_VU that was created based on the EMPLOYEES, DEPARTMENTS, and LOCATIONS tables, She granted SELECT privilege-to Scott on this view. Which option enables Scott to eliminate the need to qualify the view with the name MARY EMP_DEP_LOC_VU each time the view is referenced? A. Scott can create a synonym for the EMP_DEPT_LOC_VU bus using the command CREATE PRIVATE SYNONYM EDL_VU FOR mary.EMP DEPT_LOC_VU; then he can prefix the columns with this synonymn. B. Scott can create a synonym far the EMP_DEPT_LOC_VU by using the command: Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 115~ Oracle 11g Material ee CREATE SYNONYM EDL_VU FOR mary.EMP_DEPT_LOC_VU; then he can prefix the columns with this synonym. C. Scott can create a synonym for the EMP_DEPT_LOC_VU by using the command: CREATE LOCAL SYNONYM EDL_VU FOR mary.EMP DEPT_LOC_VU; then he can prefix the columns with this synonym. D. Scott can create a synonym for the EMP_DEPT_LOC_VU by using the ‘command: CREATE SYNONYM EDL_VU ‘ON mary(EMP_DEPT_LOC_VU); then he can prefix the columns with this synonym, E, Scott cannot create a synonym because synonyms can be created only for tables. F. Scott cannot create any synonym for Mary's view. Muty should create a private synonym for the view and grant SELECT privilege on thet synonym to Scott. 3) Evaluate the’SQL statement DROP TABLE DEPT: Which four statements are true of the SQL statement? (Choose four) A. You cannot roll back this statement. B. All pending transactions are committed, C. All views based on the DEPT table are deleted, __D. All indexes based on the DEPT table are dropped. E. All data in the table is deleted, and the table structure is also deleted. F. All data in the table is deleted, but the structure of the table is retained. G. All synonyms based on the DEPT table are deleted. ————— eee ee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000". = 116- Oracle 11g Material —————————————————— Data Manipulation Language ———— Naresh { Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 117 - : Oracle 11g Material ——— Data manipulation language (DML) is a core part of SQL. When you want to add, update, or delete data in the database, you execute a DML statement. A collection of DML statements that form a logical unit of work is called a transaction. Update «Update is used to modify the existing vales in Table or in the base table of View Prerequisites ‘+ The table must be in the Own schema, + UPDATE object privilege should be available, ‘Syntax ‘SqI>UPDATE table SET column = value [, column = value, ...][WHERE condition}; ‘Sql> UPDATE Emp SET Deptno = 40 WHERE Empno = 7788; Sql> UPDATE Emp SET Sal=4000,Comm =NULL WHERE Job = ‘SALESMAN'; Updating Two Colymns with a Sub query: Sql> UPDATE emp SET job= (SELECT job FROM emp WHERE empno=7788), sal= (SELECT sal FROM emp WHERE empno=7499); WHERE employee id = 7369; Sql> Update Emp Set (Job,Deptno)=(Select Job,Deptno From Dept Where Empno=7499) Where Empno=7698; Sql> Update Emp Set Deptno=(Select Deptno From Emp Where Empno=7788) Where Job=(Selec’ job From Emp Where Empno=7788); Updating Rows Based on Another Table: ‘+ Use Sub queries in UPDATE statements to update rows in a table based on values from another table. Sql>Update Emp Set Deptno=(Select Deptno From Dept Where Dname='ACCOUNTING') Where Deptno=( Select Deptno From Dept Where Driame=’SALES"); Appl fault-Values: «It is used to UPADETE a value in a column with DEFAULT value set in the constraints, Sql>Update Emp Set Sal=DEFAULT Where Ename='FORD’, Sql> Update Emp Set Hiredate=DEFAULT Where Empno=7788; Returning Clause: ‘© The returning clause is introduced from 8.0 + It is used to return a valve from a aggregate function. «The clause can be specified for table and materialized views and for views with a single base table. Restrictions: + Each express must be a simple expression or a single set aggregate fun:.ion, «It cannot be specified for multiple table insert. + It cannot be specified upon a view upon which a instead of trigger is det ved. Sql>VAR sumsal number Sqi>Update Emp Set S: ssumsal; ‘Sal*1.2 Where Deptno=10 Returning SUM(Sal) 1 TO Sql> VAR bsal Number Sql> VAR bname Varchar2(20) Sql> update emp set sal=sal+sal*.25 where empno=7788 returning enam: ,sal into soname, :bsal; Sql> print :bname :bsal Naresh i Technologies, Opp. Satyarn Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994 ° - 118 - Grace 1g Maferial MERGE Statement: The MERGE statement is used to SELECT rows from one or more Sources for UPDATE or INSERT into one or more tables. * The MERGE statement is convenient to combine multiple operations and avoid multiple INSERT,UPDATE, DELETE. MERGE is a deterministic statement, using which the same row of the target table can be transacted multiple times in the same MERGE statement. Illustrations: Gs Sql>Create Tabie Ebonus ( Empno NUMBER, Bonus NUMBER’ DEFAULT 100 ); Sql> Insert into Ebonus (Empno) (Select E.Empno From Emp & Where Job='SALESMAN’); Sql> MERGE into Ebonus B Using (Select Empno,Sal,Deptno From Emp Where Deptno = 30) S On (B.Empno = S.Empno) When MATCHED THEN UPDATE Set 8. Bonus = B.Bonus + S, Sal *0.1 DELETE Where (S. Sal > 4000) WHEN NOT MATCHED THEN INSERT (B. Empno , B Bonus) VALUS ( S . Empno, S. Sal * 0.1) Where ( S. Sal < = 4000); 7 ‘Sql>MERGE INTO TEST T USING EMP E ON(E,EMPNO=T.EMPNO) WHEN Matched THEN UPDATE SET T.JOB=E.JOB, T.SAL=E,SAL, T.DEPTNO=! T.COMM=E.COMM WHEN NOT Matched THEN INSERT VALUES(E.EMPNO,E.ENAME,E.JOB, E.MGR,E.HIREDATE,E.SAL,E.COMM,E.DEPTNO) Sql > Create Table Examtimetable (Examname varechar2(30), Examtime varechar2(12), CONSTRAINT ExamnamePK PRIMARY KEY(Examname); Sql> Insert Into Examtimetable VALUES (‘PHYSICAL SCINCE’,'9:00 AM’); .DEPTNO, ‘Sql> MERGE Into Examtimetable E1 USING Examtimetable E2 ON (£2. Examname = E1, Examname AND E1. Examname = ‘PHYSICAL SCIENCES’) WHEN MATCHED THEN UPDATE Set E1.Examtime = ‘10:30 AM’ WHEN NOT MATCHED THEN Insert (E1. Examname , £2. Examntime) VALUES (* PHYSICAL SCIENCES’, '10:30 AM’); Sql> Merge into Examtime table E2 Using Examtimetable E2 ON (E2. Examname = E1.Examname AND E1.Examname = ‘CHEMICAL SCIENCES’) WHEN MATCHED THEN UPDATE SET E1.Examtime = ‘12:30 PM’ WHEN NOT MATCHED THEN Insert (Et, Examname , £2. Examntime) ‘VALUES (' CHEMICAL SCIENCES’, '12:30 PM’); DELETE Statement: + Itused to remove existing rows from a table. * An Un partitioned or partitioned table. + The Un partitioned or partitioned base table of view. + The Un partitioned or partitioned constraint table of writable Materialized view. ———————————— Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 119 - Oracta 11g Material —————————— Prere lisites: © To DELETE rows from a table, the table must be in the USERS SCHEMA. + DELETE ANY TABLE system privilege allows to DELETE rows from any TABLE OR PARTITION TABLE OR form the base table of any VIEW. ‘Sql>DELETE [FROM]
[WHERE condition]; Usir teturning Clauss ‘Sql>DELETE From Emp Where Empno Ini(7788,7902); Sql>Delete From Emp Where Deptno=(Select Deptno From Dept Where Dname=’ACCOUNTING’); Sql> DELETE FROM EMP P_ WHERE ROWID<(SELECT MAX(ROWID) ; ROM EMP S WHERE P.ENAME=S.ENAME); SqI>VAR BVSAL number i ‘Sql>Delete From Emp Where Job=’SALESMAN' AND Hiredateinsert all into di values(deptno,dname,loc) into d2 values(deptno,dname,loc) into d3 values(deptno,dname,|oc) select * from dept; Sql>Insert ALL. Into di(deptno) Values(70) Into d2(deptno) Values(80) Select deptno From Dept Where Deptno=40 Conditional Insert: Sql>insert all when deptno<=40 then Into di values(deptno,dname,loc) when deptno >40 and deptno<=80 then into d2 values(deptno,dnar=;loc) else into d3(deptno,loc) values(deptno,loc) select *from dept Sql>Select * From di; Sql>Select * From d2; Sql>Select * From d3; Sql Mul oce 1)Examine the data in the EMPLOYEES and EMP_HIST tables: EMPLOYEES EMPLOYEE ID NAME DEPTID MGR_ID JOB_ID = SALARY 101 Smith 20 120 SA_REP. 4000 102 Martin 10 105 CLERK 2500 103 Chris 20 120 IT_ADMIN 4200 104 Jorn 30 108 HR_CLERK — 2500 105 Diana 30 108 TTADMIN — 5000 106 Smith 40 110 AD.ASST 3000 108 Jennifer * 30 110 HR_DIR 6500 110 Bob 40 EX_DIR 8000 120 Ravi 20 110 SA_DIR 6500 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 900099400° 120 Oracle 11g Material ——S—————————— ——— EMP HIST EMPLOYEE_ID NAME JoB_ID SALARY 101 Smith SA_CLERK 2000 103 Chris IT_CLERK 2200 104 John HR_CLERK 2000 106 ‘Smith AD_ASST 3000 108 Jennifer HR_MGR, 4500 The EMP_HIST table is updated at the end of every year. The employee ID, name, job ID, and salary of each existing employee are modified with the latest data. New employee details are added to the table. Which statement accomplishes this task? A. UPDATE emp_hist SET employee_id, name, job_id, salary = (SELECT employee_id, name, job_id, salary FROM employees) WHERE employee_id IN (SELECT employee_id FROM employees); B. MERGE INTO emp_hist eh USING employees e ON (eh.employee_id = e.employee_id)WHEN MATCHED THEN UPDATE SET eh.name = e.name, eh. job_i e.job_id, eh.salary = e.salary WHEN NOT MATCHED THEN INSERT. VALUES (e.employee id, e.name, e,job id, e.salary); C. MERGE INTO emp_hist eh USING employees e ON(eh.employee_id = e.employee_id) WHEN MATCHED THEN UPDATE emp hist SET eh.name = e.name, eh,job_id = e.job_id, eh.salary = e.salary WHEN NOT MATCHED THEN INSERT INTO emp_hist VALUES (e,employees_id, e.name, e,job_id, e.salary); D. MERGE INTO emp_hist eh USING employees e WHEN MATCHED THEN UPDATE ‘emp_hist SET eh.name = e.name, eh.job_id = e.job_id, eh.salary = e.salary WHEN NOT MATCHED THEN INSERT INTO emp_hist VALUES (e,employees_id, e.name, e.job_id, e.salary); 2) Examine the structure if the EMPLOYEES and NEW EMPLOYEES tables: EMPLOYEES EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25) HIRE_DATE DATE NEW EMPLOYEES EMPLOYEE_ID NUMBER Primary Key ‘A, SELECT AVERAGE(gpa) FROM student_grades WHERE semester _ end > '01- JAN-2000' and semester end <31-DEC-2000'; B, SELECT COUNT(gpa) FROM student grades WHERE semester _ end > ‘01-JAN- 2000' and semester end <31-DEC-2000', C. SELECT MIN (gpa) FROM student grades WHERE semester _ end >.‘01- JAN-2000' and semester end <31-DEC-2000'; D. SELECT AVG(gpa) FROM student_grades WHERE semester _ end BETWEEN 01-JAN-2000' and '31-DEC-2000'; E, SELECT SUM(gpa) FROM student grades WHERE semester _ end > '01-JAN- 2000' and semester end <31-DEC-2000'; , SELECT MEDIAN(gpa) FROM student_grades WHERE semester _ end > ‘O1- JAN-2000' and Semester end <31-DEC-2000'; 3)You added a PHONE NUMBER column of NUMBER data type to an existing EMPLOYEES table. The EMPLOYEES table already contains records of 100 employees. Now, you want to enter the phone faresk i Technologies, Opp. Satyam Theatre, Ameerper, Hyderab Oracle 11g Materi —————————————— numbers of each of the 100 employees into the table. Some of the employees may net have a phone number available. Which data manipulation operation do you perform? A. MERGE B. INSERT C. UPDATE D. ADD E, ENTER F. You cannot enter the phone mimbers for the existing employee records. 4) Which are DML statements? (Choose all that apply) ‘A. COMMIT. B. MERGE, C. UPDATE... D, DELETE... CREATE F. DROP... 5) Examine the structure of the EMPLOYEES and NEW_EMPLOYEES tables: EMPLOYEES EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25) HIRE_DATE DATE NEW_EMPLOYEES EMPLOYEE_ID NUMBER Primary Key NAME VARCHAR2(60) Which MERGE statement is valid? ‘A. MERGE INTO new_employees c USING employees e ON (c.employee_id = e,employee_id) WHEN MATCHED THEN UPDATE SET c.name = e.first_name 11''I] edlast_name WHEN NOT MATCHED THEN INSERT VALUES (e.employees.i¢, e.first_name [['/'I] evlast_name); B, MERGE new_employees c USING employees e ON (c.employee_id = e.employee_id) WHEN EXISTS THEN UPDATE SET c.name = e.first_name [I'l elast_name WHEN NOT MATCHED THEN INSERT VALUES (e.employee_id, e.first_name |!".'I] e.last_name); C. MERGE INTO new_employees c USING employees e ON (c.employee_id = e.employee_id) : WHEN EXISTS THEN UPDATE SET c.name = e.first_name ||",'|] e.last_name WHEN NOT MATCHED THEN INSERT VALUES (e.employees_id, e.first_name |I','I] e.last_name); D. MERGE new_employees c FROM employees e ON (c.employee id = e.employee_id) WHEN MATCHED THEN UPDATE SET c.name = e.first_name I") edast_name WHEN NOT MATCHED THEN INSERT INTO new _ employees VALUES (e.employees_id, e.first_oame {|','|| e.last_name); ‘Naresh I Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 90009. -°8 ~122- racle 11g Material ——— ee Transaction Control Language Oracle 11g Material ‘ransaction Control A transaction is a logical unit of work. All changes made to the database can be referred to as.a transaction. Transaction changes can be made permanent to a database only if they are committed. Transaction sta’ id end cases * A transaction begins when the first executable SQL statement is encountered. «The Transaction Terminates when the following specifications occur. © ACOMMIT OR ROLLBACK is issued. © ADDL statement issued. © ADCL statement issued. co The user Exits the SQL *Plus o Failure of Machine or System Crashes. Commit It used to save changes made by DML statements. Types of Commits: . Implicit Commit o ADDL statement or a DCL statement is automatically committed by implicitly commit and hence’ ends a transaction. Explicit Commit 0 Itis given by user, valid for only DML operations. ROLL BACK: + _Itis used to cancel transactions which are not saved. SAVE POINT:~ * IT is used to mark with current transaction . + Savepoints are used to identify a point in the Transaction to which you can rollback rather than cancel the complete transaction. ‘State of data before Commit or Rollback ‘* Every data change made during the transaction is temporary until the transaction is committed + Data manipulation operations primarily do not affect the state of the data, hence the can be recovered. + The current user can review the results of the Data Manipulation operation by Querying the tables. * Other users can not view the results of the Data Manipulation made by the current user. State of the Data after commit is issued Data changes are written to the database permanently. The previous state of the data in the Database is Permanently Lost. All users can view the Results of the recent Transactional change. The Locks on the affected rows are automatically released. All SAVEPOINT are erased, Sal>COMMIT; State of the Data after Rollback + Rollback statement is used to Discard all pending changes. ‘+ The Data changes are undone. ‘+ The previous state of the data is returned OR Restored. + The LOCKS on the affected rows are released automatically Sql>ROLLBACK; Rolling Back Changes to a SAVEPOINT + SAVEPOINT is used to create a Marked in the current Transaction. + Using SAVEPOINT the transaction can be discarded up to the marked by - .ing the ROLLBACK statement. Sql>ROLLBACK TO ; + Ifa second SAVEPOINT is created with the same name as an earlier SAV! INT, The Earlier SAVEPOINT is deleted. ‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Pi: 23746666, 9000991008 124- Oracle 1g Material oce 1) CREATE TABLE dept (deptno NUMBER(2), dname VARCNAR2(14), toc VARCNAR2 (13); ROLLBACK; DESCRIBE DEPT What is true about the set? A, The DESCRIBE DEPT statement displays the structure of the DEPT table. B, The ROLLBACK statement frees the storage space occupies by the DEPT table. C. The DESCRIBE DEPT statement returns an error ORA-04043; object DEPT does not exist. D, The DESCRIBE DEFT statement displays the structure of the DEPT table only if there is a COMMIT statement introduced before the ROLLBACK statement. 2) Which two statements complete a transaction? (Choose two) A. DELETE employees; _B. DESCRIBE employees; C, ROLLBACK TO SAVE POINT C; _D, GRANT SELECT ON employees TO SCOTH £. ALTER TABLE employees SET UNUSED COLUMN sal; F, Select MAX(sal) FROM employees WHERE department _ id 20; 3) Evaluate the SQL statement DROP TABLE DEPT: Which four statements are true of the SQL statement? (Choose four) ‘A. You cannot roll back this statement. B, All pending transactions are committed, C. All views based on the DEPT table are deleted. D. All indexes based on the DEPT table are dropped. E. All data in the table is deleted, and the table structure is also deleted. F. All data in the table is deleted, but the structure of the table is retained. G. All synonyms based on the DEPT table are deleted, ‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 125 - : Oracle 11g Material Data Definition Language Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 126- Oracle ip Materiat —— ee Altering The Table Definition 1, ALTER to modify the structure of the table(add new columns, remove existing columns). Alterting for adding Column 2. ADD It is used to add new column(s). Syntax for Adding Column ‘Sql>Alter Table
ADD (Column Name Datatype[DEFAULT Exp}, Column Name Datatype]..... ); Sql>Alter table faculty ADD phoneno umber(10); Sql>Alter table faculty ADD(- City varchar2(10), Bonus number(6,2) ); jidelines \DDING Colum 4 We cannot specify the location where the column can appear, It by default become the Last Column, 5. I’ the table contains records, before the column is added, the new column contains NULL values. Modify. 6 Itis used to modify structure of existing column(s). ‘Syntax for Modifying Column ‘Sql>Alter Table
MODIFY ( Column Name Datatype[DEFAULT Exp], * Column Name Datatypel..... yi Sql>alter Table Faculty MODIF City Varchar2(20); 7 We can increase the width or precision of a numeric column. 8 We can decrease the width of a column if the column contains only NULL values and if the table has no rows. 9. We can change the data type if the column contains NULL’s. 10 We can converts a CHAR column to the VARCHAR? data type or convert a VARCHAR? Column to the CHAR data type if the column contains NULL values or if the size is not changed. Drop 1 It is used to remove column(s). Guidelines to Drop a Column 2 The column may or may not contain data. 3. We can drop more than one column at a time. 4 The table must have at least one column remaining in it after it is altered. 5 Once a column is drooped it cannot be recovered. Sql> Alter Table
DROP Column ; Sql>Alter Table Temp Drop column Empno; For more than column ‘Syntax Sqi> Alter Table
DROP (ColumnName1,ColumnName2,...); sonny Sql> Alter Table Temp Drop(JOB,MGR); Rename columns 1 Acolumn can renamed in table by using ATER RENAME . 2 The Feature is enabled from oracle 9.2 onwards. 3. We can rename only one column at a tiem. Syntax ‘Sqi>Alter Table
RENAME TO Sql>Alter Table Emp Rename Column Empno TO Employ_no; ‘The SET UNUSED OPTION 1 The SET UNUSED OPTION marks one or more columns as unused such that hey can be dropped when the demand on System Resources Is less(8i Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, Oracle 11g Material —— eee 2 The response time is faster than the DROP clause. 3. after a column has been marked unused, we cannot have access to that columt 4 The names and types of column marked unused will not be displayed during a describe, 5 We-can ADD to a TABLE a new column with the same name as an unused column. Sqi>Alter Table Temp Set UNUSED(Job); DROP UNUSED Column tion 1 This option removes from the table all columns currently marked as unused. 2. The option is used when we want to reclaim the extra disk space from unused columns in the table. 3 If the table does not Contain UNUSED columns the statement returns with no esror. Sql Alter Table Temp Drop UNUSED Columns; Dropping A Table 1. It removes the definition of the oracle table. 2 The command not only drops the table and along with the associated INDEXES also, ‘Syntax Sql>DROP TBALE
[CASCADE CONSTRAINTS]; Sql>Drop Table Temp CASCADE CONSTRAINTS; : Guidelines to Drop Table 1 The data is totally deleted from the table, 2 Any VIEWS and SYNONYAMS will remain but are kept in invalid state. 3. Any pending transactions are committed. 4 Only the create or owner of the table or a USER with DROP any table privilege can remove a table from Database. 1 The DROP Table statement once executed is irreversible. hanging the name of an Object 2. The RENAME command can be used to change the name of a 3° TABLE 4 VIEW 5 SEQUENCE 6 SYNONYM To RENAME the OBJECT we must be the OWNER of the OBJECT. Syntax Sql>RENAME TO ; Example ‘Sql>RENAME Emp TO Employee; Tuncating A Table It is used to remove all rows from a table and to release the STORAGE SPACE Used by the specific TABLE. ee + The TRUNACTE TABLE will not facilitate for ROLLBACK, mtax: ‘Sql>TRUNCATE Table
; Example: Sql> TRUNCATE Table Employee; + To TRUNCATE a Table we must be the OWNER of the Table Applying Comments Upon a Table + The COMMENTS command is used to ADD comments to a TABLE or a COLUMN or VIEW etc, + Each comments can be up to 2000 bytes. + The data dictionary in which comments are stored are... *ALL_COL_COMMENTS *ALL_TAB_COMMENTS *USER_COL_COMMENTS *USER_TAB_COMMENTS Naresh { Techalogies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746('*, 9000°94008 128 Oracle 11 Matestal ee Syntax ‘Sql>COMMENT ON table/Column is ‘Tex Example: Sq}>COMMENT ON Table Emp 1S "The table storing employee Information’; Sql>COMMENT ON Column Emp.MGR IS ‘The Column is actually storing the Registered employee number as Manaver Numbers, with a Self relation’; Dropping a Comment + Acomment is dropped from the database by setting it to an empty string, Sql>COMMENT ON table Emp IS Advanced Table Creation Strategies Creating a table from an Existing Table ON THE FLY Tables * Oracle allows the creation of a new table On-The_Fly, Depending on «~ statement on an already existing table. ‘Syntax Sql>Create Table
AS Select Columas From TableName [Where Condition]; + The Create Table...As SELECT... Command will not work if one of t columns use LONG data type. + When the New table is described it reveats that it has "INHERITEL definition from the Existing table + Using this style we can include all columns using asterisk or as: from table, + The New table can contain “INVENTED COLUMNS" which are th function of the combination of other columns. + The column definition will adjust to the size necessary to contsi= t'2 « he INVENTED COLUMNS, Creating an Exact Copy Sql>Create Table Temp AS Select *From Emp: Create an Exact Copy with different and required column nam ‘Sqi>Create Table Templ ( Ecode, Name, Basic, Deptno empno,ename,sal,deptno From Emp; Create a Copy with Invented Columns ‘Sqi>Create Table Temp2 ( Deptid, Deptname, Deptbudget ) AS Select D.deptno,D.dname,SUM(E,Sal) From Emp i E.deptno=D.deptno Group by D.deptno,D.dname; Creating a copy without Data Sql>Create Table Temp3 ‘As Select Empno “Emp_Num’,Ename “Emp_Name",Sal “Basi” 691.0 “Dept_Num” From Emp Having ‘KRISHNA’=‘ORACLE’; Creating a table without Generating REDO LOG Entrie * REDO LOG entries are chronological records of database act! bhases recoveries. + The REDO LOG entries generation can be avoided by using keyword. + By circumventing with NOLOGGING key word the performs, -*"h'2 CHEAT ‘TABLE command will improve as less work is being done. + As the new tabie creation is not being written to the REC wy not be able to Re-Create, following a Database failure. + The REDO LOG files are Used to recover the Database Sqi>Create Table Tdept NOLOGGING AS Select * From Sql>Select LOGGING From ALL_TABLES Where Table_Namc Sqlzselect *from v$logfile —— eee io Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 2 Oracle 11g Material Creating Index Organized Table: * An Index Organized table keeps its data stored according to the PRIMARY KEY column values in the table. + An Index Organized table stores its data as if the entire table was stored in an INDEX, + To create an Index organized table the ORGANIZATION INDEX clause of the CREATE TABLE is used. + To create a table as an Index Organized table we must create a PRIMARY KEY constraint on it. Example ‘Sql>Create Table DemoTab ( Stuid Number(4), Name Varchar2(20), Doj Date, Constraint sid_pk PRIMARY KEY(Stuid,Name) )ORGANIZATION INDEX; + To Minimize the amount of active management of the Index Organized table, we should create it only if the table's data is very static. + An Index Organized table is most effective when the Primary key constitutes a large part of the tables columns. Worving with Partitioned Tables Dividing the rows of a single table into multiple parts is called Partitioning of a table. «The table that is Partitioned is called "PARTITIONED TABLE” and the parts are called PARTITIONS. + The Partitioned is useful for very large Table only. Important Goals behind Partitioning » The performance of Query against the tables can improve performance. + The Management of the table becomes easier. + As the Partitioned table data Is stored in multiple parts, It is Easier to Load and Delete data in Partitions than in the Large Table. + The backup and recovery operation can be performed better. Normal un Partiti le Sql>Create Table TempTable ( Sampleid number(4) Constraint Sampidpk Primary key,Sampname Varchar2(20), Sampdate date, Sampdesc Long ); Creating Range Partition Table Sql> Create Table TempTablePart ( Empid number(4) Primary key, Empname Varchar2(20), Doj date, Remarks Varchar2(4000) ) PARTITION BY RANGE(Empid) ' (PARTITION Empidpart1 Values LESS THAN(509), PARTITION Empidpart2 Values LESS THAN(1000), PARTITION Empidpart3 Values LESS THAN(MAXVALUE) ) The Maximum value need not be specified for the last partition, the MAXVALUE keyword is specified, ‘The MAXVALUE specified oracle to use the partition to store any data that could not be stored in the earlier partitions. We can create multiple partitions each with its own upper value defined. The minimum value for the range is implicitly determined by orac'e from the definition of the preceding partition. Hash Partitions upon a table * Ahash partitions upon a table determines the physical placement of data. «The Physical placement of data is determined by performed a Hash function on the values of the partition key. + To create a Hash Partition we use the PARTITION BY HASH Clause, Sq|> Create table emptablehash (Empno Number(6) constraint empnopk Primary Key, Ename Varchar2(20), Job Varchar2(30), Deptno Number(2), Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994: 130 3 CHECK( Deptno IN(10,20,30,40,50,60,70,80,90)), Sal Number(8,2),Constraint Deptnofk_Hash Foreign key (Deptno) References Dept(Deptric’ ) PARTITION BY HASH(DEPTNO) PARTITIONS 9; Working with List Partitionin * In LIST PARTITIONNING we specify oracle all the possible values and desis ‘the partition into which the corresponding rows should be instead. Sql>Create Table Emplistpart ( EMPNO NUMBER(4) Constraint pk_eno PRIMARY KEY, RCHAR2(10), JOB VARCHAR2(9), MGR NUMBER(4), HIREDATE DATE, SAL NUMBER(7,2), COMM NUMBER(7,2), DEPTNO NUMBER(2), Constraint dnofk Foreign Key(Deptno) REFERENC Dept(Deptno) )PARTITSON BY LIST(Job) ( PARTITION jpart1 Values('PRESIDENT’,’ANALYST’), PARTITION jpart2. Values(‘MANAGER’, SALESMAN’, CLERK’) si ni Sub partitions are partitions of partitions. Sub partition can be used to combine the two types of partitions... RANGE Partitions HASH Partitions In very large tables, the composite partition star strategy is an eff: separating the data info manageable and tunable divisions, Sql> Create Table Empsubpart (EMPNO NUMBER(4)Constraint eno_y Key, ENAME VARCHAR2(10),J0B _ VARCHAR2(9),MGR__ Nv HIREDATE DATE,SAL NUMBER(7,2),COMM NUMBER, DEPTNO NUMBER(2),Constraint fkdno Foreign Key(D< Dept(Deptno) ) PARTITION BY RANGE(ENAME) SUBPARTITION BY HASH(JOB) SUBPARTITIONS 5( PARTITION Namep1 VALUES LESS THAN ('M'), PARTITION Nam VALUES LESS THAN (MAXVALUE) ); Splitting Table Partitions Sql> Alter Table TempTablePart ‘SPLIT PARTITION Empidpart3 AT(2000) INTO( PARTITION Empidpart3, PARTITION Empidr Sql> Alter Table Emplistpart SPLIT PARTITION jpart2 Ve INTO (PARTITION JSalesMan, PARTITION S: Merging Table Partitions ‘Sql>Alter Table Emplistpart MERGE PARTITIONS Jpart1, JSa! Ipart; Sql> Alter Table Emplistpart MERGE PARTITIONS Jpart1, JS@ s.:igs: LTO PeRTITION Jpart; Dropping a table PARTITION: : Sql>Alter Table Emplistpart Drop PARTITION Jpart1; Sql>Alter Table Emplistpart Drop PARTITION Jpart1; Sql> Alter Table TempTablePart Drop PARTITION Empic,-.:'> Creating Indexes upon Partitions ‘+ Once a Partitioned table is created, we have ta create an + The Index may be Partitioned according to the same range * used to Partition the Table. Sql>Create INDEX Emptestlistinx ON Emptestlist(JOB) LOC. Oh dpa * The LOCAL keyword tells oracle to create a separate index the table. TS Naresh i Pechnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 2. . Oracle 11g Materiat Oracle Object Oriented Concepts Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 132 Oracle Ig hte ee An Object is a reusable application component that developers need to lic aware of, rather than how it works, Object are the basic entities in a system. They could represent a person, place, bank account, of any item that is hanclied by program. Every object consists of an attribute and one or more methods. An attribute could be any property of the object. Class: Itis a collection of attributes and functions(method) to plan the object. Object Table * Object table are created by using the user defined data types. * In an Object Table each row or record is treated as an object. Each Row in an Object Table has an Object Identifier(OID),Which is unique through out the Database. * The Rows or Objects of an object table can be referenced by other objects \ the Database. * An object table is created using the CREATE TABLE command. © All object types are associated with default methad applied upon the + tables i.e INSERT, DELETE, UPDATE and SELECT. * The relational DML operation style is accepted only when the user def type Is a collection of Built-in data types, and the object table does rv- any REF Constraints. Creating an user defined object type ‘Syntax Sql>CREATE OR REPLACE TYPE as Object (Elementi (size), Element2 (size), Element (size) ); * Alluser defined data types are schema objects of the database. * The user defined object data type can be used as Reference in oth=" < * Alluser defined data types and object are stored permanently i! dictionaries © USER_TYPES USER_OBJECTS * We can Query for the user defined data types and objects using .« SELECT, Sql>Select Type_Name,TypeCode, Attributes, Methods From USER_TYPES; Sql>Select Object_Name, Object_type From USER_OBJECTS; Creating User Defined Addr 1e ‘Sql>Create or Replace TYPE Addr_type AS OBJECT ( Hno VAR. 2/12) Street VARCHAR2(20), City VARCHAR2(20) , Pir =) ois <, Sql>Create or Replace TYPE PF_TYPE AS OBJECT ( PENO NUM: AMT NUMBER(12,2)); * The above statement create the user defined object data type Addr_type and PF_TYPE in the data Dictionary called USER_TY ‘+ This data type is also called as collection in oracle, and this co! where ever the same data type Collection is expected in proje Creating Table with user Defined Data Sqi>CREATE TABLE EMPLOYEE( ECODE NUMBER(3), NAME VA\ ADDRESS ADDR_TYPE, BASIC NUMBER(12,2), PF PF_TY ——— eee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 2374u:. Oracle 11g Materia * Once the user defined data types are created we can instantiate them in the ‘normal relational tables. ‘© These instances look as normal attributes with in the table, but can be operated only with CONSTRUCTOR METHOD or OBJECT VIEWS. ‘© Inany of the operation we have to provide reference to all attributes with in the instance, but partial association is not accepted. Sql>Create table Supp_Det( Rol number(3), Name varchar2(20), Saddr addr type,Course varchar2(20)); Inserting the data into Empl e Tabl Sql>INSERT INTO EMPLOYEE VALUES(100, 'Vijji', ADDR_TYPE('130 A’, “JAYA NAGAR’, 'BLORE',516217), 8000,PF_TYPE(1200,400)); lect Data fr: OBIE le Sql>SELECT *FROM EMPLOYEE; Sql>SELECT ADDRESS FROM EMPLOYEE; Sql>SELECT NAME,E.ADDRESS.CITY FROM EMPLOYEE E; Note: * Alias is must to retrieve/manipulate Object elements. e data from Object Table ‘Sql>UPDATE EMPLOYEE E SET BASIC= BASIC+1000 WHERE E.ADDRESS.CITY="HYD’; Deleting Data from Object table Sql>DELETE FROM EMPLOYEE; ‘Sql>DELETE FROM EMPLOYEE E WHERE €.PF,PFNO=1200; reatic r Defi Emp Det Type Sql>Create type Info As Object{ code Number(4), Name Varchar2(20), Hno VARCHAR2(10), Street VARCHAR2(20), City VARCHAR2(20) , Pin NUMBER(6)); Creating an Object Table * Isa table which is entirely build from the abstract type. ‘Syntax: Create table
of ; Illustrate & Sql>Create table Emp_Info of Info; © The above statement creates the object table Emp as an Abstract data type. i. * Each row in the object table has an O10 value generated by oracle server. * The rows in'the object table are referenced as OBJECTS. Inserting rows into Object Tables *® To INSERT a record into an OBJECT TABLE we may use the CONSTRUCTOR METHOD of the actual data type or directly implement the RELATIONL INSERT statement. * The Normal INSERT OR RELATION INSERT Is possible only when the table does not contain any nested data types. Relational INSER” Sql>Insert into Emp_info Values(1001,’SANJU','12-134",/SRNAG',/MGS' ‘Blore’,516217); Inserting Using Construct Method Sql>Insert into Emp_info Values(Info(1002, ‘Kelly’,'12-135','VIJIT NAG" ‘Blore’,516247)); Sql> Create table supp_info of Info; | REF clause: Itis used to retrieve the object reference. The reference of the object is the address of the row object, witch is internally generated by oracle. The REF() Function » The REF() function allows to reference existing row objects. © The OID assigned to each row can be seen by using the REF function. Sal>Select REF(AN) From Etab AN Where City='HYD'; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Phi: 23746666, 9000994008 ~ 134~ I 4 i | : Oracle 11g Material ———— City will not accept_null values >create or replace trigger city_chk before insert on employ for each row Begin if snew.address.city is null then raise_application_error(-20101, ‘city carnot empty’); end if; End; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, P Oracle 11g Material SQL* LOADER Naresh i Technotogies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 136- Oracle 1g Material SQL * LOADER: co ‘onder Control File fia Taaniefe—{_soutoante_}-—#} Database [= Discard Files [a Tables Working Scheme: SQL * Loader uses a control file called Loader control File, which contains instructions for the execution,’ manipulation, and filtering of the records contained in the input datafiles. During execution, SQL * Loader produces a log file with the operation. If there are records with problems in the input files, a File with the rejected records is produced. Discarded or Rejected Records: The records read from input files that cannot be inserted in the database are written in separate files for further checking or Correction Bad File: A bad file contains the records that were rejected by SQL * Loader or by oracle. Normally, this occurs when the record format is invalid. A common situation & quotation marks missing in a field, or a field without the separation comma, after it is approved by SQL * ioader, the record is inserted in the database. However, oracle can reject it violates some constraint Discard File: SQL * Loader can also create a file called a discard file. The discard file is created when it was specified as activated. It contains the records that did not pass through the selection filter of the contro} files. Log File: When executed, SQL * Loader, creates a tog file containing detailed information about the data processing, including information about possible errars The SQL * Loader Control File: The control File specifies how data in the input file is treated, which tables will receive it, which conversions are made, and so on, This is @ text document file, and the commands to be interpreted by SQL * Loader are written to it. They include ihe specification of the input file location characteristics of rows and columns, specification of data types, and so on. The contents of the file depend on the type of data configuration. However, we can say that it is divided into three parts. The first section contains general information, such as the INFILE. option to specify the input file, the specification of the set of characters. Or global options such as rows, records to skip, and son The second section may contain the INTO TABLE commands each of these commands contains information relating to the table that will receive data. The third section is optional and can store input data, turning the contro! file into a datafile. Load Data: This is a manadatory command that tell SQL * Loader to configure data Infile: This specifies the input datafile. If the filename extension is omitted, data is assumed. If on asterisk is specified, the program assumes that data is inside its own control file, after the word BEGINDATA. Examples: INFILE INFILE test.dat INFILE ‘C:/topdir/subdir/datafile.dat" Append/Replace/Truncate: If the table to be configured are empty, you can use the INSERT option. If the tables have contents, the options APPEND, REPLACE, or TRUNCATE can be used Naresh t Technologies, Opp. Satyam Theatre, Amectpet, Hyderabad, Ph : 23746666, 9000994008 - 137- Oracle 1g Material APPEND adds the rows to the end of the table, REPLACE deletes all the rows of the table before inserting new ones, and TRUNCATE adds the rows in an attempt to obtain the best performances, Delimiters: Special Characters can delimit fields at type char, date, or numeric external, The delimited fields can be enclosed in a character or terminated by another character. Ex: load data infile "d:\dept.txt* 0 table dept fields terminated by "," (deptno,dname,loc) load data infile "d:\dept.txt* append into table de fields terminated by " (deptno,dname,loc) load data Infile "d:\dept.txt" truncate into table dept fields terminated by", (deptno,dname, loc) load data infile "d:\depts. txt” replace into table dept fields terminated by *," (deptno,dname,loc) load data infile * truncate into table dept fields terminated by *," (deptno,dname,ioc) Begindata 60,SW,BLORE 7O,EXP,HND, load data infile "d:\dept.txt” infile "d:\deptd txt" insert into table dept fields terminated by (deptno,dname,loc) Flashback Query: -->Using Flashback feature which was introduced from Oracle 109, we can quickly rewind a data base to previous time to correct any.problems or users errors, -->It provides point in time recovery without requiring a backup to restore. Example: Login krishna/oracle >desc recyclebin Stepi: drop table.(Temp) >select OBJECT_NAME,ORIGINAL_NAME,OPERATION from recyclebin where ORIGINAL_NAME="TEMP'; To find droptime,createtime of table. >select OBJECT_NAME,ORIGINAL_NAME, OPERATION, droptime,createtime from recyclebin where ORIGINAL_NAME="TEMP'; To recavery the TEMP table > flashback table temp to before drop; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph : 23746666, 9000994008 - 138 - . Oracle 11g Material —— Query for Practice Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 139- Oracte 11g Material ——————————————————————— 1)DEPT table is required with the following structure: DEPTNO NUMBER(10) DNAME CHAR(30) LOC VARCHAR2(33) 2)EMP table is required with the following structure. EMPNO NUMBER(2) ENAME VARCHAR2(15) JOB VARCHAR2(15) MGR char(4) HIREDATE DATE SAL NUMBER(6) COMM NUMBER(6) DEPTNO NUMBER(2) 3)Display the DEPT details from department table. 4)Display the EMP details from employees 5)Display empno,ename and job for all employees 6)Reduce the size of DEPTNO cciumn of DEPT table to 2 7)change the data type of DNAME to VARCHAR2 and width to 15. 8)Reduce the with of LOC to 15. 9)Increase the size of EMPNO to 4 . 10)Reduce the size of JOB to 10 11)Change the data type of MGR to NUMBER(4) 12)SAL should accept 5 integers and 2 decimals 13)COMM should accept 5 integers and 2 decimals 14)Display all the details of all SALESMAN 15)List the emps who joined before 1982, 16)List the empno,ename,deptno, hiredate,and Exp of all Managers. 17)Display all the details of the emps whose Comm is more than their Sal 18)List the emps along with their Exp and whose Daily Sal is more than Rs 200 19)J0B can be duplicate 20)0MM can be NULL 21)HIREDATE should not be SUNDAY 22)SAL should be less than or equals to 10,000 23)EMPNO should be primary key 24)DEPTNO of DEPT table should be PRIMARY KEY 25)DEPTNO of EMP table should be a foreign key to DEPTNO of DEPT table. 26)Display the names of all the employees and their experience in years. 27)Deptno of EMP table should be a foreign key to DEPTNO of DEPT table. 28)List all employees number,name,job and hiredate of employees in department 10. 29)Select the name and salary of all employees who are CLERKS 30)Display the unique Dept’s of emps. 31)Display emps whose Salary is more than 2000 after giving 20% increment. 32)List the Empno,Ename and Sal is increased by 20% and expressed as No.of.RS 33)Disriay the unique Dept with Jobs. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 140- is Oracle 11g Mat 34)List all MANAGER,CLERKS 35) Display alf employee names and their salaries whose salary is not in the range on 4500 and 2850 4 The Column Heading to be displayed as Emp Monthly Name Salary 36) Display the name of the employee who don't have any manager. 37) Display the name ,salary and commission for all emplayees whose commission amount is greater than their salary increased by 10% 38) Display the Ename,salary and salary increased by 15% expressed as a whale number.Label the column New Salary.in addition to this display the Increase of salary over the previous one, For Example. ENAMESAL NEWSAL INCREASE KING 5000 5500 500 39)Display the Employee name ,hiredate, salary review date which is the first Monday after 6 months of the service. EnameHliredate Review 40)Display employee number and total salary for each employees. 41)Display employee number and annual salary for each employees. 42)Display the names of ali employees who are working in department number 10 43)Display the names of all employees working as MAMAGER and drawing a salary more than 2000. 44)Display employee number and names for employees who earn commission, 45)Display names of employees who do not earn any commission 46)Display the names of employees who are working as CLERK,SALESMAN or ANALYST and drawing a salary more than 2000. 47)Display the names of employees who are working in the company for the past 5 ‘years, 48)Display the list of employees who have joined the company before 31° JAN 81 or 30 NOV 81. 49)Display current user 50)Display current date 5i)list the first 10 records of the EMP table. 52)List the emps empno,ename,sal and the column heading as Emp_Num,Emp_Name,Salary. 53)List all the unique deptno of emps. 54)Display the Job and the no, of persons working in each job type. 55)Display the name and salary of all employees who are CLERKS. 56)List the name,job and salary of everyane hired on December 17,1980. 57)List the Department name and department number for departments with numbers greater than of equals to 20. 58)Select the name, salary and commission of employees whose commission is greater than thelr salary, 59)Display the names of employees working in department number 10 or 20 or and employees working as CLERK,MANAGER or SALESMAN. 60)Display the name, monthly salary, daily salary and hourly salary for all employees. Assume that SAL column in the table is monthly salary; that there are 22 Working days in a month; and that there are 8 working hours ina day, Rename the columns as MONTHLY, DAILY and HOURLY. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 141 - Oracle 11g Material eee 61)Display details of FORD. 62)Display the names of employees whose name starts with alphabet M 63)Display the names, job of employees whose job ends with alphabet R 64)List the names of employees whose name is exactly four character in length 65)List the names, jobs of employees whose name have second alphabet 66)Display the names of employees who are not working as manegers 67)Display all employees joined.on 1 MAY 1981. 68)Display empno, ename, hiredate of all employees joined before 1 JAN 1983. 69)Display ‘employee number and total salary for each employee 70)Display employee name and annual salary for all employees 71)Display the names of all employees who are working in department number 10 72)Display the names of all employees working as clerks and drawing a salary more than 2000 73)Display the employees whose names start with ‘T’ and end with 'R’ 74)Display the employees whose exp is more than 10 years 75)Display the who are working as clerks and exp is more than 15 Years 76)How to create .LST file 77)Display the names of employees who are working as clerk , salesman or analyst and drawing a salary more than 3000 78)Dieplay the total number employees working in the company c 79)Display the total salary and total commission to all employees. Ma 80)Display all rews from emp table. The system should wait after every screen full of & information, * 81)List the names and employee numbers of managers who earn more than 2600,in the ordei' of names. & 82)select the information about managers and the president from the column job in the : EMP table, order the result by department number. e 83)list all the employee names that do not end with 'S’ @ 84) Display the maximum salary from emp table . 85) Display the minimum salary from emp table ’ 86) Display the average salary from emp table e 87) Display the maximum salary being paid to CLERK : 88) Display the maximum salary being paid in dept no 20 Display the 89) Display the = minimum salary being paid to any SALESMAN s 90)List the name,job and department of everyone whose name falls in the alhabetical = range from 'C’to *F’ 2 91) List the empno,ename,sal,job of emps with the annSal<3400 but receiving some + comm. Which should not be greater than Sal and the desg should be Salesmen working £ for dept 20. e 92) List all the unique jobs along with deptno. 93) Display the average salary drawn by managers 94) Display the total salary drawn by analyst working in dept no 40 95) Display the names of employees in order of salary i.e. the name of the ployee earning lowest salary should appear first. 96) Display the names of employees in descending order of salary. 97) Display the details from emp table in order of emp name. 98) Display empnno,ename,deptno and sal. Sort the output first based on na 2 and within name by deptno and witdhin deptno by sal. 99) Display the name of employees along with their annual salary(sal*12). 7 name of the employee earning highest annual salary should appear first? 100)Display all employee names start with 'TH’ or ‘LL’, 101)Dispiay all employees who are hired during 1983. 102)Display the data as Who..What..When. Ex SMITH HAS HELD THE POSIT. OF CLERK IN DEPT 20 SINCE 13-JUN-83. 103)List the details of the employees in department 19 and 20 in alphabetice rder of names. 104)List all rows from EMP table by converting the NULL values in COMM col Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000 G Oracle Lig Material ——————————— 105)List all SALESMAN 106)List all managers and salesman with salaries over 1500. 107)Write a query that will accept a given job and displays all records according to the job. '108)List the names and hiredates of employees in department 20.Display the hiredates as ‘DD/MM/YY". 109)How many months has the president worked for the company?Round to the nearest whole number. 110)List all the employee names, jobs and a job classification ,which you will supply. Translate the value stored in each job filed(CLERK,MANAGER,etc) to a job Classification number(1,2,etc). Translate CLERK to 1,MANAGER to 3,PRESIDENT to 5 and all other jobs to 2.Name the job classification column JOB-CLASS. 111) List all the emps who are working since 1* April 1982. 112) List the emps who joined before 1985 and salary is more than 3000. 113) Give SQL commands to find the average annual salary per jobs in each department, The SAL figures in the EMP table are for each month. 114) In one query, count the number of people in department 30 who can_ receive a salary and the number of people who receive the commission. 115) Display name,salary,Hra,pf,da, TatalSalary far each employee. The out put should be in the order of total salary,hra 15% of salary,DA 10% of salary .pf 5% salaryTotal Salary will be salary+hra+da)-pf? 116) Display Department numbers and total number of employees working in each Department? 117) Display the various jobs and total number of employees working in each job group? 118) Display department numbers and Total Salary for each Department? 119) Display department numbers and Maximum Salary from each Department? 120) Display various jobs and Total Salary for each job? 121) Display each job along with min of salary being paid in each job group? 122) Display the department Number with more than three employees in each department? 123) Display the department Number with more than three employees in each department? 124) Display various jobs along with total salary for each of the job where total salary is greater than 4000? 125) Display the various jobs along with total number of employees in each job.The output should contain only those jobs with more than three employees? 126) Display the emps whose job same as FORD. 127) Display the emps who are senior to KING. 128) Display the name of employees who earn Highest Salary? 129) Display the employee Number and name for employee working as clerk and earning highest salary among the clerks? 130) Display the names of salesman who ears a salary more than the Highest Salary of the clerk? 131) Display the names of clerks who earn a salary more than the lowest Salary of any salesman? 132) Computer Average, Minimum and Maximum salaries of those group of employees having the job of CLERK or MANGER. 133) Display the department number where more than twa clerks are working. 134) Calculate the total compensation expense for each department for one year. The sal and comm figures in the EMP tables are for each month. Assume that employees who don’t earn @ commission receive non-monetary benefits that are worth s,400/-. 135) Do a case sensitive search for a list of employees with a job that a user enters. 136) Display the names of employees. who earn a salary more than that of jones or that of salary greater than that of scott? 137) Display the names of employees who earn Highest salary in their respective departments? 138) Produce the names and jobs of employees as Ex:-SMITH(CLERK). Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 ~ 143 - Oracle 11g Material 139) Which employees earn less than 30% of the president's salary? 140) Display the names of employees who earn Highest salary in their respective departments? 141) Display the names of employees who earn Highest salaries in their respective job Groups? 142) Display employee names who are working in Accounting department? 143) create-a view consisting of employees and theit total sum of salary grouped by department number wise. 144) Display the employee names who are Working in Chicago? 145) Transfer SMITH to deptno 10. 146) Transfer the emps of dept 20 to 30. 147) Transfer the emps CHICAGO to DALLAS. 148) Create a view consisting of all the columns from EMP table and their corresponding records from dept table consisting of department name & location 149) How many employees are working in NEW YORK. 150)Update the Salary of ‘ALLEN’ with the highest paid emp of Grade 2 and transfer him to BLAKEs dept and change the MGR to BLAKE, 151) Create a query that will display the employee name ,dept number and all the employees name that work in tha same dept as a given employee. 152) Display dept name,location,number of employees and the average salary for all employees in that dept. 153) Display the employee name and his manager's name. . 154) Display the employee's name, department's name ,grade and manager's name. 155) Print the following: salary itself if it is 1500.’HIGH' if it is more than 1500.'LOW’ if it is less than 1500, 156) Display the job groups having Total Salary greater than the maximum salary for Managers? 157) Display the names of employees from department number 10 with salary greater than that of ANY employee working in other departments? 158) Display the names of mployees in Upper Case? 159) Display the names,jobs of employees in Lower Case? 160) Display the names of employees in Proper case? 161)Find the length of your name using Appropriate Function? 162) Display the length of all the employee names? 163) List department number, department name, location, commission paid and total salary of each department. 164) Display the average monthly salary bill for each job type with in a department. 165) Display those jobs where the minimum salary is greater than or equal to 3000. 166) Display the name of employee Concatinate with Employee Number? 167) Use appropriate function and extract 3 characters starting from 2 characters from the following string ‘Oracle’ i.e., the out put should be ac? 168) Find the first occurance of character o from the following string Naresh Technologies . 169) Increment the Salaries by 5% and add a comm. of 300 to the existing comm. and changing the clerk to jobs of all ‘salesman’ whose salaries is more than or equal to 1500. 170) Increment the sals of the emps by 5% 171)Increment the sal of all the by Rs 500 and change their MGR to 7902 172) Change the MGR of all BOSTON related emps FORD. 173)Transfer the emps to analyst dept and give the sal of smith plus 500 to those belongs to grade 3 working at NEW YORK or DALLAS with an exp>7y whose name should : not be 4 chars. 174)Find out the difference between highest and lowest salaries. 175)Find all department, which have more than 3 employees. ‘ 176) List lowest paid employee working for each manager, exclude any group where the ¥ minimum salary is less than 1000,in the reverse order of salaries. t 177) Display all employee names and their department names in the order of * 4 Naresh i Technologies, Opp. Satvam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 144 - Oracle Lig Material —— department names, 178) Display all employee name, department numbers, and department names 179) Replace every occurance of alphabet A with B in the string .Allliens (Use Translate function)? 180) Display the information from the employee table . where ever job Manager is found it should be displayed as Boss? 181) Display empno,ename,deptno from emp table. Instead of display department numbers display the related department name(Use decode function)? 182) Display your Age in Days? 183) Display your Age in Months? 184) Display current date as 15th August Friday Nineteen Nienty Seven? 185) Display the following output for each row from emp table? Scott has joined the company on 13th August ninteen ninety? 186) Update the deptno of sales dept for those emps working at deptno 10, 187) update the salary of FORD with the highest paid salary emp of SALESMAN more than 8 Y exp. 188) Change the mgr to 7788 for those working for the mcr 7369, 189) Display the departments that have no employees. 190) Find all employees who joined the company before their managers. 191) Find the employees who earn more than the lowest salary in each department. 192) Add 300 to the comm, of all SALESMAN who are receiving some comm. 193) Change the deptno of FORD to 30 and also change the job as SALEMAN with an increment in the Salary 8%. 194) Display employees who earn more than the lowest salary in each department 30, 195) Find the job with highest average salary. 196) Display the name, job, and hiredate for employees whose salary is more than the highest salary in SALES dept. 197) Transfer the emps of dept 20 to SALES dept. 198) Give an increment of 300 to all emps of grade 2. 199) Replace the sal of SMITH with the highest paid CLERK of NEW YORK or DALLAS. 200) Display all the employees whose grade is the same as that of JONES 201) Display the empname,salary of all employees who report to KING. 202) Display the empname,gross,job,loc who are having more than JONES Gross. 203) Display current date and 78 days after. 204) Find the nearest Saturday after Current date? 205) Display the current time? 206) delete all the information of CLERKS. 207)Delete all Grade 2 emps 208)Delete all employees who joined in the month of DEC 1981, 209)Delete all the emps working in NEW YORK. 210)Delete all the emps who are senior than their manager. 211) Display the date three months before the Current date? 212) Display the common jobs from department number 10 and 20? 213) Display current date and 78 days after. 214) Display the current date in the following fashion. 215) Display Employee name and Job information from employee in the following fashion. 216) Display all the information from dept table where second character of LOC name is 'R. 217) Display the last date in Feb-97. 218) Display logged an user name in the following fashion.Current User Name is : SCOTT 219) Display ‘NARESH TECHNOLOGY IS VERY GOOD FOR ORACLE! text as 'Naresh Technology Is Very Good For Oracle’ in a Select statement. 220) Select employee name ,Hiredate in the farmat of "2nd of july 1997" far deptno 10 and 20, 221) Display employee names in lower case whose salary is greater than 2000 and less ‘than 2800. Se Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 145 - Oracle Lig Material 222) Display the jobs found in department 16 and 20 Eliminate duplicate jobs? 223) Display the details of those employees who do not have any person working under him? 224) Display the details of those employees who are in sales department and grade is 2 225) Display those department whose name start with"S" while location name ends with “Kr? 226) Display those employees whose manager name is Jones? 227) Display those employees whose salary is more than 3000 after giving 20% increment? 228) Display all employees with their department names? 229) Delete all the emps. working under FORD with exp>Syear. 230) Delete the Information FORD,SCOTT. 231) Delete the emps who joined most recently under FORD. 232) create a unique index for employee names of emp table. 233) Assuming the salary of emp table as for a month, produce annual salary with haeding as ANNUAL SALARY’, 234) $ lect employee number and name combined to together to together with a heading ‘EMPLOYEE’. 235) Display in how many department employees are working 236) List the employees who are having experience of more than 10 years 237) List tre employees who have’ or ‘LL’ as the exact middle character(s) of their names. 238) List the employees whose name bigger than their manager's name. 239) List the employees who are managers of clerk with salary more than 2000. 240) Find all the managers in any department and all clerks in department 10 only. 241) List the employee names by adding ‘~' on left side, to the double of the actual size of the name. 242) Display ename who are working in sales department? 243) Ust the total information of EMP table along with dname and loc of all the emps working under *SALES’ or ‘ACCOUNTING’ in the asc deptno. 244) Display employee number, employee name, department name, location from employee and department tables 245) Display employee number, employee name, salary + comm as TOTAL, location, from employee and department tables. 246) Display the empno,ename;sai,dname,loc of all the CLERK or MANAGER working in NEW YORK or CHICAGO with an exp more than 8 years without receiving the COMM. 247) Diplay employee name, department name, job from employee and department tables who job is CLERK. 248) Display employee name, deptno, dname from employee and department table where location is DALLAS. 249) Display empno,ename,deptno,dname from emp and dept who empno is 7788 or 7902. 250) Display first 3 characters of employee name, job, sal, comm, location from employee and department tables who works in department 20 or 30, salary should be more than 1000 comm as not null. 251) Delete the emps who joined most recently under KING 252) Delete grade 3 and 4 emps. 253) List the employee names where the second occurrence from second position is ‘A’. 254) Display employee name,job,hiredate and salary combined together without using the ‘|’ operator, 255) Display employee name,dept name,salary,and commission for those sal in between 2000 to 5000 while location is Chicago? 256) Display those employees whose salary is greater than his managers salary? 257) Display those employees who are working in the same dept where his manager is work? 258) Display those employees who are not working under any Manager? Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 146 - Oracle 11g Material 259) Display the grade and employees name for the deptno 10 or 30 but grade is not 4 while joined the company before 31-DEC-82? 260) Update the salary of each employee by 10% increment who are not eligible for commission? 261) Delete thase employees who joined the company before 31-Dec-82 wlille their department Location is New York or Chicago? 262) Delete the emps who belongs to Grade 2 or 3 working at Chivago joined in any month of the first half of 82. 263) Delete duplicate records in the emp table. 264) Delete those dept's where no employee is working. 265) Delete the emps who are senior to their own managers. 266) List all managers from all departments and all clerks from department 10 only. 267) List all employee names from from EMP table if the name contains second and last- but-one character as W. 268) List all columns from bath the DEPT and EMP tables 269) Display different jobs and the number of employees working from EMP table, 270) Display the difference between total salary of department 10 and department 20. 271) Display first 3 characters of employee name, job, sal, comm, location from employee and department tables who works in department 20 or 30, salary should be more than 1000 comm as not null. 272) Display location, department name, length of location, length of department name for employee numbers 7788, 7902,7346. * 273) Display location and sum of the salary spending for employees on that location respectively. 274) Select department number, dname, average salary for each department, 275) Select department number, name where atleast 3 employees works. 276) Select department name, location where the average salary in each department more than 1600. 277) Count how many employees have 'S' in their names. 278) Produce this formant EMPLOYEE. JOB SMITH, CLERK ALLEN, SALESMAN : 279) Display employee name ,job,deptname,loc for all who are working as manager? 280) Display those employees whose manager name is janes and also display their manager 281) Display name and salary of ford if his salary is equal to hisal of his grade? 282) Display employee name ,job,deptname,his manager name ,his grade and make an under department wise? 283) List out all the employee names ,job,salary,grade and deptname for every one Ina company except 'CLERK' . Sort on salary display the highest salary? 284) Display employee name,job and his manager .Display also employees who are with out managers? 285) Display Top 5 employee of a Company? 286) Display those employees whose salary is equal to average of maximum and minimum? 287) Select count of employees in each department where count >3? 288) Display dname where atleast three are working and display only deptname? 289) Display name of those managers name whose salary is more than average salary of Company? 290) List employee names and hiredates by adding one year to the date. 291) List the employee names who have minimum and meximum experience. 292)Display those managers name whose salary is more than average salary of his employees? 293) Display employee name,sal,comm and netpay far those emplayees whose netpay is greater than or equal to any other employee salary of the company? 294) Display those employees whose salary is less than his manager but more than Naresh i Technologies, Opp. Satvam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 147 - Oracle 11g Material salary of other managers? 295) Find the last 5(least) employees of company? 296) Find out the number of employees whose salary is greater than their managers salary? 297) Display the manager who are not working under president but they are working under any other manager? 298) Delete those records from emp table whose deptno not available in dept table? 299) Display those enames whose salary is out of grade available in salgrade table? 300) Display employee name,sal,comm and whose netpay Is greaterthan any othere in the company? 301) Display name of those employees who are going to retire 31-Dec-99 if maximum job period is 30 years? 302) Display those employees whose salary is odd value? 303) Display those employees whose salary contains atleast 3 digits? 304) Display those employees who joined in the company in the month of Dec? 305) Display the Cartesian product of EMP and DEPT tables. 306) Display those employees whose name contains A? 307) Display those employees whose deptno is available in salary? 308) Display those employees whose first 2 characters from hiredate - last 2 characters sal? 309) Count how many duplicate records are there in the EMP table, 310) List ROWIDs from EMP table. 311) Create a view with different job and sum of salary from EMP table. Is manipulation possible in the view? 312)Create a view with EMPNO,ENAME,JOB and SAL. Is manipulation possible in the view directly? 313) Display those employeess whose 10% of salary is equal to the year joining? 314) Display those employees who are working in sales or research? 315) Display those employees who joined the company before 15th of the month? 316) Create a view with DNAME,ENAME,SAL .Is it possible to manipulate the view directly? 317) Get all department numbers, which are present in DEPT table but not in EMP table. 318) List all employees who are hired in last week of a month. 319) Delete those employee who joined the company 10 years back from today? 320) who are the top three earners of the company? 321) In the employee table if the job is ‘CLERK’ change it to ‘WORKER’ if job is ‘MANAGER’ change it to ‘BOSS’, otherwise change it to ‘EMPLOYEE’. 322) Find all employees who have the job equal to that of SMITH. 323) Create a sequence and change the employees’ number of EMP table into serial numbers. 324) Display the experience of employees in years, months, weeks and days. 325) Write a query to display a character in Pyramid format, 326) Count th number of employees who are working as managers (Using set opetrator)? 327) Display the name of employees who joined the company on the same date? 328) Display the name of the dept those employees who joined the company on the same date? 329) display those employees whose grade is equal to any number of sal but not equal to first number of sal? 330) Count the no of employees working as manager using set operation? 331) Display the name of employees wha joined the company on the same date? 332) Display the manager who is having maximum number of employees working under him? : 333) What is name of Default Index(in case of Primary key, Unique ). 334) List out the employee name and salary increased by 15% and express as whole number of Dollars? 335) Produce the output of the emp table "Employee_and Job" for ename and job ? Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 23746666, 9000994008 - 148 - ose an atten Oracle 11g Material Se 336) List of employees with hiredate in the format of ‘June 4 1988"? 337) Print list of employees displaying ‘Just salary’ If more than 1500 if exactly 1500. display ‘on taget’ if less than 1500 display below 1500? 338) Which query to calculate the length of time any employee has been with the company. 339) Given a string of the format ‘an/nn’ . Verify that the first and last 2 characters are numbers .And that the middle character is '/' Print the expressions 'Yes' IF valid NO’ of not valid . Use the following values to test your solution'12/54',01/1a,'99/98"2 340) Employes hire on OR Before 15th of any month are paid on the last friday of that month those hired after 15th are paid the last friday of th following month .print a list of employees .their hiredate and first pay date sort those who se salary contains first digit of their deptno? 341) Print the details of employees who are subordinates to BLAKE? 342) Display those who working as manager using co related sub query. 343) Write an SQL statement to refresh the salaries, according to experience of the ‘employees. For one year of experience, the salary will be 1000. 344) Write an SQL statement to accept date of birth and display the age in years, months, weeks, days, hours, minutes and seconds separately . 345) Write an SQL statement to insert a record into DEPT table. If the user provides a value for LOC It should be inserted; Otherwise ‘HYDERABAD’ should be inserted a5 default. 346) Find aut how many managers are there with out listing them 347) .Use the variable in a statement which finds all employees who can earn 30000 a year or more(i.c using &). . 348) In which year did most people join the company. Display the year and number of employees. 349) create a copy of emp table. 350) Display those employee whose joining of month and grade is equal, Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, « NARESHO techwmolozies Rs =Gole PL/SQL Course Material By Mr. Krishna Reddy Opp. Satyam Theatre, Ameerpet, Hyd. Office: 040- 23746666 Mobile: 9000994007/8 PL/SQL eee By Mr. Krishna Reddy PL/SQL is a procedural extension to a non-procedural language SQL. PL/SQL is one of the utility of Oracle dbserver and it is not a tool like SQL*plus. Itis a block-structured language. PL/SQL block is a logical collection of procedural as well as non-procedural statements. It is a data processing language, but SQL is a powerful Data Manipulation Language. PL/SQL is having all the features of procedural language as well as all non- procedural features(because of SQL support). PL/SQL can used for both Server-Side and Client-Side Development. PL/SQL block is a logical collection of procedural as well as non-procedural statements, Types of valid statements of PL/SQL block * SQL statements(non procedural statements) + Non-SQL statements(procedural statements) BI ructure a The basic units that make up a PL/SQL program are logical blocks. The block in PL/SQL can be nested with one another, A block groups related declarations and statements into one single unit. The basic parts of a PL/SQL block are © Declarative part(optional) o Executable part(Mandatory) 2 Exception Handling(optional) Declarative part + Itis used to define user defined types, variables which can be used, in the executable part for further manipulations. Executable Part * All procedural statements are included between the BEGIN and END statement. + it must have one executable statement. Exception Handling Part * Error that occur during execution are dealt in the exception handling part otes: + APL/SQL program is a logical block, which contain any number of nested sub blocks. * Block can be nested in the executable and exception handling parts of a PL/SQL block, of a sub program. A PL/SQL is marked with either a "DECLARE" or “BEGIN” keyword and ends with the keyword “END” Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL + Only BEGIN and END keywords are mandatory. + Asemicolon(;) has to be placed after the “END” keyword. Block syntax ‘SQL>DECLARE [Variable declarations; Cursor declaration; User_defined exception; ] BEGIN PL/SQL statement EXCEPTION Action to perform when errors occurs. END; By Mr. Krishna Reddy * Only executable section is required. * The declarative and exception handling section are optional. + We can define local sub programs in the declarative part of any block. * However , we can call local subprograms only from the block in which they are define. A simple PL/SOL Block SQL> BEGIN NULL; END; NULL block. SQL> BEGIN RETURN; END; BLOCK with RETURN clause. SQL>DECLARE BEGIN NULL; END; SQL>DECLARE BEGIN NULL; EXCEPTION WHEN OTHERS THEN NULL; END; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 32: By Mr. Krishna Reddy tatements and PI blocks fr Lt Place a semicolon(;) at the end of the SQL statement or PL/SQL control statement. Use a Forward slash(/) to run the Anonymous PL/SQL block in SQL*plus buffer. Place a period(.) to close a SQL*Plus Buffer with out running the PL/SQL program. A PL/SQL block is treated as one continuous statement in the SQL*plus buffer. Semicolon within the PL/SQL block does not clases or Runs the SQL Buffer. In PL/SQL an Error is called as an Exception. Sections keywords “DECLARE”,"BEGIN", and “EXCEPTION” should not contain A semicolon. “END” and all other PL/SQL statements should be applied with a semicolon at the End. Declaration part of PL/SQL block is optional ,but the body of the PL/SQL is must.(The area between begin and end is called as body of the PI/SQL block. Every PL/SQL black is terminated by END statement followed by a semicolon. PL/SQL is not a data formatting language. ‘Types of blocks in PL/SQL * A PL/SQL program can be written in various types of blocks, they are Anonymous block * The block having no name. + They are declared at the point in an application, where they are to be executed and are passed to PL/SQL engine for execution at runtime. + It cannot be called. * There are used in 02K form. SQL>DECLARE BEGIN NULL; EXCEPTION WHEN OTHERS THEN NULL; EN Named Block * The block having name and they have all the features as specified for the anonymous blocks. + Named blocks help in associating with the scope and resolution of variables in different blocks. + They give the specifications of the named spaces as provided in high level OO0Ps languages like C++ and JAVA. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy + Named blocks are conyeniences for variable management. SQL><> DECLARE BEGIN NULL; EXCEPTION WHEN OTHERS THEN NULL; END FirstBlock; + Named blocks make the PL/SQL blocks more clear and readable. «Named blocks increase the clarity of programming when we attempt the nesting process, and control structures. Sub- med blocks These are named PL/SQL blocks that can take parameters and can be invoked with in the other anonymous or sub-programmed PL/SQL blocks. These blocks are either is declared as procedures or functions. A procedure block is used for performing an action, and a functional block is used for performing calculation. These sub-programs provides modularity and reusability. Comments in PL/SQL + PL/SQL compiler ignores comments. + Comments promote readability and aids understing. + PL/SQL supports two types comments © Single line comments(--) o 7*Multi Line Comments */ riables i L Use of Variables Variables can be used for: Temporary storage of data * Data can be temporarily stared in one of more variables for use when validating data Input for Processing the Data in the Data flow process. Manipulation of stored values Information is transmitted between PL/SQL and database with variables, Variables help in the data manipulation of stored values. Variables can be used for calculations and others data manipulations without accessing the database each and every time, Hence they help in reducing the I/O Cycles. ‘* Once declared can be used repeatedly by even in other blocks. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy * Variables can be declared based on the declarations of the definitions of database columns. * Provides Data Independence, reduces maintenance costs and allows programs to adapt the changes as the Database changes. Handling Variables in PL/SOL + Declare and initialize variables in the declaration section. + Declarations allocate storage space for a value according to its defined size, Declarations can be assigned with an Initial value and can be imposed with a NOT NULL constraint or DEFAULT option. We reassign new values to variables in the executable section. Pass values into PL/SQL blocks through parameters. There are Three parameter modes, They are IN(The default),OUT and IN our. View results from a PL/SQL through output of variables. Reference variables can be used for Input or Output in SQL data manipulation statements, Types of Variables * PL/SQL variables - Scalar Composite Reference LOB (large objects) Scalar Data Types: * They holds a single value. + Main data types are those that correspond to column types in oracle server tables. + Supports Boolean variables. Composite Data types: + A variable of a composite type contains one or more scalar variables. + Composite data types are similar to structures in ‘C’ language. * They help in keeping all the related data items together as one collection. Re en es: * They hold values, acting as pointers, which designate other program items. + They are very essential when manipulating collection of data items in sub programs, LOB Data types: Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 They holds values called locations, specifying the location of large objects that are stored out of line in the PL/SQL program. Operators in PL/SOL ‘* Logical ND,OR,NOT * Arithmetic i) * Concatenation : || + Comparison 1=,<,>,<=,>5 * SQL*Plus SNULL,LIKE,BETWEEN, IN Assignii lues to a vari In PL/SQL a variable can be assigned in three ways By using assignment operator(:=) By selecting or fetching database values(INTO). By passing it as IN or OUT or INOUT parameter to a subprogram. Declaring PL/SOL Variables Syntax Identifier name [CONSTANT] datatype [NOT NULL][:=DEFAULT] Expr]; Identifier name ‘* Specifies the name of the relevant variable for that block. Constant + Constant the variable such that its value cannot change during the program process. + Constants must be initialized else raise an exception. Datatype * Itjis a scalar, composite, reference of LOB data type as applicable to the required situation. NOTNULL * Constraints a variable such that it must contain a value and raises if NULL is identified. «NOT NULL variables should be initialized else raise an exception. DEFAUL * Sets the default value for the value in the PL/SQL program if not attended. Expr * It is any PL/SQL expression that can bea literal, another variable or an expression involving operations and functions for initialization. iustration DECLARE Vno number(4):=7788; ‘name varchar2(20) not null:="SCOTT’; --must not hold null value through out program Doj date default sysdate; Fiag boolean: = true; By Mr. Krishna Reddy --for boolean variable accept only TRUE or FALSE value and --value should not be in single code pcode constant number(6: --cannot be used as an assignment target. Debugging statement The debugging statement of PL/SQL is DBMS_OUTPUT.PUT_LINE(); For producing outputs on the video device we need the assistance of DBMS_OUTPUT package. The package enabled to display output from PL/SQL blocks and sub programs. The procedure PUT_LINE() outputs information to a buffer in the SGA. This procedures is used to identify the error during runtime of the PL/SQL block. This procedure requires a single parameter of any of the data types varchar2 or number or date. To see the output of PUT_LINE() on the console of the client side enter the following SQL plus command on the SQL prompt. Syntax DBMS_OUTPUT.PUT_LINE(‘Message’||variablename); The DBMS_OUTPUT packages is owned by the oracle user SYS. The size of the buffer can be set between 2000 to 10,00,000 bytes. The specification to set buffers are o SET SERVEROUTPUT ON o SET SERVEROUTPUT ON SIZE 5000 o SET SERVEROUTPUT OFF SQL>BEGIN DBMS_OUTPUT.ENABLE; DBM$_OUTPUT.PUT_LINE(‘Frist program in PL/SQL’); DBMS _OUTPUT.PUT_LINE(Mustraind by’); DBMS_OUTPUT.PUT_LINE(""Krishna reddy ""); END; DBMS_OUTPUT.ENABLE; Once declare will make the SERVEROUTPUT process to get activated. SQL> DECLARE V_FirstNum NUMBER: =&fno; V_SecondNum NUMBER:=&sno; V_tol NUMBER; BEGIN V_tol:=v_FirstNum+V_SecondNum; OBMS_QUTPUT.PUT_LINE(‘The sum of Frist and Second num is '||v_tol); END; ee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy SQL> BEGIN . DBMS_OUTPUT.PUT_LINE(‘The sum of Frist and Second num is "| |(&FirstNum+&SecondNum)); ‘+ The scope of an identifier is that region of a program unit (block, subprogram, or package) from which you can reference the identifier. + Once the scope of the variable is fost it means that the life of the variable no more. + All variables loose their scope as soon as the PL/SQL block ends or terminates. * Oracle automatically release the space upon that variable once its scope is, closed. Concepts of scoping + With in the same scope, all identifiers must be unique. + Even when the data types are differing, variables and parameters cannot share the same name. Nested Blocks and variables * PL/SQL blocks can be nested wherever an executable statement is allowed. + Anested block becomes a statement. + An exception section can contain nested blocks. cope and visibility diagram ex: DECLARE x NUMBER; BEGIN DECLARE y NUMBER; SQL>DECLARE m NUMBER: =250; BEGIN DBM$_OUTPUT.PUT_LINE(‘The value of Outer m:'||m); DECLARE m NUMBER :=550; BEGIN DBMS_OUTPUT.PUT_LINE(‘The value of Outer m:'||m); ee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabail, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy END; 5 DBMS_OUTPUT.PUT_LINE(‘The value of Outer m:'||m); END; SQL> DECLARE m NUMBER:=100; BEGIN m:=200; DBMS_OUTPUT.PUT_LINE(‘The value of Outer m:'||m); DECLARE 8 NUMBER :=300; v_tol NUMBER; m+n; DBMS_OUTPUT.PUT_LINE('The sum of m,n is :'[{v_tol); ENI DBMS_OUTPUT.PUT_LINE(‘The value of Outer m:'||m); END; Labeled Block Represent blocks with a label associated to them. er k to Label we need to place a label before the DECLARE keyword. The label can also can use appear after the END keyword and it is optional. = The advantage of of labeled block is that labeled blocks allow you to access those variables that would nat be visible when using anonymous block. SQL> <>DECLARE m NUMBER:=100; BEGIN m:=200; DBMS_OUTPUT.PUT_LINE(‘The value of Outer m:'||m); < >DECLARE n NUMBER :=300; v_tol NUMBER; m number:=400; BEGIN block1.m:=500; 00; v_tol:sblocki.m-+n; DBMS_OUTPUT.PUT_LINE(‘The sum of block1 m,n is :'||v_tol); OBMS_OUTPUT.PUT_LINE(‘The value of Inner block is:"}]m); END block2; DBM$_OUTPUT.PUT_LINE(‘The value of Outer m:'{|m); Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy END block1; >CREATE TABLE kcb_acc_tab( accno VARCHAR2(20) CONSTRAINT pk_accno PRIMARY KEY, name VARCHAR2(20) CONSTRAINT nn_name NOT NULL, acctype CHAR CONSTRAINT chk_atype CHECK (acctype IN('C doo timestamp DEFAULT sysdate, bal NUMBER(7,2) CONSTRAINT nn_BAL NOT NULL di Writing Control Structures By Mr. Krishna Reddy PL/SQL can also process data using flow of control statements. + PL/SQL helps us manipulates and process oracle data using control statements. + The fiow of control statements can be classified under the following categories: © Conditional contro! © Iterative control © Sequential control The statement structures provided by PL/SQL for this purpose are + IF-THEN-ELSE END IF ELSIF CASE END CASE Loop FOR-LOOP WHILE-LOOP END LOOP EXIT-WHEN and GoTo * By integration all the above statements in a proper way a PL/SQL programmer can handle any real time situation. Conditional Contro} ‘* Sequence of statement can be executed based on a certain condition using the IF statement. + There are three forms of IF statements o IF-THEN-END IF © IF-THEN-ELSE-END IF o IF-THEN-ELSIF-END IF General Syntax IF condition THEN sequences of statements; END IF; Points to Ponder + IF...THEN is a reserved word and marks the beginning of the “IF” statement. + The “END IF” is a reserved phrase that indicates the end of the “IF...THEN” construct. + When “IF...THEN” is executed, A condition is evaluated to either “TRUE” or “FALSE. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy + Conditions are compared by using either the comparison operators or SQL*plus operators. * One “IF” keyword can manage any number of conditions at a point of time using the LOGICAL CONNECTIVITIES like “AND","OR". + Even though the multiple conditions need not be constrained by using brackets, It is better to control their precedence using the proper implementations of brackets to avoid ambiguity. + Every “IF” that is implemented needs compulsorily a “TRUE” state evaluation for its successful execution, But an evaluation state is not compulsory when the condition is "FALSE”. + The sequence of statements is executed only if the condition evaluates to true. + If itis false or null, then the control passes to the statement after ‘END IF’. SqI>BEGIN IF ascit(‘A’)=65 THEN DBMS_OUTPUT.PUT_LINE(This is true’); END IF; END; DECLARE v_Firstnum NUMBER: v_Secondnum NUMBER: v_Temp NUMBER; BEGIN DBMS_OUTPUT.PUT_LINE(‘Original v_Firstnum='{|v_Firstnum); DBMS_OUTPUT.PUT_LINE(‘Original v_Secondnum="||v_Secondnum); IF v_Firstnum>v_Secondnum THEN v_Temp:=v_Firstnum; v_Firstnum:=v_Secondnu v_Secondnum:=v_Temp; END IF; DBMS_OUTPUT.PUT_LINE(‘Swapped v_Firstnum DBMS_OUTPUT.PUT_LINE(‘Swapped v_Firstnum ‘|lv_Firstnum); Ilv_Secondnum); END; ..: THEN... ELSE...END IF sta’ IF... THEN...ELSE statement enable us to specify two different groups of statements for execution. * One group is evaluated when the condition evaluates to "TRUE”, then next group is evaluated when the condition evaluates to “FALSE” IF condition THEN sequences of statements; ELSE sequences of statements; END IF; Sql>OECLARE v_Firstnum NUMBER: =&Fnum; v_Secondnum NUMBER:=&Snum; BEGIN IF v_FirstnumDECLARE v_Num NUMBER: =&Enternumber; BEGIN IF MOD(v_Num,2)=0 THEN DBMS_OUTPUT.PUT_LINE(v_Num||‘ is an Even Number.’); ELSE DBMS_OUTPUT.PUT_LINE(v_Num||’ is an Odd Number."); END IF; END SQL> DECLARE v_Number1 NUMBER: = &Number1; v_Number2 NUMBER:= &Number2; BGEIN IF v_Numberl>v_Number2 THEN DBMS_OUTPUT.PUT_LINE(‘The Greatest Number is: '}jv_Number1); ELSE IF v_Number2>v_Numberl THEN DBMS_OUTPUT.PUT_LINE(‘The Greatest Number is: ‘||v_Number2); ELSE DBMS_OUTPUT.PUT_LINE(‘The Number are equal "||v_Numberi}{' and 'YWv_Number2); END IF; END IF; END; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 In simple “IF” when a condition is evaluated to NULL, then the statements in “TRUE" state will not be executed, instead the control will be passed to the first executable statement after the “END IF”. + In IF...THEN...ELSE construct the FALSE block is executed whenever the condition evaluates to NULL. + Hence when ever a conditional process is executed it is better to cross verify the NULL status of any variable or value before execution. SQL> DECLARE v_Firstnum NUMBER: =&Fnum; v_Secondnum NUMBER: =&Snum; BEGIN IF v_Firstnum=v_Secondnum THEN DBMS_OUTPUT.PUT_LINE(‘Given numbers are equal’); END IF; DBMS_OUTPUT.PUT_LINE('Did you watch the NULL effect.'); END; Note:Supply NULL at runtime to check the affect of NULL DECLARE v_num NUMBER: =&Enternumber; BEGIN IF MOD(v_num,2)=0 THEN DBMS_OUTPUT.PUT_LINE(V_num]||" is an Even number.'); ELSE DBMS_OUTPUT.PUT_LINE(v_num||' is an Odd number. ENO TF; DBMS_OUTPUT.PUT_LINE('Did you watch the Difference. The “IF” statements can be nested into one another as per requirements. * Nested “IF” is a situation in which an “IF" follows another “IF” immediately for every “TRUE” state of an “IF” condition. * Each “IF” is considered as an individual block of “IF” and needs proper nesting. + Fach “IF” block that is opened needs a proper close with “END IF”. Else PL/SQL raises exceptions. + Nested “IF” situations have to be planned when we have a series of conditions fall sequentially. By Mr. Krishna Reddy IF condition THEN F condition THEN IF condition THEN Statement1; ELSE Statement2; END IF; ELSE Statement3; END IF; ELSE Statement4; END IF; SQL>DECLARE v_year NUMBER: =&year; BEGIN IF mod(v_year,4)=0 THEN IF mod(v_year,100)<>0 THEN DBMS_OUTPUT.PUT_LINE(v_year||' is a.leap year’); ELSE IF mod(v_year,400)=0 THEN DBMS_OUTPUT.PUT_LINE(v_year||' is a leap year"); ELSE DBMS_OUTPUT.PUT_LINE(v_year||' is a not a leap year’); END IF; END IF; ELSE DBMS_OUTPUT.PUT_LINE(v_year||' is a not leap year’); END IF; END; Branching with Logical connectivity’s + In this situation one “IF” is associated with a collection of conditions using either logical either logical “AND” or logical “OR” operator, Syntax1. IF condition AND condition2 THEN PL/SQL By Mr. Krishna Reddy Statementt; Statement2; ELSE Statement; Statement2} END IF; Syntax2 IF condition OR condition2 THEN Statement; Statement2; ELSE Statement; Statement2; END IF; ‘Syntax3 IF condition1 AND condition2 OR Condition3 xTHEN Statement; ‘Statement2; ELSE statement; Statement2; ENO IF; ELSIF statements ‘Syntax: IF Condition1 THEN Statements; ESLIF Condition2 THEN Statement2; ELSIF Condition3 THEN Statement3; ELSE Statement n; END IF; SQL>DECLARE v_TotalEmps NUMBER; BEGIN SELECT COUNT(*) INTO v_TotalEmps FROM emp; IF v_TotalEmps=0 THEN INSERT INTO temp_table values(‘There are no emps'); ELSIF v_TotalEmps <5 THEN By Mr. Krishna Reddy INSERT INTO temp_table values("There are few emps joined’); ELSIF v_TotalEmps <10 THEN INSERT INTO temp_table values("There are little more emps joined’); ELSE INSERT INTO temp_table values('There are many emps joined’); END IF; END; CASE Expressions + It is similar to a switch statement in C. + When a particular search condition evaluates to TRUE, the group of statements associated with this condition are executed. + We can evaluate conditions using the normal conditional operators or SQL*Plus operators. Case expression Syntax CASE test_var WHEN valuet THEN Sequence_of_statements1; WHEN value2 THEN Sequence_of_statements2; WHEN valuen THEN Sequence_of_statementsn; [ELSE else_sequence;] END CASE; The reserved word “CASE” marks the beginning of the CASE statement. The selector is a value that determines, which “WHEN” clause should be executed. Each when clause contains as expression and or more executable statements associated with it. The “ELSE" clause is optional. Each “CASE” statement is marked with “END CASE”. Where test_var is the variable or expression to be tested, value] through valuen are the comparison values, If none of the values are equal, then else_sequence will be executed. SQL>DECLARE v_Dname varchar2(20); v_Deptno number; BEGIN SELECT deptno into v_Deptno FROM emp Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL WHERE empno=&eno; CASE v_Deptno WHEN 10 THEN v_Dname:="'ACCOUNTING'; WHEN 20 THEN v_Dname:='RESEARCH'; WHEN 30 THEN v_Dname:='SALES'; WHEN 40 THEN ‘OPERATIONS’; ‘UNKNOW'; DBMS_OUTPUT.PUT_LINE('Emp dept name is:'||v_Dname); END; Labeled CASE statements * ACASE statement can optionally be labeled, like a PL/SQL block. + Ifa CASE statement is labeled, then the label can also appear after the END CASE clause. SQL>DECLARE v_TestVar NUMBER: =10; BEGIN <> CASE v_TestVar WHEN 10 THEN DBMS_OUTPUT.PUT_LINE('ACCOUNTING'); WHEN 20 THEN DBMS_OUTPUT.PUT_LINE('RESEARCH’); WHEN 30 THEN DBMS_OUTPUT.PUT_LINE(‘SALES'); WHEN 40 THEN DBMS_OUTPUT.PUT_LINE(‘OPERATIONS'); END CASE Mycase; END; SQL>Create or replace procedure display(s varchar2) Is Begin Dbms_output.put_line(s); End; Loops( Iterations in PL/SQL) » Loops repeat a statement or sequence of statements multiple times. + There are three loop types: Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL By Mr. Krishna Reddy Basic loop or Simple Loop FOR loop WHILE loop Simple Loop + The most basic kind of loop, simple loops, have the syntax Loop Sequence_of_statemnets; END LOOP; The sequence_of_statements will be executed between the keywords “LOOP” and “END LOOP”, To keep the loop in finite state the “EXIT” statement is used. We can add one with the EXIT statement which has the following syntax: EXIT [WHEN condition]; EXIT Statement “Exit” Statement is used to terminate a LOOP. Once the loop is terminated, the control passes to the next statement after the “END LOOP”, The "EXIT" statement should always be placed inside the Loop only. “EXIT” can be associate with a "WHEN" clause to allow conditional termination of the loop. ‘The “EXIT” condition can be at the top of the loop or at the end of the loop as per logical convenience. Depending upon the circumstances we can make use of this LOOP as Pre - Tested loop or Post-Tested loop construct, The loop terminates its process when the conditional state is "TRUE". The statement EXIT WHEN condition is equivalent to IF condition THEN EXIT; END IF; SQL> DECLARE v_counter Number: BEGIN LOOP INSERT INTO temp_table VALUES(v_Counter,'Loop index’); v_Counter:=v_Counter+1; EXIT WHEN v_Counter>50; END LOOP; END; SQL>DECLARE a Number:=100; BEGIN Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL By Mr. Krishna Reddy Loop IF a=250 THEN EXIT; END IF; a+25; display(a); END LOOP; END; Nested Loops: + Itis a situation where one loop is embedded into the other. + The outer loop and the inner loop get associated with one another and execute simultaneously. The overall loop terminates is dictated by the outer loop's “EXIT WHEN “ condition or “EXIT” condition. In nested loop’s the outer loops condition evaluated as TRUE, always makes the inner (aap to resume its process and the inner loop’s termination actually makes the outer loop to update its process. SQL> DECLARE v_num NUMBER:=1; BEGIN LOOP EXIT WHEN v_num>10; Loop EXIT WHEN v_num>5; display(‘inner laop:'||v_num); v_nui /_num+1; END LOOP; display(‘Outer loop:'}|v_num); v_num:=v_num+1; END LOOP; END; Nested I nd labels: «Loops can be nested to multiple levels. + All the loops can be nested into one another. + Loops can be labeled as per the requirements. * Label loops by placing the label before the word loop within the label delimiters. When the loop is labeled, the label name can be optionally included after the END LOOP statement for clarity. DECLARE Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy v_num NUMBER: BEGIN < > LOOP < >LOOP EXIT WHEN v_num>5; display(‘Inner loop:'I|v_num); v_num:=v_num+1; END LOOP innerloop; display(‘Outer loop:"}|v_num); v_num:=v_num+1; EXIT WHEN v_num>10; END LOOP outerloop; END; GOTOs and Labels * The “GOTO” statements allows us to branch to a label unconditionally. © The label, which is enclased within double angle brackets must precede an executable SQL statement or a PL/SQL block. When executed, the GOTO statements transfers control to the labeled statement or block. Syntax GOTO LabelName; Scenario SQL>CREATE TABLE product_master (product_no varchar2(6) constraint pk_product_pk primary key, Description varchar2(25), unit_measure varchar2(10), Qty_on_hand number(8), reorder_lvl number(8), cost_price number(10,2), selling_price number(8,2)); SQL> DECLARE v_Qtyhand product_master.qty_on_hand%type; v_Relevel product_master.reorder_Ivi%type; v_product_no product_master.product_no%type; BEGIN v_product_no:='&prodno'; SELECT qty_on_hand,reorder_lvl INTO v_Qtyhand,v_Relevel FROM praduct_master WHERE product_no=v_product_no; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL By Mr. Krishna Reddy IF v_Qtyhand > UPDATE product_master SET aty_on_hand=qty_on_hand+reorder_Ivl WHERE product_no=v_product_no; RETURN; <> display(‘There are enogh product’); RETURN; END; Note: Hence to keeps proper meaning within the sequence “RETURN” should be used.. SQL>DECLARE v_Counter NUMBER: BEGIN LOOP INSERT INTO temp_table VALUES(v_Counter,'Loop Count'); v_Countec:=v_Counter+1; IF v_Counter>=50 THEN GOTO EndOfLoop; END IF; END Loop; <> INSERT INTO temp_table(Ind) VALUES(‘Done!'); EN Restrictions on GOTO It is illegal to branch into an inner block, !oop , or IF statement. “GOTO” cannot navigate from the EXCEPTION selection to any other section of the PL/SQL block. “GOTO ~ cannot reference a LABLE in a nested block. “GOTO” cannot be executed outside an “IF" cause to LABLE inside “IF” clause. It is better to have a limited usage of "GOTO" in programming block. “GOTO” cannot navigate fram the EXCEPTION selection to any other section of the PL/SQL block. — By Mr. Krishna Reddy SQL>DECLARE n NUMBER: =10; BEGIN GOTO |_innerblock; IF n>20 THEN <> INSERT INTO dept VALUES(50,'SW'; HYD"); END IF; END; SQL> BEGIN GOTO |_innerblock; BEGIN <> INSERT INTO dept VALUES(S0,'SW','HYD'); END; END; WHILE Loops + The WHILE LOOP statement includes a condition associates with a sequence of statement. +. If the condition evaluates to true, then the sequence of statements will be executed, and again control resumes at the beginning of the loop. + IF the condition evaluates to false or NULL, then the loop is bypassed and the control passes to the next statement. ‘Syntax WHILE condition LOOP statementi; Condition is statement2; evaluated at the beginning of wae each iteration. END Loop; SQL>DECLARE n NUMBER(3):=1; v VARCHAR2(100); BEGIN WHILE n<=10 Loop visvil "In; ni=n+1; END Loop; PL/SOL display(v); “END; SQL>DECLARE n NUMBER(S) s NUMBER(5) r NUMBER(2) BEGIN WHILE nt=0 100P mod(n,10); =str; runc(n/10); END LOOP; display(‘The sum of digit of given number is'||s); END; FOR LOOP it has the same general structure as the basic loop. + “FOR LOOP” contains a contro} statement at the front of the [OOP keyword, to determine the number of iterations that PL/SQL performs. Syntax: FOR loop_counter IN [REVERSE] Lowerbound..Upperbound Loop Statement1; Statement2; END:'LOOP Counter: «It is an implicitly declared INTEGER whose value is automatically increased or decreased by 1 on each iteration of the LOOP until the upper bound or lower bound is reached. Reverse: It is a keyword, and causes the counter to decrement with each iteration from the upper bound to the lower bound. The loop_counter need not be declared, as it is implicitly declared as an integer. The bounds of the loop are evaluated once. This determines the total number of iterations that loop_counter will take on the values ranging from low_bound to high_bound, incrementing by 1 each time until the loop is complete. DECLARE v_FactNum NUMBER:=8No; By Mr. Krishna Reddy v_Factorial NUMBER: BEGIN FOR v_Counter IN REVERSE 1..v_FactNum Loop V_Factorial:=v_Factorial*v_Counter; END LOOP; DBMS_OUTPUT.PUT_LINE('The Factorial of '||v_FactNum||" is 2'llv_Factorial); END; SQL>DECLARE J NUMBER(2):=83; v VARCHAR2( 100); k NUMBER(3); BEGIN FOR iin 1..10 loop ‘Sti; VASES" end loop; display(v); END; Nested FOR loops SQL>DECLARE n NUMBER: =&no; v VARCHAR2(1.00);, BEGIN FOR IN 1..n LOOP FOR K IN 1..1 Loop display(v); v:=null; END LOOP; END; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, PI + 040-23746666, 9000994007 26: CURSOR MANAGEMENT By Mr. Krishna Reddy a * In order to process a SQL statements, Oracle will allocate an area of memory know as the context area. PL/SQL uses this context area to store and to execute the SQL statements. * The information(rows) retrieved from database table, which is available in context area, is known ‘Active Set’. * A Cursor is a pointer, which works on active set i.e., which points one row at ‘a time in the context area. A cursor is used to process multiple rows using PL/SQL. ‘Types of Cursors + There are two types of cursors 0 Implicit cursors o Explicit cursors Implicit cursors * It is a CURSOR that is automatically declared by Oracle every time an SQL statement is executed. + These are created or erased automatically, + These are identified by SQL% + Whenever you issue a SQL statement, the Oracle server opens an area of memory in which the command is parsed and executed. This area is called a cursor. + When the executable part of a block issues a SQL statement, PL/SQL creates an implicit cursor, which PL/SQL manages automatically. + ACURSOR is automatically associated with every DML:statement. + AIL UPDATE and DELETE statements have cursors that identify the set of rows that will be affected by the operations. + During processing of an IMPLICIT cursor, oracie automatically performs the erations like “OPEN","FETCH", and “CLOSE” of the context area. licit Test + Explicit cursors are explicitly declared by the programmer. + This cursor is declared within the PL/SQL block, and allows sequential process of each row of the returned data from database. Exj Cursor Attributes * There are four attributes available in PL/SQL that can be applied to cursor. * Cursor attributes are appended to a cursor name in a PL/SQL block, similar to %TYPE and %ROWTYPE. * The attributes are ° %FOUND 0° %NOTFOUND © %ISOPEN © %ROWCOUNT FOUND Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL By Mr. Krishna Reddy Boolean attribute that evaluates to TRUE If the most recent SQL statement affects one or more rows. Y%eNOTFOUND * Boolean attribute that evaluates to TRUE if the most recent SQL statement does not affect any rows. %ISOPEN * Boolean attribute that evaluates to TRUE if the cursor is open else evaluates to FALSE, YeROWCOUNT Number of rows affected by the most recent SQL statement (an integer value). SQL>var rows_deleted varchar2(20) SQL>DECLARE v_Empno emp.empno%TYPE := 7788; BEGIN DELETE FROM emp WHERE empno = v_Empno; :rows_deleted:= (SQLY%ROWCOUNT ||" row deleted. END; SQL> DECLARE v_Job Emp.Job%TYPE: ='8Job'; BEGIN UPDATE emp SET sal=sal+1000 WHERE job=v_Job; DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT| |'Rows were Updated.'); IF SQL%NOTFOUND THEN DBMS_OUTPUT.PUT_LINE(‘Data Not Found So, No updation.'); END IF; END; Implicit FOR Loops SQL>DECLARE FOR v_Empdata IN(SELECT ename,job,sal,comm FROM emp WHERE deptno=30) Loop INSERT INTO bonus VALUES(v_Empdata,ename,v_Ermpdata.job,v_Empdata.sal, v_Empdata.comm); END LOOP; END; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy + An EXPLICT CURSOR is generated using a name with assaciation of select statement in the DECLARE section of the PL/SQL block. Advantages + Explicit cursor provide more programmatic control for programmers. + Explicit cursor are more efficient in implementation, hence easy to trap errors. How cursor will work The life cycle of the explicit cursor goes through four stages. DECALRE OPEN FETCH CLOSE DECLARE: ‘* The CURSOR is declared in the declarative block and is provided with a name and a SELECT statement. Syntax:~ CURSOR include most of the usual clauses, except INTO clause.(if use It there is no use). + The cursor name can be any valid identifier. + Any SELECT statements are legal, including joins and statements.with the SET OPERATORS. stration >declare vsal nhumber:=2000; cursor c1 is select sal into vsal from emp where empno=7902; begin display(‘The vsal val is '||vsal); end; Opening a Curso: ‘Syntax: OPEN cursor_name; By Mr. Krishna Reddy The opening of cursor executes the query and retrieves the information from the database and dumps it into the context area to foam active set. Cursor can be opened only in the EXECUTION OR EXCEPTION section of the PL/SQL block. The active set pointer is set to the first row. + Once a cursor has been opened, it cannot be reopened unless it is first closed. Eetching from a Cursor * Fetch the record from CONTEXT AREA into cursor variable. + This fetches 1 row at a time into the cursor variable from the active set. + The INTO clause for the query is part of the FETCH statement. The FETCH statement has two forms: Syntax: 1) FETCH cursor_name INTO list_of_variables; 2) FETCH cursor_name INTO PL/SQL_record; + The list_of_variable is a comma-separated list of previously declared PL/SQL variable, and PLYSQL_record is a previously declared PL/SQL record. Illustration: FETCH Empcursor INTO v_emprecord; Closing _a Cursor + This tells PL/SQL engine that the program is finished with the cursor, and the resources associated with it can be freed. These resource include the storage used to hold the active set, as well as any temporary space used for determining the active set. + The active set can be re-established several times. ‘Syntax CLOSE ; Cursor Attributes + There are four attributes available in PL/SQL that can be applied to cursors. cursor attributes are appended to a cursor name in PL/SQL block and then used in expressions. The attributes are %Found %NotFound %ISOPEN %Rowcount By Mr. Krishna Reddy The set of rows returned by a multiple-row query is called the Active Set. Private SQL Area Select EMO oes Fu Active set Nom $QL>declare cursor cl is select empno,ename,sal from emp where deptno=20; vempno emp.empno%type; vename emp.ename%type; vsal emp.sal%type; begin open cl; loop fetch c1 into vempno,vename,vsal; exit when ¢1%notfound; if vsal between 0 and 1000 then vsal:=vsal+vsal*0.15; elsif vsal between 1001 and 2000 then vsal:=vsal+vsal*0.25; else vsal:=vsal+vsal*0.35; end if; update emp set sal=vsal where empno=vempno; display(rpad(vename,8)||" "|| vsal); end loop; close cl; end; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL By Mr. Krishna Reddy SQU>declare cursor jc is select empno,ename,job,sal from emp; i emp%rowtype; begin open ic; loop fetch jc into i.empno,i.ename,i.job,i.sal; exit when jc%notfound; if ij LERK' then al+100; ‘SALESMAN then .sal+200; .sal+300; update emp set sal=i.sal where empno=i.empno; display(rpad{i.ename,8)}}' ‘}|rpad(i.job,10)])" ‘Hli.sal); end loop; close jc; end; >declare cursor cc is select empno,ename,comm from emp; i cc%rowtype; begin open cc; loop fetch cc into i; exit when cc%notfound; if i.comm is null then i.comm:=300; elsif i.comm=0 then i.comm:=250; else i.comm end if; update emp set comm where empni empno; display(rpad(i.ename,8)||" '||i-comm); comm+i.comm*0.35; i.comm Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 33: PL/SOL By Mr. Krishna Reddy end loop; close cc; end; SQL>declare cursor cpf is select empno,ename;sal basic,sal*0.45 hra,sal*0.35 da,sal*0.15 pf,deptno from emp where sal>4000; i cpf%rowtype; vgross number; begin open cpf; loop fetch cpf into i; if cpf%found then vgross:=i.basic+i.hra+i.da-i.pf; display(i.empno}|' '||rpad(i.ename,8)|{" '||rpad(i.basi¢,6)||" "I|rpad(i.hra,5)I |" 'I] rpad(i.da,5){|" "IIrpad(i-pf5)|1' ‘Il rpad(vgross,5){[' ‘Ilideptno); else exit; end if; end loop; display(‘No of emps eligible for pf is'||cpf%rowcount); close cpf; end; > insert into utab values(upper(‘&uid"), Translate( upper(‘&password"), "ABCDEFGHIJKLMNOPQRSTUVWXYZ’, 1234567890! @#$%*&*()-=_+;,.") 7 SQL>declare cursor primary_cur is select 'X’ from utab where userid=upper(‘&uid') and password=Translate(upper(‘&password’), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ’, '1234567890!@#$%*8*()-=_+;,."); dummy_var char; aS Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 134i: By Mr. open primary_cur: fetch primary_cur into dummy_var; if primary_cur%found then display(‘The userid and password corr'); else display(‘Unknow userid and password’); end if; close primary_cur; end; Cursor with For loops + PL/SQL provides a simple type of loop, which implicitly handles the cursor processing. Within the loop each record in the Active set is retrieved and used. Each loop iteration advances the cursor pointer by one record in the Active set. The loop works on the range oriented operational logic. The loop is very useful when traveling the entire data in the database table. It is more Dynamic in operation than the Simple toop. Syntax For IN LOOP ; END LOOP; Advantages No need to Declare INDEX variable explicitly. OPEN a cursor . FETCH the rows from cursor. Terminate the loop explicitly. CLOSE the cursor. SQL>declare cursor cpf is select empno,ename,sal basic,sal*0.45 hra,sal*0.35 da,sal¥0.15 pf,deptno from emp where sal>4000; vgross number; cnt number; begin for i in cpf loop vgross: =i.basic+i.hra+i.da-i.pf; ee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 35: By Mr. Krishna Reddy display(iempno||" '||rpad(i.ename,8)||' ‘| |rpad(i.basic,6)||" "| |rpad(i.hra,5)II" "I rpad(i.da,5)|I" "Ilrpad(i-pf,5)||" ‘Ilrpad(vgross,5)||" 'I|i.deptno); cnt:=cpf%rowcount; end loop; display('No of emps eligible for pf is'||cnt); tri ‘sor The cursor defined with parameter is called parametric Cursor. * Cursor parameters can be assigned with default values. + The Mode of cursor parameters can be only “IN” Mode. Syntax CURSOR Cursorname(ParameterName Datatype,...) Is SELECT statement; Illustration SQL> DECLARE CURSOR Empeursor (Pdeptno NUMBER, Pjob VARCHAR2) IS SELECT empno, ename FROM emp WHERE deptno = Pdeptno AND job = Pjob; Methods of Opening a Parametric Cursor 1.0pen Empcursor(30,’SALESMAN’); 2.DECLARE v_empdeptno Emp.deptno%TYPE: =&Givedeptno; v_empjob Emp.job%TYPE:=&Givelob; BEGIN OPEN Empcursor(v_empdeptno,v_empjob); 3. DECLARE CURSOR Empcursor (Pdeptno NUMBER, Pjob VARCHAR2) IS SELECT empno, ename FROM emp WHERE deptno = Pdeptno AND job = Pjob; BEGIN FOR Emprecord IN Empcursor(20,'CLERK’) Loop Import Points + Unless you want to accept default values, each formal parameter in the cursor declaration must have a corresponding actual parameter in the OPEN statement. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 36:3 PL/SQL By Mr. Krishna Reddy + Aparametric cursor can be opened and closed explicitly several times in a PL/SQL Block. + Aparametric cursor returns a different Active Set on each occasion. + The concept is more useful when the same Cursor is Referenced repeatedly. SQL>declare cursor de is select deptno from dept; cursor ec(pdno in dept.deptno%type) is select empno,ename,sal basic,sal*0.45 hra, sal*0,35 da,sal¥0.15 pf,deptno from emp where deptno=pdno; vdno dept.deptno%type; i ec%rowtype; vgross number; begin open de; loop fetch de into vdno; exit when de%notfound; open ec(vdna); loop fetch ec into i; exit when ec%notfound: vgross: =i-basic+i.hra+i.da-i display(iempno||" '||rpad(i. i rpad(i.da,5)(I' 'I|rpad(i.pf,5) II" ‘I rpad(vgross,5)||' ‘[li-deptno); end loop; if ec%rowcount>0 then display! end if; pf; name,8)||' '||rpad(i.basic,5)||' "||rpad(i.hra,5) ||" close ec; end fo0p; end; SQL> declare cursor dc is select unique deptno oe Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 from emp; cursor ec(pdno in emp.deptno%type) is select empno,ename,sal basic,sal*0.45 hra, sal*0.35 da,sal*0.15 pf,deptno from emp where deptno=pdno; vdno emp.deptno%type; i ec%rowtype; ‘gross number; begin delete from emp_report; ‘open dc; loop fetch de into vdno; exit when de%notfound; open ec(vdno); loop fetch ec into i; exit when ec%notfound; vgross: =i.basict+i.hra+i.da-i.pf; insert into emp_report values(i.empno,i.ename,j.basic,i.hra,i.da,i.pf,vgross, i.deptno); end loop; if ec%rowcount>0 then insert into emp_report(ecode) values(null); end if; close ec; ‘end loop; end; FOR UPDATE Clause * FOR UPDATE clause explicitly locks the records Stored in the private work area, + The FOR UPDATE clause in the cursor query is used to LOCK the affected rows while the cursor is opened. + You need not need provide an explicit COMMIT command to release the lock acquired by using the FOR UPDATE clause. Using WHERE CURRENT OF clause * WHERE CURRENT OF clause to refer the current record, fetched from the explicit Cursor. * we need to suffix the name of the explicit cursor with the CURRENT OF clause to refer to current record. PL/SQL + In order to use the WHER CURRENT OF clause, you need to lock the record fetched from the cursor. SQL>declare cursor Ic is select ename,sal,deptno from emp for update; i lc%arawtype; begin display(‘The emp det are’); display(’EmpName'}|' ‘}VSalary'l{" '{{"DeptNum'}; display(* HH Ii open Ic; loop fetch Ic into i; exit when IcYnotfound; display(rpad(i.ename,8)||' "||rpad(i.sal,5)|[" ‘| |i-deptno); if Ldeptno=50 then delete from emp where current of Ie; end if; end loop; close Ic; display(‘After delete the 50th dept emps'); open Ic; loop fetch Ic into 1; exit when IcYenotfound; display(rpad(iename,8)||' '{|rpad(i.sal,5)1|" "}|i-deptno); end loop; close Ic; end; us re + A CURSOR can be constructed upon the result provided through a SUBQUERY. « The sub query can be an ordinary one or a correlated sub query. SQL> DECLARE CURSOR cs is SELECT d.deptno,d.dname,d.loc,v.noe FROM dept d,(SELECT deptno,count(*) noe By Mr. Krishna Reddy group by deptno) v WHERE v.noe>3 AND d-deptno=v.deptno; BEGIN FOR i in cs Loop display(i.deptno}|' ‘|}idnamel| ‘I]Lloc||* "| |i.n0e); END LOOP; END; ficit cursor is Static Cursor. Explicit. cursor referrers always one work area associated with cursor. Dynamic cursor is Ref Cursor, It referrers different work area in memory. Cursor variables are analogous to PL/SQL variables, which can hold different values at runtime. Tt is used to declare a cursor with out select statement. A Ref Cursor can be reused if it is declared in package. ‘A Ref Cursor support to return more than 1 row from sub program. Deferent select statement can be associated with cursor variable at run time. s of cursor variabl * There are two types of Ref Cursor. If we do not include a RETURN clause in the Cursor, then itis a weak REF Cursor. * Cursor variables declared from weak REF cursors can be associated with any query at runtime. Syntax: step1: Type is ref cursor; step2: ; step3: open for(select statement); fetch exit close; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 3340:: strong cursor variable By Mr. Krishna Reddy * AREF CURSOR with a RETUN clause define a “Strong” REF CURSOR. Syntax: step1: Type is ref cursor RETURN record_type; step2: ; step3: open for(select statement); fetch exit close; SQL>DECLARE vempno emp.empno%type; vename emp.ename%type; vsal emp.sal%type; vjob‘emp.job%type; vdeptno-emp.deptno%type; ‘TYPE ref_c IS REF CURSOR; cl ref_c; --itis data type of ref_e begin vdeptno:=&dno; IF vdeptno=10 THEN OPEN:c1 FOR SELECT empna,ename;sal FROM EMP WHERE deptno=vdeptno; ELSIF vdeptno=20 THEN OPEN ci FOR SELECT ename,job,sal FROM emp WHERE deptno=vdeptno; ELSE OPEN cl FOR SELECT ename,sal,deptno FROM emp WHERE deptna=vdeptno; END IF; IF vdeptno=10 THEN Loop FETCH cl INTO vempno,vename,vsal; EXIT WHEN C1%NOTFOUND; display(vempnoj|" '}|vename||' 'IIvsal); END LOOP; CLOSE cl; _ Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL By Mr. Krishna Reddy ELSIF vdeptno=20 THEN Loop FETCH cl INTO vename,vjob,vsal} EXIT WHEN C1%NOTFOUND; display(vename||" "|Ivjob||" '||vsal); END LOOP; CLOSE cl; ELSE Loop FETCH cl INTO vename,vsal,vdeptno; EXIT WHEN c1%NOTFOUND; display(vename| |" 'I|vsal||' '||vdeptno); END LOOP; END IF; END; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 32:2 Exception Handling Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 432: —EEE— ESS By Mr. Krishna Reddy An Exception in PL /SQL Block is Raised during Execution of a Block. Once an EXCEPTION arises it terminates the main body of actions performed by the PL/SQL block. A Block always terminates when PL / SQL Raises an Exception. WE can specify an exception handler to perform Final action. If the exception is raised in the executable section of the Block and there is No corresponding Handler, the PL / SQL Block Terminates with Failure. If the exception is handled then PL / SQL Block terminates successfully. n Hani ‘An Exception is raised when an error occurs. In case of an error, normal exceptian stops and the control is immediately transferred to the exception handling part of the PL/SQL block. i + The exception handling section consists of handlers for alt the exceptions. + An exception handler contains the code that is executed when the error associated with the exception occurs, and the exception raised. + Each exception handler consists of a WHEN clause which specifies an EXCEPTION that has to.be handled. Syntax Exception When [or exception2...]_ Then SQL statement SQL statement2 When [or exception4...]_ Then SQL statementi SQL statement2 When Others Then SQL statement1 SQL statement2 End; rs Exception f * The OTHERS exception is an optional EXCEPTION handling ciause that ‘traps unspecified exceptions. The OTHERS should always be the last handler in the block. ‘+ It is good programming practice to have an OTHERS handler at the top level of your program to ensure that no errors go undetected. Excepti idelines * Begin the EXCEPTION handiing section of the block with the keywords EXCEPTION. ee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746566, 9000994007 By Mr. Krishna Reddy Define several EXCEPTION HANDLERS ,each with its own set of action for the block. Avoiding unhandled exceptions, this can be done via an OTHERS handler at the topmost level program. When an EXCEPTION occurs PL/SQL processes only one handle before leaving the block. fi ception Oracle has predefined several exceptions that correspond to the most common oracle errors. A predefined oracle server error is trapped by referencing its standard name within the corresponding exception handling at runtime. Each Predefined Exception begins With ORA followed by a number. As soon As the Exception occurs oracle implicitly raise the exception and jumps into the EXCEPTION handle block, if proper EXCEPTION handle is found manages the specified steps. In predefined oracle server exceptions only one exception is raised and handled at any time. ‘Tynes of Exception Pre defin tem defi + Predefined exception are raised automatically by the system during run time. + Predefined exception are already available in the program it is not necessary to declare them in the declarative section like user_defined exception. Predefined Exception Li: Exception Name Error No Description ‘ORA-0001 DUP_VAL_ON_INDEX Unique constraint violated. ORA-1001 INVALID_CURSOR Megat Cursor operation. ORA-1403 NO_DATA_FOUND. No data found. ORA-1422 TOO_MANY_ROWS A SELECT...INTO statement matches more than one row, ORA-1722 INVALID_NUMBER Conversion to a number felled For example,‘krishna street 1° not valid ORA-6502 VAUWE_ERROR Truncation, arithmetic, or conversion error. ORA-01476 ZERO_DIVIDE Divisor is equal to zero. ‘ORA-06511 CURSOR_ALREADY_OPEN This exception is raised when We try to open a cursor which is already opened. ORA-01017 LOGIN_DENIED ‘This exception is raised when we try to enter orade using invalid username/password. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 3245: >DECLARE v_empno emp.empno%TYPE:=&empno; v_ename emp.ename%TYPE; v_job emp.job%TYPE; BEGIN SELECT ename,job INTO v_ename,v_job FROM emp WHERE empno=v_empno; DBMS_OUTPUT.PUT_LINE(‘The empno detail are '|[v_ename||" '||v_job); EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE(‘The empno is not found END; SQL>DECLARE V_aceno keb_ace_tab.accno%TYPE v_name kcb_acc_tab.name%TYPE v_bal kcb_acc_tab.bal%TYPE:=&bal; BEGIN INSERT INTO kcb_ace_tab(accno,name,bal) VALUES(v_accno,v_name,v_bal); DBMS_OUTPUT.PUT_LINE('Account detailes are inserted successfully.’ EXCEPTION WHEN DUP_VAL_ON_INDEX THEN DBMS_OUTPUT.PUT_LINE(‘accno already exists’); END; SQL> DECLARE v_empno emp.empno%TYPE; v_ename emp.ename%TYPE; v_deptno emp.deptno%TYPE; BEGIN SELECT empno,ename,deptne INTO v_empno,v_ename,v_deptno FROM emp WHERE empno=7788 AND ename='SCOTT’; DBMS_OUTPUT.PUT_LINE(‘The scatt works in department number:'||v_deptno); Select empno,ename,deptno into v_empno,v_ename,v_deptno FROM emp Where deptno=10; DBMS_OUTPUT.PUT_LINE(‘The Employee number:'||v_empno); DBMS_OUTPUT.PUT_LINE(‘The Employee name:'||v_ename); By Mr. Krishna Reddy Exception WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('Error:There is no such empno or ename or deptno'); WHEN TOO_MANY_ROWS THEN (OBMS_OUTPUT.PUT_LINE('Error:More than one Employee works in department number 10"); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Error occurred while processing the Program’); END; User-defined Exception: + A user-defined exception is an error that is defined by the program + The developers to handle the business situations define user-defined exceptions during the execution of the PL/SQL block. + User defined exceptions are defined by the following two techniques: Using a flow control statement RAISE Raise statement transfer the control of the block from the execution Part of the PL/SQL block to the exception handing part of the block. Step 1. Declare Exception 2. Raise in Executable section explicitly using RAISE ; 3. Handle the raised exception Using a packaged procedure RAISE_APPLICATION_ERROR(error number, ‘Error message’); RAISE APPLICATION ERROR This Built-in procedure is used to create your own error message, which can be more descriptive than named exceptions. It is used to communicate a predefined exception interactively by returning a non standard error code and error message. Using this procedure we can report error to application and avoid returning unhandled exception. Error number must exists between -20,000 and -20,999 PL/SQL By Mr. Krishna Reddy * Error_message is the text associate with this error, and keep_errors is Boolean value. The error_message parameter must be less than 512 characters. SQLCODE FUNCTION + Wreturns the current error code. * Fora user defined exception it returns 1, +100 NO_DATA_FOUND exception. SQLERRM + It returns the current error message text. SQLERRM returns the message associated with the error number. The maximum length of a message returned by the SQLERRM functions is 512 bytes. SQL> DECLARE i emp%rowtype; BEGIN i.empno:=&eno; SELECT ename,sal into i.ename,i.sal from emp where empno=i.empno; IF i.sal<2000 THEN Raise_application_error(-20345,'The emp sal is less than 2000 $0 no updation’); i.sal:=i.sal+i.sal*0.35; UPDATE emp set sal=i.sal WHERE empno=i.empno; ELSE i.sal:=i.sal+i.sal*0,3 UPDATE emp set sal=i.sal WHERE empno=i.empno; display(‘The emp det are '||i.ename||" '||i.sal); END IF; END; QL>DECLARE salary_missing EXCEPTION; i emp%rowtype; BEGIN isempno:=&eno; SELECT ename;sal into iename,i.sal FROM emp WHERE empno=i.empno; IF i.sal IS NULL THEN ee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL RAISE salary_missing; ELSE i.sal:=i.sal+i.sal*0.25; UPDATE emp SET sal=i.sal WHERE empno=i.empno; display(‘The emp det are '||i.ename||' ‘| [i-sal); END IF; EXCEPTION WHEN no_data_found THEN display(i-empno]|' is not exists’); display(SQLCODE||' '||SQLERRM); WHEN salary_missing THEN display(‘The emp is not having any salary so give salary as 3000"); UPDATE emp SET sal=i.sal WHERE empno=i.empno; display(SQLCODE||" "||SQLERRM); WHEN others then display(‘The SUHE’); END; Trapping Non: ed rver error: We can associate a named exception with a particular oracle error. The Non-predefined oracle server error is trapped by declaring it first or by using the OTHERS exception handle. The declare EXCEPTION is RAISED implicitly by the oracle server. The PL/SQL PRAGMA EXCEPTION_INIT() can be used for associating EXCEPTION name with an oracle error number. The PRAGMA EXCEPTION_INIT() tells the PL/SQL engine completely to associate an EXCEPTION name with an oracle error number. The PRAGMA EXCEPTION_INIT() allows programmer to refer to any internal EXCEPTION by the name and associate that to specific handles, Pragma is a directive of compiler which tells compiler to associate error no with user declared exception at compile time. ‘Steps 1.Declare Exception 2. Associate Exception with Oracle error No. using Pragma exception_init(exception_name,oracle_error_number); 3. Handle the raised exception + Exeption_name is the name of an exception declare prior to the pragma. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL * Oracle _erroe_number is the desied error code to be associate with this named exception. SQL> DECLARE pk_vio EXCEPTION; PRAGMA EXCEPTION_INIT(pk_vio,-00001); BEGIN insert into emp(empno,ename,sal,deptno) values(&eno,'&ename',8sal,&deptno); EXCEPTION when pk_vio then dbms_output.put_line(‘Duplicate empno is not allowed here’); END; Understanding PL/SQL Collections Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 HS By Mr. Krishna Reddy + PL/SQL, similar to other programming languages such 2s C,C++, allows using arrays and records. + PL/SQL has two composite types :records and collections. PL/SQL Records + APL/SQL Record is allows you to treat several variables as a unit. + PL/SQL Record are similar to structure in C. + When a "RECORD TYPE" of fields are declared then they can be manipulated as a Unit through out the Application. Note: In the composite data type RECORD, we can specify the data type of the column. + Each RECORD defined can have as many Fields as necessary. + Fields declared as ‘not null’ must be initialized in the declaration part. + Arrecord can be initialized in its declaration part unlike PL/SQL tables, which doesn’t allow initialization in the declaration part. + The DEFAULT key word can also be used when defining fields. + ARECORD can be the component of another RECORD. PL/SQL ‘TYPE type_name IS RECORD element! , Element2 , Element3 , Blement4 , Elementn It is the data type of the Element. o Expr >It is the Field type OR an Initial Value. >The NOT NULL constraint prevents the Assigning of NULL’s to those Fields. Element declaration are like variable declaration each Element has a unique name and A specific data type. -> We must ereate the data type first and then declare an identifier using the declared data type. Naresh i Technologies, Opp. Satyam Theatre, Ameerpes, Hyderabad, Ph: 040-23746666, 9000994007 35: lustration SQL>DECLARE TYPE erec IS RECORD (veno NUMBER(A), ‘vname emp.ename%TYPE, basic emp.sal%TYPE, i depe%ROWTYPE, ‘vgross number(16,2)); ecree: BEGIN e.veno=&employe; select ename,sal,dept.deptno,dname into e.vname,e.basic,e.i.deptno,e.idname from emp,dept where emp.deptno=dept.deptno and empno: e.vgross:=e.basic+e.basic*.251-¢. basic*.35-e.basie*.12; display(e.venol! ‘je-basiel! "Je.ideptnol! "feidnamel! ‘je.vgross), END; PL/SQL Tables PL/SQL. tables are temporary array-like objects used in a PL/SQL block. They are modeled as database tables, but are not same, PL/SQL tables are very dynamic in operation, giving the simulation to pointers in ‘C’ language. PL/SQL TABLES use a “PRIMARY KEY” to give array like access to rows. PL/SQL table can be declared in the declarative part of any block. Subprogram or package. Is similar to an array in Third generation language. PL/SQL table should contain two components. o A“PRIMARY KEY” of data type BINARY_INTEGER, that indexes the PL/SQL table. © Acolumn of a scalar or Record data type which stores the PL/SQL table elements, PL/SQL tables can increase in size dynamically as they are unconstrainted. APLISQL TABLE must be declare in two steps. 1) First we define a table type 2)We declare a variable of PL/SQL table as data type, Syntax TYPE IS TABLE OF {column type OR Table.column%TYPE OR PL/SQL RECORD} INDEX BY BINARY_INTEGER; ‘© The number of rows in PL/SQL table can increase dynamically, hence a PL/SQL table can grow as new rows are added, Referencing PL/SQL Table Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL By Mr. Krishna Reddy * PLSQL_Tablename(Primary_key_value); + PRIMARY_KEY_VALUE belongs to type BINARY_INTEGER. + The primary key value can be negative indexing need not start with 1. +The method make PL/SQL tables easier to use are, COUNT Returns the number of elements that a PL/SQL table currently contais. SQL>DECLARE TYPE name IS TABLE OF VARCHARQ(50) INDEX BY BINARY_INTEGER; n(2)="Krishna’s display(The full name is 'jn(O)I! {In(1)I ‘In(2)); END; Note: In oracle 11g Negative index are not allowed. ename varchar2(20), uusal number(7,2), dou timestamp SQL>DECLARE TYPE eno IS TABLE OF ‘emp.empno%TYPE INDEX BY BINARY_INTEGER; TYPE name IS TABLE OF emp.ename%TYPE_ INDEX BY BINARY_INTEGER; TYPE pays IS TABLE OF emp.sal%TYPE INDEX BY BINARY_INTEGER; e eno; name; P pays ctl number:=1; BEGIN FOR i IN(SELECT empno,ename,sal FROM emp) eth=ctl+1; END LOOP; for Mylndex IN L..e.count PL/SQL LOOP IF p(Mylndex) BETWEEN 0 AND 1000 THEN p(Myindex):=p(Myindex)+100; ELSIF p(Mylndex) BETWEEN 1001 AND 2000 THEN p(Mylndex):=p(Mylndex)+200; ELSE p(Myindex)=p(Mylndex)+300; END IF; UPDATE emp SET sal=p(Mylndex) WHERE empno=e(Mylndex); INSERT INTO trace VALUES(n(MyIndex),p(MyIndex),sysdate); Display(n(MyIndex)|' ‘ip(MyIndex)); END LOOP; END; Nested type Collection ‘TYPE type_name 1S RECORD By Mr. Krishna Reddy EmpRecord Emp%ROWTYPE, DeptRecord Dept%ROWTYPE, Element RECORD); SQL>DECLARE, TYPE pf_info is RECORD (pfno NUMBER(4), asnount NUMBER(14.2)); TYPE emp_sec IS RECORD (cid NUMBER(4), ame VARCHARI(20), basic NUMBER(12,2), pfpf_info); TYPE etab 1S TABLE OF emp_see INDEX BY BINARY_INTEGER; ctr NUMBER@G) eetaby BEGIN FOR i INGELECT empno,ename,sal basic, sal*.12 pamt FROM emp WHERE sal>2000) 1: 040-23746666, 9000994007 55: By Mr. Krishna Reddy display(‘employee detailes are FOR Mylndex in J..c.count loop display(e(Mylndex).cid|" “|Je(Myindex).namel]" ‘e(Myindex) basic’ "le(Mylndex).pfpfino|? ‘e(Mylndex).pfamount); END LOOP; END; RETURNING Claus ‘© This clause is valid at the end of any DML statement. ‘It is used to get information about the row or wows just processed. Syntax ——> REURNING ——+ expr——+ INTO + variable © exprisa valid PL/SQL or SQL expression, which can include columns or pseudocolumns of the current table. + Variable is the PLISQL variable into which the result will be stored, BULK COLLECT clause * Itused to collect more than | row at atime. © itis used as part of the SELECT INTO,FETCH INTO , or RETURNING INTO clause and will retrieve rows fiom the query into the indicated collections. BULK COLLECT clause with SELEC Mlustrations SQL> DECLARE TYPE name IS TABLE OF emp.ename%TYPE. INDEX BY BINARY_INTEGER; ‘TYPE pays 1S TABLE OF ‘emp.sal%6T'YPE INDEX BY BINARY_INTEGER; name; P pays; BEGIN SELECT ename,sal BULK COLLECT INTO n,p FROM emp; FOR i IN I.n.COUNT Loop Display(RPAD(a(i)9,"9 ENDLOOP; END; BULK COLLECT clause DELETE, ‘Table delete_log ename varchar2(20), basic number(7,2), dod timestamp SQL> DECLARE Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy TYPE name [S TABLE OF emp.ename%TYPE INDEX BY BINARY INTEGER; TYPE pays IS TABLE OF emp.sal%TYPE INDEX BY BINARY_INTEGER; nname; p pays; BEGIN DELETE FROM emp WHERE deptno=30 RETURNING ename,sal BULK COLLECT INTO 1,p; FOR iIN L.n.COUNT LOOP Display(RPAD(n(i).9; I ip): IF p(>2500 THEN INSERT INTO detete_log VALUES(n(j),p(i),sysdate);, END IF; END LOOP; END; BULK COLLECT clause UPDATE SQL> DECLARE TYPE name IS TABLE OF emp.ename%TYPE INDEX BY BINARY INTEGER; ‘TYPE pays IS TABLE OF emp.sal%TYPE INDEX BY BINARY_JNTEGER; name; P pays; BEGIN UPDATE emp SET sal=sal+sal¥0.35 WHERE deptno=20 RETURNING ename,sal BULK COLLECT INTO n,p; FOR iIN 1.n.COUNT LOOP Display(RPAD(n(i),9," II" ip@); IF p(i)>2500 THEN INSERT INTO trace VALUES(n(i),p(i),sysdate); END IF; END LOOP; END; BULK COLLECT clause CURSOR ‘SQL> DECLARE ‘TYPE name 18 TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER; TYPE pays IS TABLE OF emp.sal%TYPE INDEX BY BINARY_IN’ ER; EES Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 57: CURSOR ¢_bulkcollect IS SELECT ename,sal FROM emp; nname; P pays; BEGIN OPEN c_bulkcallect; FETCH c_bulkcollect BULK COLLECT INTO 1,p; OR iJIN 1..n.COUNT LOOP Display(RPAD(O(H,9.' 9 PO); END LOOP; END; Differences between Anonymous and Named PL/SQL block. Anonymous PLISQL Block Named PL/SQL Block 4 This is an unnamed PLISQL block 1 This is a named PLISQL block 2.These are stored in operating system 2.These are stored in oracle databace, 3.There is no security 3.0radle is providing security 4.There is no information hiding facility 4.There is a hiding facility. 5. It requires. every time compilation process. 6.Granting privileges on this is not possible, 5.lt is compiled once and ready to execute 6 Granting privileges is possible. 7. These are accessibie by other orade | tools like SQL*PLUS ,Oracie Forms Reports, Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 Subprograms In PL/SQL By Mr. Krishna Reddy ——————————— EE + Subprograms are used to provide modularity and encapsulate a sequence of statements. * ance subprograms are built and validated, they can be used in a number of applications, + Subprogram also provide abstraction. + Subprograms are named PLISQL blocks that can accepts parameters. + A Subprogram can also have a declarative part, an executable part and an exception handling part, important features of subprogram Modularity + Subprograms allow us to break a program into manageable, well-defined logical modules. Reusability + Subprograms once executed can be used in any number of application. Maintainability + Subprograms can simplify maintenance, because if a subprogram is affected, only its definition changes. PROCEDURES o A procedure is a subprogram that performs a specific action. o Aprocedure may or may not return value. Syntax CREATE OR REPLACE PROCEDURE procedureName(parniamet [MODE] parType,..) 1s {Local variable dectaration:] BEGIN Executable Stage EXCEPTION Exception Handlers; END [ProcedureName]; * Procedure can have o or many parameters. + Every PROCEDURE consists of TWO parts * The header of the procedure. * The body of the procedure ‘The Header ‘+ Itcomes before the AS/IS keyword. + It contains the PROCEDURE NAME and the PARAMETER LIST. The Body + Itis any thing or every thing that is existing after the AS keyword. + The word REPLACE is optional EE Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PLSOL Execute a Procedure At SQL Prompt >EXECUTE/EXEC PROCEDURE_NAME Call the Procedure in another PLISQL Block SQL>BEGIN PROCEDURE_NAME; END; + The procedure details are stored in o USER_SOURCE o USER_OBJECTS By Mr. Krishna Reddy CREATE OR REPLACE PROCEDURE cal_intr (P number,N number,R number) Is si number(14,2); ci number(16,2); *N*R)/100; ci:=power((1#1/100),n);~not case sensitive ci=ptey, dbms_output puit_line(simple interest is“\jsiy, dbms_output.put_line(‘compound interest isc); END cal_intr, To view the Procedure availability ‘SQL>SELECT object_name ,object_type, status FROM USER_OBJECTS WHERE object_name="PROC_NAME"; Mlustration SQL> SELECT object_name ,object_type,status FROM USER_OBJECTS WHERE object_name=!CAL_INTR’, SQL> SELECT line|}>',text FROM user_source WHERE name='PROC_NAM Mustration ‘SQL> SELECT line||>',text FROM user_source WHERE name='CAL_INTR'; Recompile an Existing Procedure Syntax ‘SQL>ALTER PROCEQURE procedurename compile; Illustration SQL>ALTER PROCEDURE cal_intr COMPILE SQL>CREATE OR REPALCE procedure proc_bonus as Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 36h By Mr. Krishna Reddy cursor cbis select empno,ename, job,sal+nvi(comm,0) netsal from emp; { eb%rowtype, bonus number, begin ‘open cb; loop fetch cb into i; exit when cb%notfound; ‘CLERK’ then :=i.netsal"0.15; elsif ijob='SALESMAN' then netsal"0.25; bonus:=i.netsal*0.35; endif, update emp set sal=sal+bonus where empno=i.empno; display(rpad(ename.8)|{' ‘[lrpad(i.job,8)|I' ‘I|bonus); end loop; close cb; END proc_bonus; Subprogram Parameters PARAMETERS are the mean to pass values TO and FROM the calling environments to the oracle server. PARAMETERS are the values that will be processed of retuned via the EXECUTION of the PROCEDURE or FUNCTION + These PARAMETERS can have different modes. Parameter Modes + There are three types of modes © IN Mode © OUT Mode 0 INOUT Mode IN MODE + Itis the Default mode of subprogram. * Passes a value into the program , from the calling environment. *_ itis READ ONLY value QUT MODE Used to return a value from subprogram, Itis WRITE ONLY value. Passes a valued back from the pragram to the calling environment. Cannot be assigned default values. Value assigned only if the program is successful. — ee EEE Naresh i Technotogies, Opp. Satyare Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 INOUT MODE * Carriers a value into a subprogram, ‘Returns value from sub program. + Values will be READ from the calling environment and then WRITTEN to the calling environment SQL> CREATE OR REPLACE PROCEDURE proc_sc(n in NUMBER,s OUT NUMBER, c OUT NUMBER) c=s'n; END proc_sc; > var st NUMBER > VAR or NUMBER > EXEC proc_sc(10,:sr,:cr) Calling in PLISQL block SQL>DECLARE n NUMBE! vs NUMBER: vc NUMBER; BEGIN proc_se(n,vs,ve); dispiay((The "jai seq and cube values are 'Ilvs|' ‘IVc); END; SQL>DECLARE n NUMBER:=&no; BEGIN proc_se(n,:st,:cr); display(‘The ‘|[n||" seq and cube values are '||:sr{|" ‘[I:cr); END; SQL>CREATE OR REPLACE PROCEDURE Proc_dtsal(pdts IN OUT NUMBER ) Is BEGIN SELECT SUM(sal) INTO pats FROM emp WHERE deptno=pdts; END proc_dtsal; SQL> CREATE OR REPLACE PROCEDURE proc_dtsal(pdts IN OUT NUMBER) Naresh i Techuologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 63:1 By Mr. Krishna Reddy SELECT SUM(sal) INTO pats FROM emp WHERE deptno=pdts; END proc_dtsal, > var bdts NUMBER >EXEC :bdts:=10 SQL> CREATE OR REPLACE PROCEDURE ‘adé_dept(pdname IN dept cname’STYPE DEFAULT "'UNKNOW, jg OPIN deptloc¥sTYPE DEFAULT UNKNOW) k BEGIN INSERT INTO dept VALUES (ds.nextval,pdname,ploc); END add_dept; Note: If want insert value only for ‘loc’ ‘Types of sending arquments to the subproaram Position Notation + Itis simple an association of the values by POSITION of the arguments at call time with that of declaration in the header of the procedure creation. . «The order of the parameters used wtién executing the procedure should match the order in the PROCEDURES HEADER exactly. Named Notions(=>) ‘+. Itis an explicit association using the symbol => Syntax Formalparametername=>ArgValue + In named notation the order of parameters in:does not matter. ‘+ If the notation is mixed then position notation should be used first then the named notation should be used. SQL>GRANT EXECUTE ON cal_intr to mitier, MILLER SQL>EXEC scott cal_intr(1000,12,2) ‘Synonym for Procedure SQL>Create [public] Synonym for ; SQL> Create public Synonym sci FOR. cal_intr; SQL> GRANT EXECUTE ON sci TO PUBLIC; MILLER ‘SQL>exec $ci(1000,12,2) Note: Synonym can't be created for Procedure which is defined in Package. pragma autonomous transaction Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23 746666, 9000994007 1643: By Mr. Krishna Reddy Prior to Oracle 8i and higher .(Autonomous-in_depended). it Used in nested procedure to make each procedure in_depended for TCL. Allow to write TCL in Trigger. It must appear in the declarative section of the block and only one pragma is allowed in the block. Itcan go anywhere in the declarative section ,but is it good style to put it at the beginning. SQL>CREATE OR REPLACE PROCEDURE add_emp AS BEGIN INSERT INTO emp(empno,ename job,sal,deptno) VALUES(7001 ,EFCODD’ MANAGER’, 2000,50); ‘COMMIT; END add_emp: ‘SQL>CREATE OR REPLACE PROCEDURE add_dept AS BEGIN INSERT INTO dept VALUES(50,'EXPORT,, add.emp; END add_dept; How to store Images SQL>CREATE OR REPLACE procedure load(fname varchar2) as flab bfile; b_lob blob; Begin insert into Images values(iname, substr (fname, instr(fname,.’)+1) sempty_blab()) RETURN image into b_lob; £_lob=BFILENAME('KRISHNA’ fname); dbms_tob fileopen(f_lob,dbms_lob.file_readonly);_dbms_lob.loadfromfile(b_lob,f_lob, dbms_lob.getlength(f_lob)); dbms_lob.fileclose(f_lob); commit, end load; Dropping Procedure ‘* Similar to dropping a table procedure can also be dropped. Syntax SQL> DROP PROCEDUE procedure_name; illustration SQL>DROP PROCEDURE cal_intr; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 USER DEFINED FUNCTIONS By Mr. Krishna Reddy A function is very similar to a procedure. Function is a named PL/SQL block and it may or my not take the parameters but it must return a value. Function must have a RETURN clause in the EXECUTABLE section of a FUNCTION. Functions are mainly used to perform the calculation. ‘The data type of the return values must be declared in the header of the function. Procedures and Functions are different forms of PL/SQL blocks, with a declared, executable, and exception section. Procedures and Functions can be stored in the database or declared within a block. A procedure calll is a PL/SQL statement by itself, while a function calll is called as part of an expression. A function has output that needs to be assigned to a variable or it can be used in a SELECT statement. Function can not call when it has RETURN data type as Boolean. A Function can contain more than one RETURN statement, each Exception should have a RETURN statement. Syntax ‘CREATE [OR REPLACE] FUNCTION (parameter List) RETURN data type Is {Local variables] BEGIN RETURN(value); EXCEPTION END [Function name]; >CREATE OR REPLACE FUNCTION cal_intr (P NUMBER,N NUMBER,R NUMBER) RETURN NUMBER Is v_ci NUMBER(16,2); POWER((1+1/100),n); _ci:=p*v_ci; RETURN(V_ci); END; Naresh i Technalogies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy Ning function a >var cint number; >exec :cint: int, function wit LECT si en >SELECT cal_intr(1000,12,2) FROM dual; > SELECT ename,hiredate,sal,ROUND (cal_intr(sal,12,2)) "cinte" FROM emp Calling Function In PL/SQL block DECLARE v_cintr NUMBER; BEGIN V_cintr:= cal_intr(1000,12,2); DISPLAY(‘The Compound Intr is: ‘I|v_cintr); END; / CREATE OR REPLACE FUNCTION leapyear {y NUMBER) RETURN VARCHAR2 Is BEGIN IF (MOD(y,400)=0)OR (MOD(y,100)!=0 and MOD(y,4)=0) THEN RETURN(‘Leap Year’); ELSE RETURN(‘Not Leap Year'); END IF; END; / Q)Write a function to accept the empno and return exp with minimum 3 decimal? CREATE OR REPLACE FUNCTION empexp(p_empno emp.empno%TYPE) RETURN NUMBER Is v_hiredate emp.hiredate%TYPE; v_exp NUMBER(6,3); BEGIN SELECT hiredate INTO v_hiredate FROM emp WHERE empno=p_empno; v_exp:=MONTHS_BETWEEN(SYSDATE,v_hiredate)/12; RETURN v_exp; END; 140-23 746666, 9000994007 268: By Mr. Krishna Reddy Q) Write a function to accept the deptna and return the No of emps in that deptna. CREATE OR REPLACE FUNCTION noe(p_deptno emp.deptno%TYPE) RETURN NUMBER Is v_noe NUMBER(6,3); BEGIN SELECT count(empno) INTO v_noe FROM emp WHERE deptno=p_deptno; RETURN v_noe; END; > select unique deptno,noe(deptno) from emp where noe(deptno)>3; Database TRIGGERS By Mr. Krishna Reddy Database TRIGGER: 7 A Trigger set of PL/SQL statements automatically executed whenever an DML statement is performed on table. {tis a PL/ SQL Block like a Procedure. i, to perform some specific task. But a procedure always requires an expiicit cali for execution but triggers are executed automatically when any triggering event occurs. Itis Associated with a Table or View. INSERT,UPDATE,DELETE are considered as the triggering events of the database trigger. These events initiate the firing of trigger. The firing of trigger is nothing but the execution of the PLISQL code associated to that trigger. Itis also a Database Object Advantage ‘A database trigger is a security object to provide security to the table like tracking the transaction. A database trigger is also used to define the complex business constraints that cannot be defined by using integrity constraints, Automatically generating values for derived columns or PRIMARY KEY columns. Used to implement user defined restrictions on table provides high security. Activated when table are manipulated from other application software also, Synta SQL>CRAETE [OR REPLACE ] TRIGGER triggername AFTER/BEFORE INSERT or UPDATE or DELETE [OF columnname] ON tablename [FOR EACH ROW, (WHEN condition] DECLARE Declaration statements; BEGIN Executable statements; [EXCEPTION Exception handling:] END [trg_name]; * Trigger can not be duplicate trigger name ‘© Trigger can be attached one table * When condition is true, trigger will be executed otherwise not executed The specification New&0ld «Refers to the values available in DML statements. + Valid in row trigger only. PL/SQL By Mr. Krishna Reddy New&Old:- Refers to the values available in DML stmts. Valid in row trigger only Application Database| | Tri Trigger | Application Trigger + {tis fired when DML Event occurs Within the Application. Example : Oracle Forms Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 Database Trigger * Itis fired when DML Event occurs on a Table / View, no matter which User is connected. Component of Trigger Trigger Parts ‘* Indicates when to activate the trigger. i.e., defines whether the trigger fires before or after the statement is executed. Before Triggers * These TRIGGERS fire BEFORE any transactions are implemented. * These TRIGGERS can be classified as o BEFORE INSERT © BEFORE UPDATE o BEFORE DELETE Usage * When a trigger provides values for derived columns BEFORE the INSERT OR UPDATE statement is completed. + When a trigger determines whether an INSERT,UPDATE of DELETE statement should be allowed to completed After Triggers + These TRIGGERS fire AFTER any transaction is implemented. * These TRIGGERS can be classified as © AFTER INSERT. o AFTER UPDATE By Mr. Krishna Reddy o AFTER DELETE Usage ‘| When a TRIGGER should fire after a DML statement is executed for acknowledgement Purpose or auditing. + When a TRIGGER should perform action not specified in a BEFORE trigger. Restrictions * A trigger may not issue a transactional control statement like COMMIT,SAVEPOINT and ROLLBACK. * Any FUNCTION or PROCEDURE called by a trigger cannot issues a transaction control statement. Level of Triggers + Trigger can be define at two different levels. + They are 1)Row level 2)Staterent of table level Row level Trigger ‘+ Arowtrigger is fired as many times as there ate rows affected by triggering event. + When the statement FOR EACH ROW is present in the CREATE TRIGGER clause, the trigger is a ROW trigger. Statement Level ‘+ Trigger will be fired only once for DML statement. Trigger Body + Aset of PUSQL statements. The WHEN clause + The WHEN clause is valid for row-level triggers only. ‘+The trigger body will be executed only for those rows that meet the condition Syntax: WHEN trigger_condition «The :new and :old records can be referenced inside trigger_condition as well «The colon is only valid in the trigger body. + Activated when table are manipulated from other application software also. Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 nT: Database Applications Update How many Trigger are there Wxm-12 Trigger. Row level After Insert Before Insert After Update Before Update After Delete Before Delete Table Level After Insert Before Insert After Update Before Update After Delete Before Delete SQL>create ar replace trigger trg_upp_con before insert or update of name on keb_ace_tab FOR EACH ROW BEGIN :NEW.name:=UPPER(-NEW. name); END trg_upp_con, SQL> CREATE OR REPLACE TRIGGER trg_nnd By Mr. Krishna Reddy BEFORE INSERT OR UPDATE OF dname ON dept FOR EACH ROW DECLARE ont NUMBER; pragma autonomous_transaction; BEGIN SELECT count(*) INTO cnt FROM DEPT WHERE dname=:NEW.DNAME; IF cnt>0 THEN, RAISE_APPLICATION_ERROR (-20345,The dame con not be dup’); ELSIF :NEW.dname IS NULL THEN RAISE_APPLICATION_ERROR (-20346,The dname con not be nul’); END IF; END trg_nnd; Table delete_log ecode NUMBER(4), ename VARCHAR2(20), basic NUMBER(7,2), dod timestamp SQL>CREATE OR REPLACE TRIGGER trg_del AFTER delete ON emp FOR EACH ROW BEGIN INSERT INTO delete_log VALUES(-OLD.empno,:OLD.ename, :OLD.sal,sysdate); END trg_dels Table Trace Userid varehar2(20), dod timestamp SQL>CREATE OR REPLACE TRIGGER trg_del AFTER delete ON emp FOR EACH ROW BEGIN INSERT INTO trace VALUES(user,sysdate); END trg_det, SQL>CREATE OR REPLACE TRIGGER trg_bonus AFTER INSERT ON emp Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL FOR EACH ROW DECLARE pragma autonomous transaction; BEGIN INSERT INTO bonus VALUES(-NE W.ename,:NEW.job,:NEW.sal, COMMIT; END trg_bonus; It gives Run time error ORA-04092: cannot COMMIT in a trigger SQL> rollback: Emp table transactions only will rollback; SQL>CREATE OR REPLACE TRIGGER trg_sal AFTER delete ON EMP FOR EACH ROW WHEN (0ld.sal>1500) BEGIN INSERT INTO delete_log VALUESCOLD.empno,:OLD.ename,:OLD.sal sysdate); END tig sal; 3.events on single Trigger (nsert,update,delete) CREATE (OR REPLACE ] TRIGGER BEFORE/AFTER insert OR update OR dekte ON (FOR EACH ROW) [When condition] (DECLARE] BEGIN IF Inserting THEN SQL Statements ENDIF; IF updating THEN SQL Statements ENDIF; IF deleting THEN SQL Statements END IF; END [trg_name]; CE Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 HTT: By Mr. Krishna Reddy > dese INT_TAB Name ECODE NUMBER(4) NAME VARCHAR2(10) DEPTNO NUMBER(2) SQL> desc UPD_TAB Name Null? ‘Type ECODE NUMBER(4) NAME VARCHAR2(10) USAL NUMBER(7,2) SQL> dese del_tab Name Null? Type ECODE NUMBER(4) NAME VARCHAR2(10) JOB VARCHAR2(9) ‘SQL> CREATE OR REPLACE TRIGGER trg_iud AFTER. insert OR update OR delete ON emp FOR BACH ROW BEGIN IF Inserting THEN INSERT INTO int_tab VALUES(:NEW.empno,:NEW.ename,:NEW.deptno); END IF; IF updating THEN INSERT INTO upd_tab VALUES(-NEW.empno,:NEW.cname,:NEW,sal); ENDIF; IF deleting THEN INSERT INTO del_tab VALUES(:OLD.empno,:OLD.ename,:OLD.job); END IF; END trg_uid; Table job_list Job low_pay high_pay Clerk 3000 3000 Salesman 4000 12000 Annalist $000 25000 Naresh i Technologies, Opp. Salyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 78s: By Mr. Krishna Reddy SQL>CREATE OR REPLACE TRIGGER trg_job BEFORE insert OR update ON EMP for each row WHEN (NEW. job PRESIDENT) DECLARE, i job_list%ROWTYPE; BEGIN SELECT low_pay,high_pay INTO i.low_pay,i.high_pay FROM job_list WHERE job=INITCAP(-NEW job); IF :NEW-sal NOT BETWEEN i-low_pay AND i.high_pay THEN RAISE_APPLICATION_ERROR -20345,:NEW,job |I' sal in between Ii-low_pay(| and "Ii-high pay); ENDIF; exception WHEN no_data_found THEN RAISE_APPLICATION_ERROR (-20346;NEW job||' is not exists in job_list table’); END trg_job; SQL>CREATE OR REPLACE TRIGGER trg_wht BEFORE INSERT OR UPDATE OR DELETE, ON emp DECLARE ‘nt NUMBER; BEGIN SELECT COUNT(*) INTO cnt FROM htab WHERE TO_CHAR(HDAY,'DD-MON-YY')=TO_CHAR(SYSDATE,'DD-MON-YY}); IF TO_CHAR(SYSDATE,DY9) IN(SAT SUN’) THEN RAISE_APPLICATION_ERROR(-20345,'No transaction in week end’); ELSIF cnt>0 THEN RAISE_APPLICATION_ERROR(-20347,'No transaction in Hay’); ELSIF TO_CHAR(sysdateHH24’) NOT BETWEEN 9 AND 19 THEN RAISE_APPLICATION_ERROR(-20348, No transaction in this time’); END trg_whts Remove trigger Syntax SQL>DROP TRIGGER ; SQL>DROP TRIGGER trg_wht; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL ‘To disable all triggers on Table SQL> ALTER TABLE DISABLE ALL TRIGGERS; SQL>ALTER TABLE emp DISABLE ALL TRIGGERS; To Enable all triggers on Table SQL> ALTER TABLE ENABLE ALL TRIGGERS; SQL > ALTER TABLE emp ENABLE ALL TRIGGERS; To disable single trigger on Table Syntax SQL>ALTER TRIGGER trg_name DISABLE; SQL>ALTER TRIGGER trg_wht DISABLE; ‘To enable single_ trigger on Table Syntax SQL>ALTER TRIGGER trg_name ENABLE SQL>ALTER TRIGGER trg_wht ENABLE; SQL> SELECT TRIGGER_TYPE, TRIGGERING _EVENT,STATUS from user triggers WHERE TRIGGER_NAME=TRG_WHT ‘To view the source code of Trigger SQL>SELECT text FROM user_source WHERE nameTRG_WHT;, Instead of Triggers(8i Trigger on view used to manipulate join views Instead of >insert update Pdelete SQL> CREATE VIEW ev AS SELECT *FROM emp; ‘SQL> CREATE OR REPLACE TRIGGER trg_ev Instead of DELETE ONev BEGIN display(Record is removed’); END trg_ev; SQL> CREATE OR REPLACE VIEW ed_view AS SELECT empno,ename,job,sal,e.deptnio,dname,loc FROM emp e,dept d WHERE e.deptno=d.depino; SQL> CREATE OR REPLACE TRIGGER trg_ed instead of DELETE ON ed_view BEGIN DELETE FROM emp eee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 1280: DELETE FROM dept WHERE deptno=:OLD deptno; END trg_ed; DDL_ TRIGGERS + The only difference between DML and DOL triggers isthe firing event, “You use DDL triggers to enforce rules Or audit the creation of database objects. 2 _ We create a table name AUDIT. CREATION. ‘5Q13create table aust-creation (audit creation 1d number constraint se primary key, audi owner neve varchar2{30) constraint agi creation nt nok ull ‘audit-ob]-name varcher2(30) constrain audit reation.2 not nll audit date date constraint aude creation an3 Rot null Even attribute Function. ‘ORG_DICT_OBJ_OWNER “This function takes no formal parameter. + TtRetums no owner of the object acted upon by the event as a VARCHAR? datatype. ‘ORA_DICT_OBI_NAME + TeFetum an object name as a VARCHAR2 datatype. +The object name represents the target ofthe DDL statement. This trigger tracks the creation all objects, including which user issued the CREATE statement. >CREATE OR REPLACE TRIGGER audit_creation -Before-create on SCHEMA BEGIN oe INSERT INTO audit. creation VALUES(audit_creation_si.nextval, ‘ORA_DICT_OB)_OWNER, By Mr. Krishna Reddy Database Packages By Mr. Krishna Reddy Itis logical group of objects such as ©. Functions © Procedures co Global variables © Cursors Advantages + Packages allow us to organize our application development more efficiently + Packages allow us to grant the privileges more efficiently. + allows the Oracle Server to Read Multiple Objects into Memory at Once. © Packages can contain global variables and cursors that are available to all procedures and functions in the packages. Packages allow us to overload procedure and functions. All related program objects are stored in one particular location in the memory (which reduce the search process) stored in USER_SOURCE. Package has two parts, with are individually coded. © Package specification © Package body Components of a Package Specification ‘Body [Package] Specification] Package Specification * The PACKAGE SPECIEICATION contains information about the contents of the package. * PACKAGE SPECIFICATION contains declarations of GLOBAL/PUBLIC variables, Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy * All object placed in the PACKAGE SPECIFICATION are called PUBLIC OBJECTS. such objects are called public objects Syntax for Specification: CREATE (OR REPLACE ] PACKAGE IS/AS type_definition PROCEDURE ( parameter ) FUNCTION ( parameter ) RETURN datatype; Variable_declaration; Exception_ declaration; Cursor_declaration; END [Pkg Name]; Package Body + The PACKAGE BODY isa separate data dictionary object from the package header. * The PACKAGE BODY contains the actual executable code for the OBJECTS described in the PACKAGE SPECIFICATION. + The PACKAGE BODY contain code for all procedures and function described in the specification. When creating stored package the package specification and body can be complied separately. Syntax for Body: CREATE [OR REPLACE] PACKAGE BODY IS/AS [Private variable declaration]; PROCEDURE arg list) 1s END [procedure name]; FUNCTION arg list) RETURN datatype END ; Invoking Package Constructs >Execute .; Bodiless Package © We can declare Package Specification that does not need Package body. SQL>CREATE OR REPLACE PACKAGE pack_am Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 Bde: By Mr. Krishna Reddy PL/SQL AS PROCEDURE add_nuni(m IN NUMBER,n IN NUMBER); FUNCTION mul_num(x IN NUMBER.y IN NUMBER) RETURN oumber; result NUMBER; END pack_am; SQL> CREATE OR REPLACE PACKAGE BODY pack_am AS PROCEDURE add_num(m IN NUMBER,n IN NUMBER) Is BEGIN result:=n+n; display(‘The sum of m,n is '|result); END add_numy, FUNCTION mul_num(x IN NUMBER.y IN NUMBER) RETURN number Is BEGIN result=xty; RETURN(result); END miul_nuin; END pack_am; SQL>CREATE OR REPLACE PACKAGE pack_eg AS FUNCTION exp(pdoj IN DATE) RETURN NUMBER; FUNCTION gross(pbasic IN NUMBER) RETURN NUMBER; END pack_eg; SQL>CREATE OR REPLACE PACKAGE BODY pack eg AS FUNCTION exp(pdoj IN DATE) RETURN NUMBER Is BEGIN RETURN(tound(MONTHS_between(SYSDATE,pdoj)/12)); END exp: FUNCTION gross(pbasic IN NUMBER) RETURN NUMBER Is BEGIN RETURN(pbasict phasic*0.45+pbasic*0.35-pbasic*0.15); END gross; END pack_eg; SQL>select pack_eg.exp('l4-jun-95),pack_eg.gross(1000) from dual; SQL> select ename,hiredate,pack_eg.exp(hiredate), eee Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy sal,pack_eg.gross(sal) : from emp WHERE pack_eg.exp(hiredate)>30; PL/SQL Eunction over loading ‘SQL>CREATE OR REPLACE PACKAGE pack_fo AS FUNCTION fuun_add(m IN NUMBER,n IN NUMBER) RETURN NUMBER; FUNCTION fiun_add(x IN VARCHAR2,y IN VARCHAR2) RETURN VARCHAR2; END pack_fo; SQL>CREATE OR REPLACE PACKAGE BODY pack _fo AS FUNCTION fun_add(m IN NUMBER,n IN NUMBER) RETURN NUMBER Is BEGIN RETURN(m#n); END fun_add; FUNCTION fun_add(x IN VARCHAR2,y IN. VARCHAR?) RETURN VARCHAR2 Is BEGIN RETURN(«(!' ly); END fiun_add; END pack_fo; SQL> SELECT pack_fo.fiun_add(100,200) "Res|,pack_fo.fun_add((KRISHNA' ORACLE) "Res2” from dual; Package will be stored in USER_SOURCE SQL> SELECT TEXT FROM USER_SOURCE, WHERE NAME=PACK ] Remove the package:~ SQL>DROP PACKAGE ; SQL>CREATE OR REPLACE PACKAGE pack_bal AS PROCEDURE upé_bal(paceno IN keb_ace_tab.accno%TYPE, pttype IN keb_tran_tab.ttype%TYPE, pamt IN kcb_tran_tab.amt%TYPE), FUNCTION chk_bal(paceno IN keb_ace_tab.accno%TYPE, pamt IN keb,tran_tab.amt%TYPE) RETURN BOOLEAN; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 1286: By y Mr. ‘Krishna Reddy FUNCTION finow(paceno IN keb_acc_tab.accno%TYPE) ~' RETURN NUMBER, FUNCTION ftwa(paceno IN keb_ace.tab.aceno%TYPE) RETURN NUMBER; bai keb_ace_tab.bal%TYPE; END pack_bal; SQL> PACKAGE BODY pack_bal AS PROCEDURE upd_bal{paceno IN keb_ace_tab.accno%TYPE, pitype IN keb_tran_tab.ttype%TYPE, pamt IN keb_tran_tab.amt%TYPE) 1s BEGIN SELECT bal INTO cbal FROM keb_ace_tab WHERE aceno=paceno; AE upper(pttype)"D' THEN cbal:=cbaltpamt; elsif upper(pttype)="W' THEN ebale=cbal-pamt; ENDIF; UPDATE keb_ace_tab SET bal=cbal END upd_bal; FUNCTION chk_bal(paceno IN keb_ace_tab.aceno%TYPE, pamt IN keb_tran_tab.amt%TYPE) RETURN BOOLEAN Is vacetype keb_ace_tab.acctype%type: BEGIN SELECT acetype, bal INTO vacctype,cbal FROM keb_ace_tab WHERE cbal:=cbal-pamt; AF chal<5000 AND vacety RETURN(false); ELSIF cbal<10000 AND vacctypeC’ THEN RETURN(Ealse); ELSE RETURN(true); END IF; IND chk_bal; FUNCTION fnow(paceno IN keb_ace_tab.accno%TYPE) RETURN NUMBER Is Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 By Mr. Krishna Reddy vnow NUMBER; BEGIN SELECT count(*) INTO vnow FROM keb_tran_tab WHERE aceno=paccno AND ttype="W" AND ‘TO_CHAR(ot/DD-MON-YY)= ‘TO_CHAR(sysdate,DD-MON-YY') AND EXISTS (SELECT ‘krishna’ FROM keb_ace_tab WHERE aceno=paceno AND acctype='S'); RETURN(vnow); END fhow; FUNCTION ftwa(paceno IN keb_ace_tab.accno%TYPE) RETURN NUMBER Is vtwa NUMBER; BEGIN : SELECT sum(amt) INTO viwa FROM keb_tran_tab WHERE accno=paccno-AND ttype="W' AND TO_CHAR(dot,DD-MON-YY!)= ‘TO_CHAR(sysdate,DD-MON-YY') AND EXISTS (SELECT ‘krishna’ FROM keb_ace_tab WHERE aceno=paceno AND acctype='S'); IF viwa IS NULL THEN vuwa:=0; END IF; RETURN(wtwa); END ftwa; END pack_bal; Dynamic Cursor in package SQL>CREATE OR REPLACE PACKAGE se_fin Is type r_comp is record (deptno emp.deptno%type, ‘ename emp.ename%type, hiredate emp.hiredate%type, sal emp.sal%type, total_sal emp.sal%type); TYPE comp_rc IS REF CURSOR, RETURN r_comp; a Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 1:88:: By Mr. Krishna Reddy FUNCTION fun_emp(p_deptno NUMBER) RETURN comp_re; END se_fin ; SQL> CREATE OR REPLACE PACKAGE BODY sc_fin Is FUNCTION fun_emp(p_deptno NUMBER) RETURN comp_re Is ¢_emp sc_im.comp_res v_saise NUMBER; BEGIN IF p_deptno>=$0 THEN v_raise :=1.4; ELSIF p_deptno=30 THEN v_raise “1.3; ELSIF p_deptno=20 THEN v_raise :=1.2; ELSE v_raise:=1.1; ENDIF; c_emp FOR SELECT deptno,ename,hiredate,sal, v_raise*(sak+nv{(comm,0)) total_sal FROM emp WHERE deptno=p_deptno; RETURN c_emp; END fuun_emp; END sc_fin; Dynamic SQL Within PL/SQL, you can execute any kind of SQL statement(even data definition and data control statements) In PL/SQL, such statements cannot be executed statically. ‘when we want to execute a SQL data definition statement (such as CREATE) A data control statement (such as GRANT). EXECUTE IMMEDIATE -- ‘The EXECUTE IMMEDIATE statement prepares and immediately executes a dynamic SQL statement or an anonymous PL/SQL block. syntax EXECUTE IMMEDIATE dynamic_string By Mr. Krishna Reddy | i $QL>CREATE OR REPLACE PROCEDURE drop_table (table_name IN VARCHAR2) AS BEGIN EXECUTE IMMEDIATE 'DROP TABLE ‘j table_namell' PURGE’; END drop_table; SQL>CREATE OR REPLACE PROCEDURE proc_tg AS BEGIN FOR i IN (SELECT ‘GRANT SELECT ON 'itable_name|'to krishna ' cmd FROM user_tables) LOOP execute immediate icmd; END LOOP; EXCEPTION when others then dbms_output-put_ine(error'jsubstr(salerrm, 1,250); END PROC_1G; SQL> CREATE OR REPLACE PROCEDURE proc_tab_revoke AS BEGIN FORi IN (SELECT ‘REVOKE SELECT ON ‘itable_namel FROM krishna ' emd FROM user_tables) END LOOP; EXCEPTION when others then CREATE OR REPLACE PROCEDURE outbound AS CURSOR cl 1S select empno,ename,job,hiredate,saldepino Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 PL/SQL FROM EMP; 1d UTL_FILE.FILE_TYPE; BEGIN Id:-UTL_FILE. FOPENCKRISHNA’ fempf.txt'W); FORiINel LOOP UTL_FILE.PUT_LINE(id,,EMPNO}!, i. ENAMEf, i,j0bI, i-hiredate)ji.sal[Ii.deptno), END LOOP, UTL_FILEFCLOSE(d); END outbound; Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 391:

You might also like