You are on page 1of 425

First steps towards oracle 10g

Let us make database practical

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

What is data actually? Data: It is stored representation of objects and events that have meaning and importance in the users environment. Data can be structure or unstructured. Structured -> Student Name, Address.. Unstructured -> StudentPhoto, Addrmap. Representation of data: King 10 5500 10-02-06 Blake 10 4500 02-03-05 Clark 20 3500 15-05-04 Smith 30 1800 06-10-00 Miller 20 1100 22-12-03 Taylor 30 3500 What is information actually? Information: It is data that is in processed form, such that it increases the knowledge of the person who uses the data. Representation of Information: Organization: Sekhar. Employees Information Date: 28 August 2009. Place: Thimmamdoddi Salary 5500 4500 3500 1800 1100 3500 DOJ 10-02-06 02-03-05 15-05-04 06-10-00 22-12-03

Name Department King 10 Blake 10 Clark 20 Smith 30 Miller 20 Taylor 30 What is Metadata Actually? Metadata:

It is the data which describes the properties or characteristics of end users data and the context of the data. Metadata properties can include information such as: Data Name. Definitions. Length or size. Values allowed. 2 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Source of data. Ownership. Metadata and data are always separate. Metadata enables the database designers and programmers to understand exactly in which form the data should exist within the system. Metadata for Employees Information Data Item Specification Field Type Name Empname Alpha Numeric DeptNo Integer EmpSal Decimal HireDate Date Database Management systems Database management systems are software that is used to create, maintain, and provide controlled access to user database. Database Management systems should provide systematic method of Creating the database. Updating the database. Storing the database. Retrieving of data from database. Expected Features of DBMS Software Enable end users and application programmers to share the data. Enable data shared among multiple applications. Should not propagate and store data in new files for every new application. Should provide facility for.. Controlling data access. Enforce data integrity. Manage concurrency control. Restoring the data in system failures. Length 30 2 7 Min value Max

10 90 1500 50000

Database Management Systems Evolution First time introduced during 1960s. Relational model first defined by e.f. codd (IBM) in 1970.

Objective behind Evolution. Provide greater independence between programs and data. Reduce the maintenance cost of software. 3 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Manage complex data types and structures. Provide easier and faster access to data even for novice users. Provide future sensation for powerful platforms for decision support systems and expert systems. Different Database Models Flat file DBMS. Hierarchical DBMS. Network DBMS. Relational DBMS. Object-Oriented DBMS. Object-Relational DBMS. Data Warehousing. Web-Enabled DBMS.

Database Models and Their Timelines 1960 Flat File Hierarchical Network Relational Object-Oriented Object-Relational Data warehousing Web-Enabled 1970 1980 1990 200

What is Meant by Database Application It is an application program or set of related programs that is used to perform a series of activities on behalf of database users. The database application activities include Create -> Add New data to database. Read -> Read current database data. Update -> Update or modify current database data. Delete -> Delete current data from the database.

Database as per Oracle As per oracle database is a collection of data in one or more number of files. 4 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

The database is a collection of logical structures and physical structures which are integrated and configured for the integrity of the system.

Logical Structures: In design state the systems is represented in the form of entity relationship model, or DFDs or UML diagrams. In the database state it is representation of the actual metadata of the database management system software which will be in the form of table spaces, data dictionary objects etc...

Physical Structures: In this system is represented in the form of tables, indexes, synonyms, views etc. as per the database software.

Database should have the ability to provide access to external tables for files outside the database as if the rows in the files were rows in the table. The course of developing an application consists of. Creating structures ( Tables & Indexes ) Creating synonyms for the object Names. View objects in different database. Restricting access to the objects. Within the oracle database, the basic structure is a table used to store data.

The Different Tables Supported by Oracle Database are. Relational tables. Object relational tables. Index organized tables. External tables. Partitioned tables. Materialized views. Temporary tables. Clustered tables. Dropped tables.

Note: A database application ma contains all the above categories of tables or may contain few depending on the application type. As the data in the database grows the speed and performance of database decreases. The following indexes are provided oracle products for speed of database. B+ Tree indexes 5 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Bitmap indexes Reverse key indexes Function based indexes. Partitioned indexes. Text indexes. Domain indexes.

Let us understand the Oracle Style for data storage All the logical structures in the database must be stored within the database only. Oracle maintains a data dictionary, which records metadata about all the database objects. The database objects which need physical storage space on the computer system, are allocated space within a table space. Table Space: It is a logical storage unit within oracle database and is not visible in the file system of the machine on which the database resides. The table space builds the bridge between the oracle database and the file system in which the tables or index data is stored. It consists of one or more number of data files of the database. A data file can be part of one and lonely one table space. There are three types of table spaces in oracle: Permanent table spaces. Undo table spaces. Temporary tables spaces. Each table or index stored in an oracle database belongs to a table space. As per oracle 10g minimum tow table spaces are compulsory they are system and SysAux table space, both used to support oracle internal management. The system table space is always available when a database is open and cannot be taken offline. The system table space stores the data dictionary or their base tables, respectively. In 10g a big file table space can be created, which can grow to the size of tera bytes of space on disk.

The general Architecture of Oracle

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

General Facts about Relational Model The model was first outlined by Dr. E. F. Codd in 1970. The components of the model are.. Collection of objects or relations that store the data. A set of operators that can act on the relations to produce other relations. Data integrity for accuracy and consistency. A relational database should use relations or two dimensional tables to store information. System and Data Modeling Importance Data Models: Data models help in exploring ideas and improve the understanding of the database design for both developers and system designers. Purpose of Data Models: .communicate .Categorize .Describe .Specify .Investigate .Evolve .Analyze .Imitate

Objective of the models: To produce a model that fits a multitude of users. Should be understood by an end user. Should contain sufficient details for a developer to build the database system.

Relational Database Properties: Should be accessed and modified by executing structured query language (SQL) statements only. Should contain a collection of tables with no physical pointers. Should use a set of operators. Need not specify the access route to the tables and data. There is no need to identify how the data is arranged physically. How to Communicate with RDBMS? The structured query language is used to communicate with RDBMS. Generic Features of Structured Query Language It allows the user to communicate with the server. 7 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

It is highly efficient. It is easy to learn and use. Functionally complete, by allowing the user to Define the system. Retrieve and manipulate the data from the system. The general dialect is similar to English language. The entire structure is built on collection of statements. It is platform independent and architecture independent.

About Oracle 8 It is the first object capable database. It provides a New engine which supports Object oriented programming. Complex data types. Complex business objects. Full compatibility with the relational concepts. It provides OLTP applications, with Sharing of runtime data structures. Large buffer caches Deferrable constraints. It supports client server and web based application which are distributed and multi tired. It can scale tens and thousands of concurrent users. About Oracle 8i It is the database of internet computing. It provides advanced tools to manage all types of data in web sites. The internet file system (IFS) combines the power for ease of use a file system. End users can easily access files and folders in oracle IFS via a variety of protocols. If enables the users to web-enable their multimedia data. It provides full, native integration with Microsoft Transaction Server (MTS). It provides high performance internet platform for e-commerce and data warehousing. The core pieces of oracle internet platform are Browser based clients to process presentation. Application servers to execute business logic and serve presentation logic to browser based clients. Databases to execute database intensive business logic and serve data. Entity Relationship Model In an effective system data should be divided into discrete categories or entities. An ER-Model is an illustration of various entities in a business and the relationships between them. It is built during the analysis phase of the system developing life cycle. ER-Model separates the information required & the business from the activities performed. 8 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ER-Model Benefits It documents 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. It offers an effective framework for integrating multiple applications. Key Components in ER-Model Entity It is a thing of significance about which the information needs to be known. Attributes It is something that describes or qualifies an entity. Each attribute may be mandatory or optional. Relation It is any rule or situation that should be satisfied between the attribute and attributes of an entity or entities. Relational Database Terminology Row or Tuple It represents all data required for a particular instance in an entity. Each row in an entity is uniquely identified by declaring it as primary key or unique. The order of the rows is not significant, while retrieving the data. Column or Attribute It represents one kind of data in a table vertically collected. The column order is not significant when storing the data. Field It can be found at the intersection of a row and a column. A field can have only one value, or may not have a value at all. The absence of value in oracle is represented as null. Relating Multiple Tables Each table should contain 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 by using the foreign keys. A foreign key is a column or a set of columns that refer to a primary key in the same table or another table. Structured Query Language Statements in Oracle Oracle SQL complies with industry accepted standards. The different categories into which the sql statements fall are as follows. Data Retrieval Statement SELECT statement. 9 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Data Manipulation Language Statements INSERT statement. UPDATE statement. DELETE statement. Data Definition Language Statements CREATE statement. ALTER statement. DROP statement. RENAME statement. TRUNCATE statement.

Transaction Control Language Statements COMMIT statement. ROLLBACK statement. SAVEPOINT statement. Data Control Language Statements GRANT statement. REVOVKE statement. About the SQL Buffer 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. The 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 line. Every statement of sql should be terminated using semi colon ;. One sql statement can contain only one semi colon. To run the previous or current sql statement in the buffer type / at sql prompt. To open the sql editor type ED at sql prompt. Connecting to Oracle or sql*plus Double click the sql*plus short cut on the desktop. Start -> Run -> Type sqlplus or sqlplusqw in open box and click ok. Start -> Programs -> Oracle -> Application Development -> sql*plus. In the login box or login prompt type the user name and password as supplied by the administrator. The host string is optional and is provided by the administrator. Creating and Managing Tables. An oracle database is a collection of multiple data structures. 10 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

These data structures are called as database objects. The major database objects associated with database programmer are.. Table -> Used to store data, basic unit in oracle. View -> Logically represents subsets of data from one or more tables. Sequence -> Used to generate primary key values. Synonym -> Used to give alternate names to objects. Index -> It is used to improve the performance of some queries.

Tables in Oracle 8 / 9 / 10 Tables can be created at any time, even when the users are using the database. Size of the table need not be specified. The structure of the table can be modified online. Rules to Create a Table: The user should have permission on create table command, and storage area should be allocated. The table name should begin with a letter and can be 1 30 characters long. Table names can contain combination of. A Z (OR) a z (OR) 0 9 (OR) _, $, # Names cannot be duplicated for another object name in the same oracle server. Name cannot be oracle servers reserved words. Table names are not case sensitive in oracle. Table is a collection of attribute names and oracle data types and required which along with constraints. Create Table Statement Syntax SQL>create table <table_name> ( Column_name1 <dataType> (width), Column_name2 <dataType> (width), Column_nameN <dataType> (width) ); Note All data types may not have the width property. No two columns in the same table can have the same name.

Building Blocks of SQL Statements Data types. Literals. Format Models. 11 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Nulls. Pseudo Columns. Comments. Database Objects. Schema objects names and qualifiers. Syntax for schema objects. Parts of sql statements.

Data Types in Oracle Each value in oracle is manipulated by a data type. The data type associates a fixed set of properties with that value stored. 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. Built-in Data Types CHARACTER DATA TYPES. NUMBER DATA TYPES. LONG AND RAW DATA TYPES. DATETIME DATA TYPES. LARGE OBJECT DATATYPES. ROWID DATATYPES.

Character Data Types They store character data, which can be alphanumeric data collection. The information can be Words or free-form text. Database or notional character set. This data type is less restrictive than other data types and has very few properties. The data is stored in string with byte collections as values. The information can belong to either 7 Bit ASCII (American standard code for information interchange) character set. EBCDIC (Extended binary coded decimal interchange code) Oracle supports both single & multi byte character sets. The different character data types are: .Char .varchar2 .Nchar .nvarchar2 Char Data Type It specifies fixed length character strings. The size should be specified. If the data is less than the original specified size, blank pads are applied. The default length is 1 byte and the maximum is 2000 bytes. 12 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

The size of a character can range from 1 byte to 4 bytes depending on the database character set.

Nchar Data Type First time defined in oracle 9i, and contains Unicode data only. Maximum length is determined by the national character set definition. Maximum size is 2000 bytes and size has to be specified. Padded if data is shorter than specified. Varchar2 Data Type Specifies the variable length character string. Minimum size is 1 byte and the maximum size is 4000 bytes. It occupies only that space for which the data is supplied. Nvarchar2 Data Type First time defined in oracle 9i. It is defined for Unicode data only. The minimum size is 1 byte and maximum size is 400 bytes.

Numeric Data Types Number Data Type It stores zero, positive and negative fixed and floating point numbers. The range of magnitude is 1.0 * 10-130 to 9.9.9*10+125 The general declaration is . Number (p, s) P -> It specifies the precision, i.e.., the total number of digits (1 to 38). S -> It specifies the scale, i.e., the number of digits to the right of the decimal point, can range from -84 to 127. Float Data Type It facilitates to have a decimal point anywhere from the first to the last digit, or can have no decimal point at all. The scale value is not applicable to floating point numbers, as the number of digits that can appear after the decimal point is not restricted. Syntax FLOAT -> It specifies a floating point number with decimal precision 38 or binary precision of 126. Float (b) -> it specifies a floating point number with binary precision b. The precision can range from 1 to 126. To convert from binary to decimal precision multiply b by 0.30103. 13 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

To convert from decimal to binary precision multiply the decimal precision by 3.32193. The maximum of 126 digits of binary precision is roughly equivalent to 38 digits of decimal precision.

Long Data Type This data type stores variable length character strings. It is used to store very lengthy text strings. The length of long values may be limited by the memory available on the computer. Long columns can be referenced in Select lists Set clause of update statements. Values clause of insert statements. Restrictions A single table can contain only one long column. Object types cannot be created on long column attribute. Long columns cannot appear in where clauses or in integrity constraints. Indexes cannot be created on long columns. Long can be returned through a function, but not through a stored procedure. If can be declared in a pl/sql unit but cannot be referenced in sql.

Date & Time Data Types Date Data Type It is used to store date and time information. The dates can be specified as literals, using the Gregorian calendar. The information revealed by date is Century, year, month, date, hour, minute, second The default date format in oracle is dd-mon-yy, and is specified in nls_date_format variable. The default time accepted by oracle date is 12.00.00 am (midnight). The default date accepted by oracle date is the first day of the current month. The date range provided by oracle is January 1, 4712 BC to December 31, 9999 AD. Timestamp Data Type It is an extension of the date data type. It stores the data in the form of Century, year, month, date, hour, minute, second Syntax Timestamp[ {Factional-seconds-precision} ] Factional-seconds-precision optionally specifies the number of digits in the fractional part of the seconds to be considered in date time field. 14 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

It can be a number in the range of 0 -9, with default as 6.

Raw & Long Raw Data Types Raw and long raw data types are intended for storage of binary data or byte strings. Raw and long raw are variable length data types. They are mostly used to store graphics, sounds, scanned documents etc. The oracle converts the raw & long raw data into hexadecimal form. Each hexadecimal character represents four bits of raw data. Large Object (lob) Data Types The built in lob data types are * BLOB * CLOB * NCLOB These data types stored the data internally. The bfile is a lob which stores the data externally. The lob data types can store large and unstructured data like text, image, video and spatial data. The maximum storage size is up to 4 GB. Lob columns contain lob locators, which can refer to out-of-line or in-line lob values. Lobs selection actually returns the lobs locator. Blob Data Type It stores unstructured binary large objects. They are bit streams with no character set semantics. They are provided with full transactional support with special methods. Clob Data Type It stores single byte and multi byte character data. Both fixed width and variable width character sets are supported. They are provided with full transactional support with special methods. Nclob Data Type It stores Unicode data using the national character set. Bfile Data Type It enables access to binary file lobs which are stored in the file systems outside oracle. A bfile column or the attribute stores the bfile locator. The bfile locator maintains the directory alias and the filename. The binary file lobs do not participate in transactions and are not recoverable. The maximum size is 4 GB. Rowid Data Type Each row in the database has an address. The rows address can be queried using the pseudo column rowid. Rowids efficiently support partitioned tales and indexes. 15 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Illustrative Example to Create a Table

SQL> create table students 2( 3 studid number (6), 4 fname varchar2 (30), 5 lname varchar2 (30), 6 DOB date, 7 doj date, 8 fees number (7, 2), 9 gender varchar2 (1) 10); Table created. SQL> Ed Wrote file afiedt.buf 1 create table labspecdification 2( 3 prodid number (6), 4 prodphot blob, 5 prodgraphic bfile, 6 prodesc long 7* ) SQL> / Table created.

Populating the Data into Tables Insert statements The insert statement is used to add rows to a Relational table. Views base table. A partition of a partition table. A sub partition of a composite partitioned table An object table An object views base table. Insertion of data into a table can be executed in two ways. Conventional insert. Direct-path inserts. In conventional insert statement, oracle reuses free space in the table into which the data in being inserted and maintains referential integrity constraints. 16 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

In direct-path insert, oracle appends the inserted data after existing data in the table; the free space is not reused. Syntax SQL> insert into <table_name> (col1, col2,) Values (value1, value2,) Let us understand the Different Situations Inserting Data into All Columns of a Table

SQL> insert into students 2 values 3( 4 1234, 5 SAMPATH, 6 KUMAR, 7 29-JAN-80', 8 30-MAR-95', 9 25000, 10 M 11); 1 row created.

In this case the values should be provided to all the columns that exist inside the table. The order of values declared in the values clause should follow the original order of the columns in table. The char, varchar and date type data should be declared in single quotes. Numerical information can be applied normally.

Inserting data into required columns


SQL> ED Wrote file afiedt.buf 1 insert into students 2( 3 studID, 4 fname, 5 lname, 6 doj, 7 genders 8) 9 values 10 ( 11 1235,

17

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

12 RAJ, 13 KUMAR, 14 20-FEB-85', 15 M 16*) SQL> / 1 row created.

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 clause 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 values can be inserted in two ways. Implicit -> Omit the column from list. Explicit -> Specify the null keyword. It is better to specify Empty string only for character strings and dates. The targeted column should not be set with not null constraint.

SQL> Ed Wrote file afiedt.buf 1 insert into students 2( 3 studID, 4 fname, 5 lname, 6 DOB, 7 doj, 8 fees, 9 genders 10) 11 values 12 ( 13 1234, 14 Krishna, 15 null, 16 , 17 28-feb-04', 18 null, 19 M 20*) SQL> / 1 row created.

Inserting Special Values into Table 18 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Sysdate Function It is pseudo column provided by the oracle. The function returns the current date and time from the system clock. User Function It is special function, which records the current user name.
SQL> Ed Wrote file afiedt.buf 1 insert into students 2( 3 studID, 4 fname, 5 doj, 6 fees, 7 genders 8) 9 values 10 ( 11 1234, 12 Mohan, 13 sysdate, 14 25000, 15 M 16*) SQL> / 1 row created.

Supplying Data at Run Time Substitution Variables These variables are used to store values temporarily. 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 executed. The double ampersand substitution variable applies for all instances until that sql statement is existing. Single Ampersand Substitution Variable
SQL> insert into students 2( 3 studID, 4 fname, 5 lname,

19

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

6 DOB, 7 fees 8) 9 values 10 ( 11 &studno, 12 &firstname', 13 &lastname', 14 &dateofbirth', 15 25000 16); Enter value for studno: 1236 Old 11: &studno, New 11: 1236, Enter value for firstname: Suresh Old 12: '&firstname', New 12: 'Suresh', Enter value for lastname: babu Old 13: '&lastname', New 13: 'babu', Enter value for dateofbirth: 02-jan-90 Old 14: '&dateofbirth', New 14: '02-jan-90', 1 row created.

Double Ampersand Substitution Variable


SQL> insert into students 2( 3 studID, 4 fname, 5 lname, 6 DOB, 7 doj, 8 fees, 9 genders 10) 11 values 12 ( 13 &studno, 14 &firstname', 15 &lastname', 16 &dateofbirth', 17 sysdate, 18 &&fess, 19 &gender' 20); Enter value for studno: 1237 Old 13: &studno, New 13: 1237, Enter value for firstname: laxmi Old 14: '&firstname', New 14: 'laxmi',

20

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Enter value for lastname: babu Old 15: '&lastname', New 15: 'babu', Enter value for dateofbirth: 02-feb-96 Old 16: '&dateofbirth', New 16: '02-feb-96', Enter value for fess: 20000 Old 18: &&fess, New 18: 20000, Enter value for gender: M Old 19: '&gender' New 19: 'M' 1 row created. SQL> / Enter value for studno: 1238 Old 13: &studno, New 13: 1238, Enter value for firstname: Suresh Old 14: '&firstname', New 14: 'Suresh', Enter value for lastname: babu Old 15: '&lastname', New 15: 'babu', Enter value for dateofbirth: 02-mar-96 Old 16: '&dateofbirth', New 16: '02-mar-96', Old 18: &&fess, New 18: 20000, Enter value for gender: M Old 19: '&gender' New 19: 'M' 1 row created.

Saving the SQL Buffer Text as SQL Script. Method 1 At the sql prompt use the save command including the required path and file name. SQL>save c:\myscripts\first.sql To replace the existing sql script file with new information. SQL>save c:\myscripts\first.sql replace Method 2 Open any text editor type the required sql statement. Save the sql statement in the required drive and folder using sql extension. Data Retrieval Standards Using SELECT Statement Querying the Data from Tables Query It is an operation that retrieves data from one or more tables or views. 21 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Select Statement The select statement is used to retrieve data from one or more Tables. Object tables. Views. Object views. Materialized views. Prerequisites The user must have the select privileges on the specified object. The select any table allows to select the data from any recognized object. Capabilities of SQL SELECT Statement The select statement can be used to select or retrieve data from the object using any one of the following criteria. SELECTION PROJECTION JOIN Selection It chooses the rows in a table that are expected to be returned by a query. Projection It chooses the columns in a table that are expected to return by a query. Join It chooses the data in from one or more number of tables by creating a link between them. Basic Select Syntax SQL>select [Distinct] [*] {column1 [alias],} From table_name; Select keyword identifies columns. From clause identifies tables. Select -> Specifies a list of columns. Distinct -> Suppresses duplicates. * -> Projection operator to select all columns from the table. Column -> Selects the named column. Alias -> Gives selected columns alternate column name. From table_name -> specifies the table containing the columns. Sample Database Used Table Name: DEPT Column Name Deptno Dname Loc 22 Data Type Number Varchar2 Varchar2

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Table Name: EMP Column Name Empno Ename Deptno Job Sal Comm Mgr Hiredate Data Type Number Varchar2 Number Varchar2 Number Number Number Date

Table Name: SALGRADE Column Name Hisal Losal Grade Data Type Number Number Number

ER Model for Class Room Sessions

Retrieving Data from all Columns of a Table For this purpose the projection operator * is used. The operator projects data from the entire column existing in the table with all records. The data is displayed in a table format Illustrative Examples
SQL> select * 2 from EMP; EMPNO ENAME ---------- ---------7369 SMITH 7499 ALLEN 7521 WARD 7566 JONES 7654 MARTIN 7698 BLAKE

JOB --------CLERK SAESMAN SALESMAN MANAGER SALESMAN MANAGER

MGR HIREDATE -------- --------7902 17-DEC-80 7698 20-FEB-81 7698 22-FEB-81 7839 02-APR-81 7698 28-SEP-81 7839 01-MAY-81

SAL ---------800 1600 1250 2975 1250 2850

COMM DEPTNO ---------- ---------20 300 30 500 30 20 1400 30 30

23

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7782 CLARK 7788 SCOTT 7839 KING 7844 TURNER 7876 ADAMS 7900 JAMES 7902 FORD 7934 MILLER 14 rows selected. SQL> select * 2 from dept;

MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK

7839 09-JUN-81 7566 19-APR-87 17-NOV-81 7698 08-SEP-81 7788 23-MAY-87 7698 03-DEC-81 7566 03-DEC-81 7782 23-JAN-82

2450 3000 5000 1500 1100 950 3000 1300

10 20 10 30 20 30 20 10

DEPTNO DNAME LOC ---------- -------------- ------------10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON 4 rows selected. SQL> select * 2 from salgrade; GRADE LOSAL HISAL ---------- ---------- --------1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 9999 5 rows selected.

The select statement can be typed in one line or can be split into multiple lines.

Retrieving Data from Specific Columns


SQL> select Empno, ename, Sal 2 from EMP; EMPNO ENAME ---------- ---------7369 SMITH 7499 ALLEN 7521 WARD 7566 JONES 7654 MARTIN 7698 BLAKE 7782 CLARK 7788 SCOTT SAL ---------800 1600 1250 2975 1250 2850 2450 3000

24

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7839 KING 7844 TURNER 7876 ADAMS 7900 JAMES 7902 FORD 7934 MILLER 14 rows selected.

5000 1500 1100 950 3000 1300

SQL> select ename, job, Sal, deptno 2 from EMP; ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB SAL DEPTNO ------------------ ---------CLERK 800 20 SALESMAN 1600 30 SALESMAN 1250 30 MANAGER 2975 20 SALESMAN 1250 30 MANAGER 2850 30 MANAGER 2450 10 ANALYST 3000 20 PRESIDENT 5000 10 SALESMAN 1500 30 CLERK 1100 20 CLERK 950 30 ANALYST 3000 20 CLERK 1300 10

14 rows selected. SQL> select deptno, dname, loc 2 from dept; DEPTNO DNAME ----------------------10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS 4 rows selected. SQL> select hisal, losal, grade 2 from salgrade; HISAL ---------1200 1400 2000 3000 9999 LOSAL GRADE ---------- ---------700 1 1201 2 1401 3 2001 4 3001 5 LOC ------------NEW YORK DALLAS CHICAGO BOSTON

25

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

5 rows selected. SQL> select EMPno, ename, sal, hiredate 2 from EMP; EMPNO ENAME SAL HIREDATE ---------- ---------- ---------- --------7369 SMITH 800 17-DEC-80 7499 ALLEN 1600 20-FEB-81 7521 WARD 1250 22-FEB-81 7566 JONES 2975 02-APR-81 7654 MARTIN 1250 28-SEP-81 7698 BLAKE 2850 01-MAY-81 7782 CLARK 2450 09-JUN-81 7788 SCOTT 3000 19-APR-87 7839 KING 5000 17-NOV-81 7844 TURNER 1500 08-SEP-81 7876 ADAMS 1100 23-MAY-87 7900 JAMES 950 03-DEC-81 7902 FORD 3000 03-DEC-81 7934 MILLER 1300 23-JAN-82 14 rows selected.

The column names need not be in the same order as table. The column should be separated using comma. The column names can be separated onto different lines within the sql buffer. The casing of column names is not important.

Column Heading Defaults The default justification of the data after it is retrieved from the table is Left -> Date and character data. Right -> Numeric data. The default display of the data is always is upper casing. The character and date column headings can be truncated, but number columns cannot be truncated. Applying Arithmetical Operations Arithmetic expressions can be implemented through select statement. Arithmetic expressions can be implemented to.. Modify the way the data is displayed. Perform calculations. Implement what if scenarios. An arithmetic expression can contain Simple column names Constant numeric values Arithmetic operators Arithmetic operators 26 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

The arithmetic operators can be used to create expressions on number and date data type columns. The arithmetic operators supported are Addition -> + Subtraction -> Multiply -> * Divide -> / 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 2 from EMP; EMPNO ENAME SAL SAL+500 ---------- ---------- ---------- ---------7369 SMITH 800 1300 7499 ALLEN 1600 2100 7521 WARD 1250 1750 7566 JONES 2975 3475 7654 MARTIN 1250 1750 7698 BLAKE 2850 3350 7782 CLARK 2450 2950 7788 SCOTT 3000 3500 7839 KING 5000 5500 7844 TURNER 1500 2000 7876 ADAMS 1100 1600 7900 JAMES 950 1450 7902 FORD 3000 3500 7934 MILLER 1300 1800 14 rows selected. SQL> select EMPno, ename, sal, sal - 1000 2 from EMP; EMPNO ENAME SAL SAL-1000 ---------- ---------- ---------- ---------7369 SMITH 800 -200 7499 ALLEN 1600 600 7521 WARD 1250 250 7566 JONES 2975 1975 7654 MARTIN 1250 250 7698 BLAKE 2850 1850 7782 CLARK 2450 1450 7788 SCOTT 3000 2000 7839 KING 5000 4000 7844 TURNER 1500 500 7876 ADAMS 1100 100 7900 JAMES 950 -50 7902 FORD 3000 2000 7934 MILLER 1300 300

27

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

14 rows selected.

Operator precedence Multiplication and division take priority over addition and subtraction ( *, /, +, - ) 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 2 from EMP; EMPNO ENAME SAL (12*SAL) +100 ---------- ---------- ---------- -----------7369 SMITH 800 9700 7499 ALLEN 1600 19300 7521 WARD 1250 15100 7566 JONES 2975 35800 7654 MARTIN 1250 15100 7698 BLAKE 2850 34300 7782 CLARK 2450 29500 7788 SCOTT 3000 36100 7839 KING 5000 60100 7844 TURNER 1500 18100 7876 ADAMS 1100 13300 7900 JAMES 950 11500 7902 FORD 3000 36100 7934 MILLER 1300 15700 14 rows selected. SQL> select EMPno, ename, Sal, 12 * (Sal + 500) 2 from EMP; EMPNO ENAME SAL 12*(SAL+500) ---------- ---------- ---------- -----------7369 SMITH 800 15600 7499 ALLEN 1600 25200 7521 WARD 1250 21000 7566 JONES 2975 41700 7654 MARTIN 1250 21000 7698 BLAKE 2850 40200 7782 CLARK 2450 35400 7788 SCOTT 3000 42000 7839 KING 5000 66000 7844 TURNER 1500 24000 7876 ADAMS 1100 19200 7900 JAMES 950 17400 7902 FORD 3000 42000 7934 MILLER 1300 21600 14 rows selected.

Handling Null Values 28 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

NULL: It is a value which is. Unavailable Unassigned. Unknown. Inapplicable. A null is not same as zero or blank space. If a row lacks the data for a particular column, than that value is said to be null or to containing null.
SQL> select ename, job, sal, comm 2 from EMP; ENAME JOB SAL COMM ---------- --------- ---------- ---------SMITH CLERK 800 ALLEN SALESMAN 1600 300 WARD SALESMAN 1250 500 JONES MANAGER 2975 MARTIN SALESMAN 1250 1400 BLAKE MANAGER 2850 CLARK MANAGER 2450 SCOTT ANALYST 3000 KING PRESIDENT 5000 TURNER SALESMAN 1500 0 ADAMS CLERK 1100 JAMES CLERK 950 FORD ANALYST 3000 MILLER CLERK 1300 14 rows selected.

If any column value in an arithmetic expression is null, the overall result is also null. The above situations are termed as null propagation and have to be handled very carefully.

SQL> select ename, job, sal, comm, sal + comm 2 from EMP; ENAME JOB SAL COMM SAL+COMM ---------- --------- ---------- ---------- ---------SMITH CLERK 800 ALLEN SALESMAN 1600 300 1900 WARD SALESMAN 1250 500 1750 JONES MANAGER 2975 MARTIN SALESMAN 1250 1400 2650 BLAKE MANAGER 2850 CLARK MANAGER 2450 SCOTT ANALYST 3000 KING PRESIDENT 5000 TURNER SALESMAN 1500 0 1500 ADAMS CLERK 1100 JAMES CLERK 950

29

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

FORD MILLER

ANALYST CLERK

3000 1300

14 rows selected. SQL> select ename, job, sal, comm, 12 * (Sal + comm) 2 from EMP; ENAME JOB SAL COMM 12*(SAL+COMM) ---------- --------- ---------- ---------- ------------SMITH CLERK 800 ALLEN SALESMAN 1600 300 22800 WARD SALESMAN 1250 500 21000 JONES MANAGER 2975 MARTIN SALESMAN 1250 1400 31800 BLAKE MANAGER 2850 CLARK MANAGER 2450 SCOTT ANALYST 3000 KING PRESIDENT 5000 TURNER SALESMAN 1500 0 18000 ADAMS CLERK 1100 JAMES CLERK 950 FORD ANALYST 3000 MILLER CLERK 1300 14 rows selected.

NVL Function The NVL function is used to convert a null value to an actual value. Syntax NVL (Expr1, Expr2) Expr1: It is the source value or expression that may contain null. Expr2: It is the target value for converting null. NVL function can be used to convert any data type; the return value is always the same as the data type of expr1. The data types of the source and destination must match. NVL(comm.,0) NVL(hiredate, 01-jun-99) NVL(job, Not Assigned)
SQL> select ename, sal, comm, sal+nvl (comm, 0) 2 from EMP; ENAME SAL COMM SAL+NVL (COMM, 0) ---------- ---------- ---------- --------------SMITH 800 800 ALLEN 1600 300 1900 WARD 1250 500 1750 JONES 2975 2975

30

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

1250 2850 2450 3000 5000 1500 1100 950 3000 1300

1400

2650 2850 2450 3000 5000 1500 1100 950 3000 1300

14 rows selected. SQL> select ename, sal, comm, (Sal*12) +nvl (comm, 0) 2 from EMP; ENAME SAL COMM (SAL*12) +NVL (COMM, 0) ---------- ---------- ---------- -------------------SMITH 800 9600 ALLEN 1600 300 19500 WARD 1250 500 15500 JONES 2975 35700 MARTIN 1250 1400 16400 BLAKE 2850 34200 CLARK 2450 29400 SCOTT 3000 36000 KING 5000 60000 TURNER 1500 0 18000 ADAMS 1100 13200 JAMES 950 11400 FORD 3000 36000 MILLER 1300 15600 14 rows selected. SQL> select ename, sal, comm, (sal+500) +nvl (comm, 0) 2 from EMP; ENAME SAL COMM (SAL+500) +NVL (COMM, 0) ---------- ---------- ---------- --------------------SMITH 800 1300 ALLEN 1600 300 2400 WARD 1250 500 2250 JONES 2975 3475 MARTIN 1250 1400 3150 BLAKE 2850 3350 CLARK 2450 2950 SCOTT 3000 3500 KING 5000 5500 TURNER 1500 0 2000 ADAMS 1100 1600 JAMES 950 1450 FORD 3000 3500 MILLER 1300 1800

31

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

14 rows selected.

Working with Aliases An alias is an alternate name given for any oracle object. Aliases in oracle are of two types.. Column Alias Column alias renames a column heading in a query. The column alias is specified in the select list by declaring the alias after the column name by using the space separator. Alias heading appears in upper casing by default. The alias should be declared in double quotes if it is against the specifications of naming conversions of oracle. The AS keyword can be used between the column name and alias. An alias effectively renames the select list item for the duration of that query only. An alias cannot be used, anywhere in the select list for operational purpose. Table Alias Table alias renames the original name of the table in a sql statement. Table aliases are very important when working with self joins. The table alias is applied for the current sql statement only. It is an important source when implementing the standards of merge statements, correlated queries and analytic functions.
SQL> select 2 Empno numbers, 3 ename name, 4 Sal "Basic Salary", 5 job Designation 6 from EMP; NUMBERS NAME Basic Salary DESIGNATI ---------- ---------- ------------ --------7369 SMITH 800 CLERK 7499 ALLEN 1600 SALESMAN 7521 WARD 1250 SALESMAN 7566 JONES 2975 MANAGER 7654 MARTIN 1250 SALESMAN 7698 BLAKE 2850 MANAGER 7782 CLARK 2450 MANAGER 7788 SCOTT 3000 ANALYST 7839 KING 5000 PRESIDENT 7844 TURNER 1500 SALESMAN 7876 ADAMS 1100 CLERK 7900 JAMES 950 CLERK 7902 FORD 3000 ANALYST 7934 MILLER 1300 CLERK 14 rows selected.

32

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> select 2 deptno as "Department ID", 3 dname as "department Name", 4 loc as place 5 from dept; Department ID department Nam PLACE ------------- -------------- ------------10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON 4 rows selected. SQL> select 2 hisal as "Maximum Range", 3 losal as "minimum Range", 4 grade 5 from salgrade; Maximum Range minimum Range ------------- ------------- ---------1200 700 1 1400 1201 2 2000 1401 3 3000 2001 4 9999 3001 5 5 rows selected. GRADE

Literals in Oracle A literal and a constant value are synonyms to one another and refer to a fixed data value. The types of literals recognized by oracle are. Text literals. Integer literals. Number literals. Interval literals.

Text Literals It specifies a text or character literal. It is used to specify values whenever text or char appear in Expressions Conditions Sql function Sql statements. 33 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Text literal should be enclosed in single quotes. They have properties of both char and varchar2 data types. A text literal can have a maximum length of 4000 bytes.

Example: Employees Information Managers Specification Nnchar literal Using Literal character Strings A literal that is declared in a select list can be a character, a number, or a date. A literal is not a column name or a column alias. A literal is printed for each row that is retrieved by the select statement. Literal strings of free-form text can be included in the query as per the requirement. Date and character literals must be enclosed within the single quotation marks. Literals increase the readability of the output. A literal is printed for each row that is retrieved by the select statement. Literal strings of free-form text can be included in the query as per the requirement. Date and character literal must be enclosed within the single quotation marks. Literals increase the readability of the output.

SQL> select ename||':'||' Month Salary = '||Sal as salaries 2 from EMP; SALARIES ------------------------------------------------------------------SMITH: Month Salary = 800 ALLEN: Month Salary = 1600 WARD: Month Salary = 1250 JONES: Month Salary = 2975 MARTIN: Month Salary = 1250 BLAKE: Month Salary = 2850 CLARK: Month Salary = 2450 SCOTT: Month Salary = 3000 KING: Month Salary = 5000 TURNER: Month Salary = 1500 ADAMS: Month Salary = 1100 JAMES: Month Salary = 950 FORD: Month Salary = 3000 MILLER: Month Salary = 1300 14 rows selected. SQL> select 2 The Designation of '||ename||' is '||job as Designation 3 from EMP; DESIGNATION ------------------------------------------

34

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

The Designation of SMITH is CLERK The Designation of ALLEN is SALESMAN The Designation of WARD is SALESMAN The Designation of JONES is MANAGER The Designation of MARTIN is SALESMAN The Designation of BLAKE is MANAGER The Designation of CLARK is MANAGER The Designation of SCOTT is ANALYST The Designation of KING is PRESIDENT The Designation of TURNER is SALESMAN The Designation of ADAMS is CLERK The Designation of JAMES is CLERK The Designation of FORD is ANALYST The Designation of MILLER is CLERK 14 rows selected. SQL> select 2 The Annual salary of '||ename||' is '||Sal*12 as annaul_salary 3 from EMP; ANNAUL_SALARY --------------------------------------------------------------------------The Annual salary of SMITH is 9600 The Annual salary of ALLEN is 19200 The Annual salary of WARD is 15000 The Annual salary of JONES is 35700 The Annual salary of MARTIN is 15000 The Annual salary of BLAKE is 34200 The Annual salary of CLARK is 29400 The Annual salary of SCOTT is 36000 The Annual salary of KING is 60000 The Annual salary of TURNER is 18000 The Annual salary of ADAMS is 13200 The Annual salary of JAMES is 11400 The Annual salary of FORD is 36000 The Annual salary of MILLER is 15600 14 rows selected. SQL> select dname||'Department is located at '||loc locations 2 from dept; LOCATIONS ---------------------------------------------------ACCOUNTINGDepartment is located at NEW YORK RESEARCHDepartment is located at DALLAS SALESDepartment is located at CHICAGO OPERATIONSDepartment is located at BOSTON 4 rows selected. SQL> select ename||' Joined the organization on '||hiredate 2 from EMP;

35

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ENAME||'JOINDEDTHEORGANIZATIONON'||HIREDATE -----------------------------------------------SMITH joined the organization on 17-DEC-80 ALLEN joined the organization on 20-FEB-81 WARD joined the organization on 22-FEB-81 JONES joined the organization on 02-APR-81 MARTIN joined the organization on 28-SEP-81 BLAKE joined the organization on 01-MAY-81 CLARK joined the organization on 09-JUN-81 SCOTT joined the organization on 19-APR-87 KING joined the organization on 17-NOV-81 TURNER joined the organization on 08-SEP-81 ADAMS joined the organization on 23-MAY-87 JAMES joined the organization on 03-DEC-81 FORD joined the organization on 03-DEC-81 MILLER joined the organization on 23-JAN-82 14 rows selected. SQL> select 2 ename||' Works in department number '||deptno 3 ||' as '||job 4 from EMP; ENAME||'WORKSINDEPARMENTNUMBER'||DEPTNO||'AS'||JOB -----------------------------------------------------------------------------------------SMITH Works in department number 20 as CLERK ALLEN Works in department number 30 as SALESMAN WARD Works in department number 30 as SALESMAN JONES Works in department number 20 as MANAGER MARTIN Works in department number 30 as SALESMAN BLAKE Works in department number 30 as MANAGER CLARK Works in department number 10 as MANAGER SCOTT Works in department number 20 as ANALYST KING Works in department number 10 as PRESIDENT TURNER Works in department number 30 as SALESMAN ADAMS Works in department number 20 as CLERK JAMES Works in department number 30 as CLERK FORD Works in department number 20 as ANALYST MILLER Works in department number 10 as CLERK 14 rows selected.

Applying Concatenation Operator The concatenation operator links columns to other columns, arithmetic expressions, or constant values. Columns on either side of the operator are combined to make a single output column. The resultant column is treated as an character expression. The concatenation operator is represented in oracle by double pipe symbol (||).
SQL> select Empno||' '||ename||', Designation is' 2 ||job "Employees Information" 3 from EMP;

36

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Employees Information ---------------------------------------------------------------------------7369 SMITH, Designation is CLERK 7499 ALLEN, Designation is SALESMAN 7521 WARD, Designation is SALESMAN 7566 JONES, Designation is MANAGER 7654 MARTIN, Designation is SALESMAN 7698 BLAKE, Designation is MANAGER 7782 CLARK, Designation is MANAGER 7788 SCOTT, Designation is ANALYST 7839 KING, Designation is PRESIDENT 7844 TURNER, Designation is SALESMAN 7876 ADAMS, Designation is CLERK 7900 JAMES, Designation is CLERK 7902 FORD, Designation is ANALYST 7934 MILLER, Designation is CLERK 14 rows selected.

Suppressing Duplicate Rows in Output Until it is instructed sql*plus displays the results of a query without eliminating duplicate rows. To eliminate the duplicate rows in the result, the distinct keyword is used. Multiple columns can be declared after the distinct qualifier. The distinct qualifier affects all the selected column, and represents a distinct combination of the columns.
SQL> select distinct deptno 2 from EMP; DEPTNO ---------10 20 30 3 rows selected. SQL> select distinct mgr 2 from EMP; MGR ---------7566 7698 7782 7788 7839 7902 7 rows selected.

37

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> select distinct job, deptno 2 from EMP; JOB DEPTNO --------- ---------ANALYST 20 CLERK 10 CLERK 20 CLERK 30 MANAGER 10 MANAGER 20 MANAGER 30 PRESIDENT 10 SALESMAN 30 9 rows selected. SQL> select distinct deptno, job 2 from EMP; DEPTNO JOB ---------- --------10 CLERK 10 MANAGER 10 PRESIDENT 20 ANALYST 20 CLERK 20 MANAGER 30 CLERK 30 MANAGER 30 SALESMAN 9 rows selected.

Filtering of records The number of rows returned by a query can be limited using the where clause. A where clause contains a condition that must be met and should directly follow the from clause.

Syntax SQL> select [distinct] [*] {column1 [alias],} From table_name [Where condition(s)]; The where clause can compare Values in columns Literal values Arithmetic Expressions Functions The components of where clause are Column name. 38 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Comparison operator. Column name (or) constant (or) list of values. The character strings and dates should be enclosed in single quotation marks. Character values are case sensitive and date values are format sensitive (dd-mon-yy) The comparison operators are used in such conditions that compare one expression to another. The different comparison operators are Equality operator -> = Not equality operator -> <>, =, ^=.
Greater than operator -> > Less than operator -> <

Greater than or equal to operator -> >= Less than or equal to operator -> <= The format of the where clause is Where Expr Operator Value.
SQL> select ename, sal, job 2 from EMP 3 where job='MANAGER'; ENAME SAL JOB ---------- ---------- --------JONES 2975 MANAGER BLAKE 2850 MANAGER CLARK 2450 MANAGER 3 rows selected. SQL> select ename, hiredate, deptno, sal 2 from EMP 3 where deptno=10; ENAME HIREDATE DEPTNO SAL ---------- --------- ---------- ---------CLARK 09-JUN-81 10 2450 KING 17-NOV-81 10 5000 MILLER 23-JAN-82 10 1300 3 rows selected. SQL> select EMPno, ename, Sal 2 from EMP 3 where Sal>=3000; EMPNO ENAME SAL ---------- ---------- ---------7788 SCOTT 3000 7839 KING 5000 7902 FORD 3000 3 rows selected.

39

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> select 2 ename||' Joined on '||hiredate "Employees joining dates" 3 from EMP 4 where hiredate='01-jan-95'; No rows selected SQL> select 2 ename||' Works in department '||deptno "Employees and Departments" 3 from EMP 4 where deptno<>20; Employees and Departments ----------------------------------------------------------------------ALLEN Works in department 30 WARD Works in department 30 MARTIN Works in department 30 BLAKE Works in department 30 CLARK Works in department 10 KING Works in department 10 TURNER Works in department 30 JAMES Works in department 30 MILLER Works in department 10 9 rows selected. SQL> select ename, sal, deptno, job 2 from EMP 3 where job<>'CLERK'; ENAME SAL DEPTNO JOB ---------- ---------- ---------- --------ALLEN 1600 30 SALESMAN WARD 1250 30 SALESMAN JONES 2975 20 MANAGER MARTIN 1250 30 SALESMAN BLAKE 2850 30 MANAGER CLARK 2450 10 MANAGER SCOTT 3000 20 ANALYST KING 5000 10 PRESIDENT TURNER 1500 30 SALESMAN FORD 3000 20 ANALYST 10 rows selected. SQL> select ename Name, Sal Basic, Sal*12 Annual 2 from EMP 3 where Sal*12>60000; No rows selected

Applying Logical Operators to Filters 40 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

The logical operators combine the results of two component conditions to produce a single result. The logical operators provided by oracle are Logical conjunction operator -> AND Logical disjunction operator -> OR Logical negation operator -> NOT

AND Operator It returns true if both or all component conditions are true. It returns false if either is false, else returns unknown. Truth Table AND TRUE FALSE NULL TRUE T F NULL FALSE F F F NULL NULL F NULL

SQL> select ename, sal, deptno, job 2 from EMP 3 where deptno=20 and job='MANAGER'; ENAME SAL DEPTNO JOB ---------- ---------- ---------- --------JONES 2975 20 MANAGER 1 row selected. SQL> Ed Wrote file afiedt.buf 1 select EMPno, ename, sal, job 2 from EMP 3* where Sal>=1100 and job='CLERK' SQL> / EMPNO ENAME SAL JOB ---------- ---------- ---------- --------7876 ADAMS 1100 CLERK 7934 MILLER 1300 CLERK 2 rows selected. SQL> select EMPno, ename, sal, job 2 from EMP 3 where deptno=10 and job='CLERK'; EMPNO ENAME SAL JOB ---------- ---------- ---------- ---------

41

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7934 MILLER 1 row selected.

1300 CLERK

SQL> select ename, sal, job 2 from EMP 3 where (Sal>=1500 and Sal<=5000) and 4 job='MANAGER'; ENAME SAL JOB ---------- ---------- --------JONES 2975 MANAGER BLAKE 2850 MANAGER CLARK 2450 MANAGER 3 rows selected.

OR Operator It returns true if either of the component condition is true. It returns false if both are false, else returns unknown. Truth Table OR TRUE FALSE NULL TRUE T T T FALSE T F NULL NULL T NULL NULL

SQL> select ename, sal, deptno, job 2 from EMP 3 where deptno=20 or job='MANAGER'; ENAME SAL DEPTNO JOB ---------- ---------- ---------- --------SMITH 800 20 CLERK JONES 2975 20 MANAGER BLAKE 2850 30 MANAGER CLARK 2450 10 MANAGER SCOTT 3000 20 ANALYST ADAMS 1100 20 CLERK FORD 3000 20 ANALYST 7 rows selected. SQL> select EMPno, ename, job, sal 2 from EMP 3 where Sal>=1100 or job='CLERK'; EMPNO ENAME JOB ---------- ---------- --------- ---------7369 SMITH CLERK SAL 800

42

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7499 ALLEN SALESMAN 7521 WARD SALESMAN 7566 JONES MANAGER 7654 MARTIN SALESMAN 7698 BLAKE MANAGER 7782 CLARK MANAGER 7788 SCOTT ANALYST 7839 KING PRESIDENT 7844 TURNER SALESMAN 7876 ADAMS CLERK 7900 JAMES CLERK 7902 FORD ANALYST 7934 MILLER CLERK 14 rows selected.

1600 1250 2975 1250 2850 2450 3000 5000 1500 1100 950 3000 1300

SQL> select EMPno, ename, sal, job 2 from EMP 3 where deptno=10 or job='MANAGER'; EMPNO ENAME SAL JOB ---------- ---------- ---------- --------7566 JONES 2975 MANAGER 7698 BLAKE 2850 MANAGER 7782 CLARK 2450 MANAGER 7839 KING 5000 PRESIDENT 7934 MILLER 1300 CLERK 5 rows selected. SQL> select ename, sal, job 2 from EMP 3 where Sal>=1500 or Sal>=5000; ENAME SAL JOB ---------- ---------- --------ALLEN 1600 SALESMAN JONES 2975 MANAGER BLAKE 2850 MANAGER CLARK 2450 MANAGER SCOTT 3000 ANALYST KING 5000 PRESIDENT TURNER 1500 SALESMAN FORD 3000 ANALYST 8 rows selected. SQL> select ename, sal, job, deptno 2 from EMP 3 where deptno=10 or deptno=20; ENAME SAL JOB DEPTNO ---------- ---------- --------- ---------SMITH 800 CLERK 20

43

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

JONES CLARK SCOTT KING ADAMS FORD MILLER

2975 MANAGER 2450 MANAGER 3000 ANALYST 5000 PRESIDENT 1100 CLERK 3000 ANALYST 1300 CLERK

20 10 20 10 20 20 10

8 rows selected. SQL> select ename, sal, job 2 from EMP 3 where job='CLERK' or job='MANAGER'; ENAME SAL JOB ---------- ---------- --------SMITH 800 CLERK JONES 2975 MANAGER BLAKE 2850 MANAGER CLARK 2450 MANAGER ADAMS 1100 CLERK JAMES 950 CLERK MILLER 1300 CLERK 7 rows selected. SQL> select ename, sal, job 2 from EMP 3 where (Sal<=2500 or Sal>=5000) or 4 job='MANAGER'; ENAME SAL JOB ---------- ---------- --------SMITH 800 CLERK ALLEN 1600 SALESMAN WARD 1250 SALESMAN JONES 2975 MANAGER MARTIN 1250 SALESMAN BLAKE 2850 MANAGER CLARK 2450 MANAGER KING 5000 PRESIDENT TURNER 1500 SALESMAN ADAMS 1100 CLERK JAMES 950 CLERK MILLER 1300 CLERK 12 rows selected.

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. Truth Table 44 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

NOT NOT

TRUE FALSE NULL F F NULL

SQL> select ename, sal, job 2 from EMP 3 where not job='MANAGER'; ENAME SAL JOB ---------- ---------- --------SMITH 800 CLERK ALLEN 1600 SALESMAN WARD 1250 SALESMAN MARTIN 1250 SALESMAN SCOTT 3000 ANALYST KING 5000 PRESIDENT TURNER 1500 SALESMAN ADAMS 1100 CLERK JAMES 950 CLERK FORD 3000 ANALYST MILLER 1300 CLERK 11 rows selected. SQL> select ename, sal, job 2 from EMP 3 where not Sal>5000; ENAME SAL JOB ---------- ---------- --------SMITH 800 CLERK ALLEN 1600 SALESMAN WARD 1250 SALESMAN JONES 2975 MANAGER MARTIN 1250 SALESMAN BLAKE 2850 MANAGER CLARK 2450 MANAGER SCOTT 3000 ANALYST KING 5000 PRESIDENT TURNER 1500 SALESMAN ADAMS 1100 CLERK JAMES 950 CLERK FORD 3000 ANALYST MILLER 1300 CLERK 14 rows selected. SQL> select ename, sal, job

45

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 from EMP 3 where not Sal<5000; ENAME SAL JOB ---------- ---------- --------KING 5000 PRESIDENT 1 row selected. SQL> select ename, sal, hiredate 2 from EMP 3 where not job='SALESMAN' and deptno=30; ENAME SAL HIREDATE ---------- ---------- --------BLAKE 2850 01-MAY-81 JAMES 950 03-DEC-81 2 rows selected.

Combination of AND and OR Operators


SQL> select EMPno, ename, job, sal 2 from EMP 3 where (Sal>1100 or job='CLERK') AND DEPTNO=20; EMPNO ENAME JOB ---------- ---------- --------- ---------7369 SMITH CLERK 7566 JONES MANAGER 7788 SCOTT ANALYST 7876 ADAMS CLERK 7902 FORD ANALYST 5 rows selected. SQL> SELECT EMPNO, ENAME, JOB, SAL 2 FROM EMP 3 WHERE (deptno=10 AND job='MANAGER') OR 4 Sal>=3000; EMPNO ENAME JOB ---------- ---------- --------- ---------7782 CLARK MANAGER 7788 SCOTT ANALYST 7839 KING PRESIDENT 7902 FORD ANALYST 4 rows selected. SQL> Ed Wrote file afiedt.buf 1 SELECT EMPno, ename, job, sal SAL 2450 3000 5000 3000 SAL 800 2975 3000 1100 3000

46

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 FROM EMP 3 WHERE (deptno=10 AND job='MANAGER') OR 4* (deptno=20 AND Sal>=3000) SQL> / EMPNO ENAME JOB ---------- ---------- --------- ---------7782 CLARK MANAGER 7788 SCOTT ANALYST 7902 FORD ANALYST 3 rows selected. SAL 2450 3000 3000

Some Things to Note


SQL> SELECT ename, sal, job 2 FROM EMP 3 WHERE job>'MANAGER'; ENAME SAL JOB ---------- ---------- --------ALLEN 1600 SALESMAN WARD 1250 SALESMAN MARTIN 1250 SALESMAN KING 5000 PRESIDENT TURNER 1500 SALESMAN 5 rows selected. SQL> SELECT ename, sal, job 2 FROM EMP 3 WHERE job<'MANAGER'; ENAME SAL JOB ---------- ---------- --------SMITH 800 CLERK SCOTT 3000 ANALYST ADAMS 1100 CLERK JAMES 950 CLERK FORD 3000 ANALYST MILLER 1300 CLERK 6 rows selected. SQL> SELECT ename, sal, hiredate 2 FROM EMP 3 WHERE hiredate>'20-feb-1981'; ENAME SAL HIREDATE ---------- ---------- --------WARD 1250 22-FEB-81 JONES 2975 02-APR-81 MARTIN 1250 28-SEP-81 BLAKE 2850 01-MAY-81

47

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

2450 09-JUN-81 3000 19-APR-87 5000 17-NOV-81 1500 08-SEP-81 1100 23-MAY-87 950 03-DEC-81 3000 03-DEC-81 1300 23-JAN-82

12 rows selected. SQL> SELECT ename, sal, hiredate 2 FROM EMP 3 WHERE hiredate<'20-feb-1981'; ENAME SAL HIREDATE ---------- ---------- --------SMITH 800 17-DEC-80 1 row selected. SQL> SELECT ename, sal, hiredate 2 FROM EMP 3 WHERE job<>'CLERK'; ENAME SAL HIREDATE ---------- ---------- --------ALLEN 1600 20-FEB-81 WARD 1250 22-FEB-81 JONES 2975 02-APR-81 MARTIN 1250 28-SEP-81 BLAKE 2850 01-MAY-81 CLARK 2450 09-JUN-81 SCOTT 3000 19-APR-87 KING 5000 17-NOV-81 TURNER 1500 08-SEP-81 FORD 3000 03-DEC-81 10 rows selected. SQL> SELECT ename, sal, comm 2 FROM EMP 3 WHERE comm IS NULL; ENAME SAL COMM ---------- ---------- ---------SMITH 800 JONES 2975 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 ADAMS 1100 JAMES 950

48

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

FORD MILLER

3000 1300

10 rows selected. SQL> SELECT ename, sal, comm 2 FROM EMP 3 WHERE comm IS NOT NULL; ENAME SAL ---------- ---------- ---------ALLEN 1600 WARD 1250 MARTIN 1250 TURNER 1500 4 rows selected. SQL> SELECT ename, sal, job 2 FROM EMP 3 WHERE NOT job>'MANAGER'; ENAME SAL JOB ---------- ---------- --------SMITH 800 CLERK JONES 2975 MANAGER BLAKE 2850 MANAGER CLARK 2450 MANAGER SCOTT 3000 ANALYST ADAMS 1100 CLERK JAMES 950 CLERK FORD 3000 ANALYST MILLER 1300 CLERK 9 rows selected. SQL> SELECT ename, sal, hiredate 2 FROM EMP 3 WHERE NOT hiredate='17-dec-1980'; ENAME SAL HIREDATE ---------- ---------- --------ALLEN 1600 20-FEB-81 WARD 1250 22-FEB-81 JONES 2975 02-APR-81 MARTIN 1250 28-SEP-81 BLAKE 2850 01-MAY-81 CLARK 2450 09-JUN-81 SCOTT 3000 19-APR-87 KING 5000 17-NOV-81 TURNER 1500 08-SEP-81 ADAMS 1100 23-MAY-87 JAMES 950 03-DEC-81 FORD 3000 03-DEC-81 COMM 300 500 1400 0

49

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

MILLER

1300 23-JAN-82

13 rows selected. SQL> SELECT ename, sal, hiredate 2 FROM EMP 3 WHERE NOT hiredate>'17-dec-1980'; ENAME SAL HIREDATE ---------- ---------- --------SMITH 800 17-DEC-80 1 row selected. SQL> SELECT ename, sal, hiredate 2 FROM EMP 3 WHERE NOT hiredate>'17-december-1980'; ENAME SAL HIREDATE ---------- ---------- --------SMITH 800 17-DEC-80 1 row selected.

Rules of Operator Precedence The default precedence order if All comparison operators Not operator And operator Or operator The precedence can be controlled using parenthesis.
SQL> SELECT ename, deptno, job, sal 2 FROM EMP 3 WHERE deptno=10 OR 4 deptno=20 AND 5 job='SALESMAN' AND 6 Sal>2500 OR 7 Sal<1500; ENAME DEPTNO JOB ---------- ---------- --------- ---------SMITH 20 CLERK WARD 30 SALESMAN MARTIN 30 SALESMAN CLARK 10 MANAGER KING 10 PRESIDENT ADAMS 20 CLERK JAMES 30 CLERK MILLER 10 CLERK 8 rows selected. SAL 800 1250 1250 2450 5000 1100 950 1300

50

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT ename, deptno, job, sal 2 FROM EMP 3 WHERE deptno=10 OR 4 (deptno=20 AND job='SALESMAN') AND 5 (Sal>2500 OR Sal<1500); ENAME DEPTNO JOB ---------- ---------- --------- ---------CLARK 10 MANAGER KING 10 PRESIDENT MILLER 10 CLERK 3 rows selected. SAL 2450 5000 1300

SQL*Plus Operators BETWEEN AND Operator This operator is used to display rows based on a range of values. The declared range is inclusive. The lower limit should be declared first. The negation of this operator is NOT BETWEEN AND
SQL> SELECT ename, sal, job 2 FROM EMP 3 WHERE Sal 4 BETWEEN 1000 AND 1500; ENAME SAL JOB ---------- ---------- --------WARD 1250 SALESMAN MARTIN 1250 SALESMAN TURNER 1500 SALESMAN ADAMS 1100 CLERK MILLER 1300 CLERK 5 rows selected. SQL> SELECT ename, sal, job 2 FROM EMP 3 WHERE Sal 4 NOT BETWEEN 1000 AND 1500; ENAME SAL JOB ---------- ---------- --------SMITH 800 CLERK ALLEN 1600 SALESMAN JONES 2975 MANAGER BLAKE 2850 MANAGER CLARK 2450 MANAGER SCOTT 3000 ANALYST KING 5000 PRESIDENT JAMES 950 CLERK FORD 3000 ANALYST

51

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

9 rows selected. SQL> SELECT ename, sal, job 2 FROM EMP 3 WHERE JOB 4 BETWEEN 'MANAGER' AND 'SALESMAN'; ENAME SAL JOB ---------- ---------- --------ALLEN 1600 SALESMAN WARD 1250 SALESMAN JONES 2975 MANAGER MARTIN 1250 SALESMAN BLAKE 2850 MANAGER CLARK 2450 MANAGER KING 5000 PRESIDENT TURNER 1500 SALESMAN 8 rows selected. SQL> SQL> SELECT ename, sal, job 2 FROM EMP 3 WHERE job 4 NOT BETWEEN 'MANAGER' AND 'SALESMAN'; ENAME SAL JOB ---------- ---------- --------SMITH 800 CLERK SCOTT 3000 ANALYST ADAMS 1100 CLERK JAMES 950 CLERK FORD 3000 ANALYST MILLER 1300 CLERK 6 rows selected. SQL> SELECT ename, sal, job, hiredate 2 FROM EMP 3 WHERE hiredate 4 BETWEEN '17-feb-1981' AND '20-jun-1983'; ENAME SAL JOB HIREDATE ---------- ---------- --------- --------ALLEN 1600 SALESMAN 20-FEB-81 WARD 1250 SALESMAN 22-FEB-81 JONES 2975 MANAGER 02-APR-81 MARTIN 1250 SALESMAN 28-SEP-81 BLAKE 2850 MANAGER 01-MAY-81 CLARK 2450 MANAGER 09-JUN-81 KING 5000 PRESIDENT 17-NOV-81 TURNER 1500 SALESMAN 08-SEP-81 JAMES 950 CLERK 03-DEC-81

52

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

FORD MILLER

3000 ANALYST 03-DEC-81 1300 CLERK 23-JAN-82

11 rows selected. SQL> SELECT ename, sal, job, hiredate 2 FROM EMP 3 WHERE hiredate 4 NOT BETWEEN '17-Feb-1981' AND '20-jun-1983'; ENAME SAL JOB HIREDATE ---------- ---------- --------- --------SMITH 800 CLERK 17-DEC-80 SCOTT 3000 ANALYST 19-APR-87 ADAMS 1100 CLERK 23-MAY-87 3 rows selected.

IN Operator The operator is used to test for values in a specified list. The operator can be used upon any data type. The negation of the operator is not in.
SQL> SELECT ename, sal, job 2 FROM EMP 3 WHERE ename IN ('FORD','ALLEN'); ENAME SAL JOB ---------- ---------- --------ALLEN 1600 SALESMAN FORD 3000 ANALYST 2 rows selected. SQL> SELECT ename, sal, job 2 FROM EMP 3 WHERE ename NOT IN ('FORD','ALLEN'); ENAME SAL JOB ---------- ---------- --------SMITH 800 CLERK WARD 1250 SALESMAN JONES 2975 MANAGER MARTIN 1250 SALESMAN BLAKE 2850 MANAGER CLARK 2450 MANAGER SCOTT 3000 ANALYST KING 5000 PRESIDENT TURNER 1500 SALESMAN ADAMS 1100 CLERK JAMES 950 CLERK MILLER 1300 CLERK

53

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

12 rows selected. SQL> SELECT ename, sal, deptno, job 2 FROM EMP 3 WHERE deptno IN (10, 30); ENAME SAL DEPTNO ---------- ---------- ---------ALLEN 1600 30 WARD 1250 30 MARTIN 1250 30 BLAKE 2850 30 CLARK 2450 10 KING 5000 10 TURNER 1500 30 JAMES 950 30 MILLER 1300 10 9 rows selected. SQL> SELECT ename, sal, deptno, job 2 FROM EMP 3 WHERE deptno NOT IN (10, 30); ENAME SAL DEPTNO ---------- ---------- ---------SMITH 800 20 JONES 2975 20 SCOTT 3000 20 ADAMS 1100 20 FORD 3000 20 5 rows selected. SQL> SELECT ename, sal, hiredate 2 FROM EMP 3 WHERE hiredate IN ('20-feb-1981','09-jun-1981'); ENAME SAL HIREDATE ---------- ---------- --------ALLEN 1600 20-FEB-81 CLARK 2450 09-JUN-81 2 rows selected. SQL> SELECT ename, sal, hiredate 2 FROM EMP 3 WHERE hiredate NOT IN ('20-feb-1981','09-jun-1981'); ENAME SAL HIREDATE ---------- ---------- --------SMITH 800 17-DEC-80 WARD 1250 22-FEB-81 JONES 2975 02-APR-81

54

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

MARTIN BLAKE SCOTT KING TURNER ADAMS JAMES FORD MILLER

1250 28-SEP-81 2850 01-MAY-81 3000 19-APR-87 5000 17-NOV-81 1500 08-SEP-81 1100 23-MAY-87 950 03-DEC-81 3000 03-DEC-81 1300 23-JAN-82

12 rows selected.

IS NULL Operator The operator tests for NULL values. It is the only operator that can be used to test for NULLs. The negation is IS NOT NULL.
SQL> SELECT ename, deptno, comm 2 FROM EMP 3 WHERE comm IS NULL; ENAME DEPTNO ---------- ---------- ---------SMITH 20 JONES 20 BLAKE 30 CLARK 10 SCOTT 20 KING 10 ADAMS 20 JAMES 30 FORD 20 MILLER 10 10 rows selected. SQL> SELECT ename, deptno, job, mgr 2 FROM EMP 3 WHERE mgr IS NULL; ENAME DEPTNO JOB ---------- ---------- --------- ---------KING 10 PRESIDENT 1 row selected. SQL> SELECT ename, deptno, comm 2 FROM EMP 3 WHERE comm IS NOT NULL; ENAME DEPTNO COMM ---------- ---------- ---------ALLEN 30 300 MGR COMM

55

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

WARD MARTIN TURNER

30 30 30

500 1400 0

4 rows selected. SQL> SELECT ename, deptno, job, mgr 2 FROM EMP 3 WHERE mgr IS NOT NULL; ENAME DEPTNO JOB MGR ---------- ---------- --------- ---------SMITH 20 CLERK 7902 ALLEN 30 SALESMAN 7698 WARD 30 SALESMAN 7698 JONES 20 MANAGER 7839 MARTIN 30 SALESMAN 7698 BLAKE 30 MANAGER 7839 CLARK 10 MANAGER 7839 SCOTT 20 ANALYST 7566 TURNER 30 SALESMAN 7698 ADAMS 20 CLERK 7788 JAMES 30 CLERK 7698 FORD 20 ANALYST 7566 MILLER 10 CLERK 7782 13 rows selected.

Like Operator The line operator is used to search for a matching character patterns. The character pattern matching operation is referred as a wild card search. The available wild cards in oracle are % -> used to represent any sequence of zero or more characters. _ -> Represents any single character, only at that position. The wild card symbols can be used in any combination with literal characters. For finding exact match for % and _ the escape option has to be used along with \ symbol.
SQL> SELECT ename, job 2 FROM EMP 3 WHERE ename LIKE 'S%'; ENAME JOB ---------- --------SMITH CLERK SCOTT ANALYST 2 rows selected.

56

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> Ed Wrote file afiedt.buf 1 SELECT ename, job 2 FROM EMP 3* WHERE ename NOT LIKE 'S%' SQL> / ENAME JOB ---------- --------ALLEN SALESMAN WARD SALESMAN JONES MANAGER MARTIN SALESMAN BLAKE MANAGER CLARK MANAGER KING PRESIDENT TURNER SALESMAN ADAMS CLERK JAMES CLERK FORD ANALYST MILLER CLERK 12 rows selected. SQL> SELECT ename, job 2 FROM EMP 3 WHERE ename LIKE '_A%'; ENAME JOB ---------- --------WARD SALESMAN MARTIN SALESMAN JAMES CLERK 3 rows selected. SQL> SELECT ename, job 2 FROM EMP 3 WHERE ename NOT LIKE '_A%'; ENAME JOB ---------- --------SMITH CLERK ALLEN SALESMAN JONES MANAGER BLAKE MANAGER CLARK MANAGER SCOTT ANALYST KING PRESIDENT TURNER SALESMAN ADAMS CLERK FORD ANALYST MILLER CLERK

57

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

11 rows selected. SQL> SELECT ename, sal 2 FROM EMP 3 WHERE ename='SM%'; No rows selected SQL> SELECT ename, sal 2 FROM EMP 3 WHERE ename=LIKE 'SM%'; WHERE ename=LIKE 'SM%' * ERROR at line 3: ORA-00936: missing expression SQL> SELECT ename, sal 2 FROM EMP 3 WHERE 'SM%' LIKE ename; No rows selected SQL> SELECT ename, hiredate 2 FROM EMP 3 WHERE hiredate LIKE '%-feb-1981'; No rows selected SQL> SELECT ename, hiredate 2 FROM EMP 3 WHERE hiredate LIKE '03-%-1981'; No rows selected SQL> SELECT * 2 FROM dept 3 WHERE dname LIKE'%\_%' ESCAPE '\'; No rows selected

Ordering Information The order of rows returned in the result of a query undefined. The order by clause can be used to sort the rows in the required order. The order by clause should be the last clause in the order of all clauses in the select statement. An expression or an alias can be specified to order by clause for sorting. Default ordering of data is ascending Numbers -> 0 9 Dates -> Earliest Latest. Strings -> A Z. 58 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

NULLS -> Last. Syntax SQL> select [distinct] [*] {column1 [alias],} From table_name [Where condition (s)] [Order by {column, expr} [asc/desc]]; The default ordering upon a 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. The controversy of sorting is broken only when there arises a conflict of consistency upon the data in a column.
SQL> SELECT ename, job, deptno, hiredate 2 FROM EMP 3 ORDER BY hiredate; ENAME JOB DEPTNO HIREDATE ---------- --------- ---------- --------SMITH CLERK 20 17-DEC-80 ALLEN SALESMAN 30 20-FEB-81 WARD SALESMAN 30 22-FEB-81 JONES MANAGER 20 02-APR-81 BLAKE MANAGER 30 01-MAY-81 CLARK MANAGER 10 09-JUN-81 TURNER SALESMAN 30 08-SEP-81 MARTIN SALESMAN 30 28-SEP-81 KING PRESIDENT 10 17-NOV-81 JAMES CLERK 30 03-DEC-81 FORD ANALYST 20 03-DEC-81 MILLER CLERK 10 23-JAN-82 SCOTT ANALYST 20 19-APR-87 ADAMS CLERK 20 23-MAY-87 14 rows selected. SQL> SELECT ename, job, deptno, hiredate 2 FROM EMP 3 ORDER BY hiredate desc; ENAME JOB DEPTNO HIREDATE ---------- --------- ---------- --------ADAMS CLERK 20 23-MAY-87 SCOTT ANALYST 20 19-APR-87 MILLER CLERK 10 23-JAN-82 JAMES CLERK 30 03-DEC-81 FORD ANALYST 20 03-DEC-81 KING PRESIDENT 10 17-NOV-81 MARTIN SALESMAN 30 28-SEP-81 TURNER SALESMAN 30 08-SEP-81 CLARK MANAGER 10 09-JUN-81

59

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

BLAKE JONES WARD ALLEN SMITH

MANAGER MANAGER SALESMAN SALESMAN CLERK

30 01-MAY-81 20 02-APR-81 30 22-FEB-81 30 20-FEB-81 20 17-DEC-80

14 rows selected. SQL> SELECT ename, job, sal 2 FROM EMP 3 WHERE job='MANAGER' 4 ORDER BY Sal; ENAME JOB SAL ---------- --------- ---------CLARK MANAGER 2450 BLAKE MANAGER 2850 JONES MANAGER 2975 3 rows selected. SQL> SELECT ename, job, sal 2 FROM EMP 3 WHERE Sal>=2500 4 ORDER BY job, ename desc; ENAME JOB SAL ---------- --------- ---------SCOTT ANALYST 3000 FORD ANALYST 3000 JONES MANAGER 2975 BLAKE MANAGER 2850 KING PRESIDENT 5000 5 rows selected. SQL> SELECT EMPno, ename, sal, sal * 12 Annsal 2 FROM EMP 3 ORDER BY annsal; EMPNO ENAME SAL ANNSAL ---------- ---------- ---------- ---------7369 SMITH 800 9600 7900 JAMES 950 11400 7876 ADAMS 1100 13200 7521 WARD 1250 15000 7654 MARTIN 1250 15000 7934 MILLER 1300 15600 7844 TURNER 1500 18000 7499 ALLEN 1600 19200 7782 CLARK 2450 29400 7698 BLAKE 2850 34200 7566 JONES 2975 35700 7788 SCOTT 3000 36000

60

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7902 FORD 7839 KING 14 rows selected.

3000 5000

36000 60000

SQL> SELECT EMPno, ename, Sal 2 FROM EMP 3 ORDER BY deptno, sal, hiredate; EMPNO ENAME SAL ---------- ---------- ---------7934 MILLER 1300 7782 CLARK 2450 7839 KING 5000 7369 SMITH 800 7876 ADAMS 1100 7566 JONES 2975 7902 FORD 3000 7788 SCOTT 3000 7900 JAMES 950 7521 WARD 1250 7654 MARTIN 1250 7844 TURNER 1500 7499 ALLEN 1600 7698 BLAKE 2850 14 rows selected. SQL> SELECT EMPno, ename, Sal 2 FROM EMP 3 WHERE Sal>=2000 4 ORDER BY hiredate, sal desc; EMPNO ENAME SAL ---------- ---------- ---------7566 JONES 2975 7698 BLAKE 2850 7782 CLARK 2450 7839 KING 5000 7902 FORD 3000 7788 SCOTT 3000 6 rows selected.

61

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

62

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Experiencing the Power of SQL Functions

SQL functions are built into oracle and are available for use in various appropriate sql statements. The sql functions can be used to.. Perform calculations on data. Modify individual data items. Manipulate output for groups or rows. Format dates and numbers for display. Convert column data types. Sql functions may accept arguments and always return a value, and can be nested. If an sql functions is called with a null argument, then a null is returned. SQL Function Types 63 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Sql identifies two types of functions Single row functions. Multiple row functions.

Single Row Functions These functions return a single result for every row of a queried table or view.

Multiple Row Functions These functions manipulate groups of row and return one result per group of rows. The single row functions can appear in Select list. Where clause and order by clause. Start with clause. Connect by clause. The single row functions are categorized as.. Character functions Number functions. Date functions. Conversion functions. Single row functions are used to manipulate data items. They can accept one or more arguments and return one value for each row returned by the query. The argument for a single row function can be User supplied constant. Variable value. Column name. Expression.

Syntax FunctionName (column/Expr, [Arg1, Arg2,]) Single Row Functions Features Acts on each row returned in the query. Returns one result per row. May return a data value of a different data type than that referenced. May expect one or more arguments. Can be used in select, where and order by clauses. It can be nested. Specification Behavior of Functions Character Functions Accept character input and can return both character and number values. 64 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Number Functions Accept numeric input and return numeric values. Date Functions Operate on values of date data type and can return both date and number. Conversion Functions Convert a value from one data type to another data type. General Functions NVL -> Operates on NULL values. DECODE -> Operates on any data type and can return any data type. Character Functions. They are functions that return character values, unless stated. 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. The functions are categorized as Case conversion functions. Character manipulation functions. Case Conversion Functions These functions are used to convert the casing of the existing character from one type to another. Lower function. Upper function. Initcap function. Lower Function It converts alpha character values to lower case. The return value has the same data type as argument char type ( char or varchar2 ) Syntax: LOWER (Column / Expression)
SQL> SELECT 2 ORACLE CORPORATION' String, 3 LOWER ('ORACLE CORPORATION') Lower 4 FROM DUAL; STRING LOWER ------------------ -----------------ORACLE CORPORATION Oracle Corporation 1 row selected. SQL> SELECT ename, LOWER ('MY INFORMATION') Lower 2 FROM EMP;

65

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ENAME LOWER ---------- -------------SMITH my information ALLEN my information WARD my information JONES my information MARTIN my information BLAKE my information CLARK my information SCOTT my information KING my information TURNER my information ADAMS my information JAMES my information FORD my information MILLER my information 14 rows selected. SQL> SELECT ename, LOWER (ename) lower 2 FROM EMP 3 WHERE job='MANAGER'; ENAME LOWER ---------- ---------JONES jones BLAKE Blake CLARK Clark 3 rows selected. SQL> SELECT 'The'||ename||'''s Designation is '||job Employees 2 FROM EMP 3 WHERE LOWER (job) ='manager'; EMPLOYEE --------------------------------------The Joness Designation is MANAGER The Blakes Designation is MANAGER The Clarks Designation is MANAGER 3 rows selected.

Upper Function It converts the alpha character values to upper case. The return value has the same data type as the argument char. Syntax: UPPER (Column / Expression)
SQL> SELECT 2 oracle corporation' string,

66

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 UPPER (Oracle Corporation') Upper 4 FROM DUAL; STRING UPPER ------------------ -----------------Oracle Corporation ORACLE CORPORATION 1 row selected. SQL> SELECT ename, UPPER ('my information') Upper 2 FROM EMP; ENAME UPEER ---------- -------------SMITH MY INFORMATION ALLEN MY INFORMATION WARD MY INFORMATION JONES MY INFORMATION MARTIN MY INFORMATION BLAKE MY INFORMATION CLARK MY INFORMATION SCOTT MY INFORMATION KING MY INFORMATION TURNER MY INFORMATION ADAMS MY INFORMATION JAMES MY INFORMATION FORD MY INFORMATION MILLER MY INFORMATION 14 rows selected. SQL> SELECT ename, LOWER (ename), UPPER (Ename) 2 FROM EMP 3 WHERE job='MANAGER'; ENAME LOWER (ENAM UPPER (ENAM ---------- ---------- ---------JONES jones JONES BLAKE blake BLAKE CLARK clark CLARK 3 rows selected. SQL> SELECT ename, job 2 FROM EMP 3 WHERE Job=UPPER ('manager'); ENAME JOB ---------- --------JONES MANAGER BLAKE MANAGER CLARK MANAGER 3 rows selected.

67

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT ename, job, sal, sal*12 2 FROM EMP 3 WHERE Job=UPPER (LOWER ('MANAGER')); ENAME JOB SAL SAL*12 ---------- --------- ---------- ---------JONES MANAGER 2975 35700 BLAKE MANAGER 2850 34200 CLARK MANAGER 2450 29400 3 rows selected. SQL> SELECT 'The'| 2. SQL> SELECT 'The'||ename||'''s Designation is'||LOWER (job) 2 FROM EMP 3 WHERE job=UPPER ('manager') 4 ORDER BY Sal; 'THE'||ENAME||'''SDESIGNATIONIS'||LOWER --------------------------------------The Clarks Designation is manager The Blakes Designation is manager The Joness Designation is manager 3 rows selected. SQL> SELECT 2 UPPER ('The'||ename||'''s Basic Salary is Rupees '||Sal) 3 FROM EMP 4 WHERE job IN ('MANAGER', UPPER ('clerk')) 5 ORDER BY Sal DESC; UPPER ('THE'||ENAME||'''SBASICSALARYISRUPEES'||SAL) ------------------------------------------------------------------------------THEJONES'S BASIC SALARY IS RUPEES 2975 THEBLAKE'S BASIC SALARY IS RUPEES 2850 THECLARK'S BASIC SALARY IS RUPEES 2450 THEMILLER'S BASIC SALARY IS RUPEES 1300 THEADAMS'S BASIC SALARY IS RUPEES 1100 THEJAMES'S BASIC SALARY IS RUPEES 950 THESMITH'S BASIC SALARY IS RUPEES 800 7 rows selected.

Initcap Function It converts the alpha character values into uppercase for the first letter of each word, keeping all other letters in lower case. Words are delimited by white spaces or characters that are not alphanumeric. Syntax: INITCAP (Column / Expression) 68 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT 2 oracle corporation' string, 3 INITCAP (Oracle Corporation') Initcap 4 FROM DUAL; STRING INITCAP ------------------ -----------------Oracle Corporation Oracle Corporation 1 row selected. SQL> SELECT 2 The job title for '||INITCAP (ename) ||' is '||LOWER (job) FROM EMP; 'THEJOBTITLEFOR'||INITCAP (ENAME) ||'IS'||L ----------------------------------------The job title for Smith is clerk The job title for Allen is salesman The job title for Ward is salesman The job title for Jones is manager The job title for Martin is salesman The job title for Blake is manager The job title for Clark is manager The job title for Scott is analyst The job title for King is president The job title for Turner is salesman The job title for Adams is clerk The job title for James is clerk The job title for Ford is analyst The job title for Miller is clerk 14 rows selected. SQL> SELECT 2 ename, UPPER (ename), LOWER (ename), INITCAP (ename) 3 FROM EMP; ENAME UPPER (ENAM LOWER (ENAM INITCAP (EN ---------- ---------- ---------- ---------SMITH SMITH smith Smith ALLEN ALLEN Allen Allen WARD WARD ward Ward JONES JONES jones Jones MARTIN MARTIN martin Martin BLAKE BLAKE Blake Blake CLARK CLARK Clark Clark SCOTT SCOTT Scott Scott KING KING king King TURNER TURNER turner Turner ADAMS ADAMS adams Adams JAMES JAMES James James FORD FORD ford Ford MILLER MILLER miller Miller

69

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

14 rows selected. SQL> SELECT Empno, INITCAP (ename), Deptno 2 FROM EMP 3 WHERE ename=UPPER ('blake'); EMPNO INITCAP (EN ---------- ---------- ---------7698 Blake 30 1 row selected. DEPTNO

Concat Function It concatenates the first characters value to the second character value. It accepts only two parameters accept. It return the character data type. Syntax: CONCAT (Column / Expr1, Column2 / Expr2)
SQL> SELECT 2 Oracle string1, 3 Corporation string2, 4 CONCAT ('Oracle, Corporation') Concat 5 FROM DUAL; STRING STRING2 CONCAT ------ ----------- ----------------Oracle Corporation OracleCorporation 1 row selected. SQL> SELECT ename, job, CONCAT (ename, job) Concat 2 FROM EMP 3 WHERE deptno=10; ENAME JOB CONCAT ---------- --------- ------------------CLARK MANAGER CLARKMANAGER KING PRESIDENT KINGPRESIDENT MILLER CLERK MILLERCLERK 3 rows selected. SQL> ED Wrote file afiedt.buf 1 SELECT 2 CONCAT ('The Employees Name is', INITCAP (Ename)) Info 3 FROM EMP 4* WHERE deptno IN (10, 30) SQL> /

70

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

INFO -----------------------------The Employees Name is Allen The Employees Name inward The Employees Name is Martin The Employees Name is Blake The Employees Name is Clark The Employees Name asking The Employees Name is Turner The Employees Name is James The Employees Name is Miller 9 rows selected. SQL> SELECT 2 CONCAT (CONCAT (INITCAP (ename),' is a '), job) Job 3 FROM EMP 4 WHERE deptno IN (10, 20); JOB ------------------------Smith is a CLERK Jones is a MANAGER Clark is a MANAGER Scott is a ANALYST King is a PRESIDENT Adams is a CLERK Ford is a ANALYST Miller is a CLERK 8 rows selected.

Sub String Function Returns specified characters form character value, starting from a specified position m to n characters long. Syntax: SUBSTR (Col / Expr, m, n) Points to Remember If m is 0, it is treated as 1. If m is positive, oracle counts from the beginning of string to find the first character. If m is negative, oracle counts backwards from the end of the string. If n is omitted, oracle returns all characters to the end of string. If n is less that 1 or 0, a NULL is returned. Floating point numbers passed as arguments to substr are automatically converted to integers.
SQL> SELECT 2 ABCDEFGH String, 3 SUBSTR ('ABCDEFGH', 3, 4) SubString 4 FROM DUAL; STRING SUBS

71

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

-------- ---ABCDEFGH CDEF 1 row selected. SQL> ED Wrote file afiedt.buf 1 SELECT 2 ABCDEFGH String, 3 SUBSTR ('ABCDEFGH',-5, 4) SubString 4* FROM DUAL SQL> / STRING SUBS -------- ---ABCDEFGH DEFG 1 row selected. SQL> SELECT 2 ABCDEFGH String, 3 SUBSTR ('ABCDEFGH', 0, 4) SubString 4 FROM DUAL; STRING SUBS -------- ---ABCDEFGH ABCD 1 row selected. SQL> SELECT 2 ABCDEFGH String, 3 SUBSTR ('ABCDEFGH', 4) SubString 4 FROM DUAL; STRING SUBST -------- ----ABCDEFGH DEFGH 1 row selected. SQL> SELECT 2 'ABCDEFGH' String, 3 SUBSTR ('ABCDEFGH', 4, 0) SubString 4 FROM DUAL; STRING S -------- ABCDEFGH 1 row selected. SQL> SELECT

72

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 ABCDEFGH String, 3 SUBSTR ('ABCDEFGH', 4,-2) SubString 4 FROM DUAL; STRING S -------- ABCDEFGH 1 row selected. SQL> SELECT ename, job 2 FROM EMP 3 WHERE SUBSTR (job, 4, 3) =UPPER ('age'); ENAME JOB ---------- --------JONES MANAGER BLAKE MANAGER CLARK MANAGER 3 rows selected. SQL> SELECT 2 CONCAT (INITCAP (ename), 3 CONCAT (' is a ', 4 CONCAT (INITCAP ( 5 SUBSTR (job, 1, 3)),'Eater.'))) 6 FROM EMP 7 WHERE SUBSTR (job, 4, 3) =UPPER ('Age'); CONCAT (INITCAP (ENAME), CON ------------------------Jones is a ManEater. Blake is a ManEater. Clark is a ManEater. 3 rows selected.

Length Function Returns the number of characters in a value. If the string has data type char, the length includes all trailing blanks. If the string is Null, it returns null. Syntax: LENGTH (Column / Expression)
SQL> SELECT 2 ORACLE String, 3 LENGTH ('ORACLE') Length 4 FROM DUAL; STRING LENGTH ------ ---------ORACLE 6

73

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row selected. SQL> SELECT 2 LENGTH (ename) ||' Characters exit in '||INITCAP (Ename) ||'''s Name.' 3 AS "Names and Lengths" 4 FROM EMP; Names and Lengths -----------------------------------------------------------------------------5 Characters exit in Smith's Name. 5 Characters exit in Allen's Name. 4 Characters exit in Ward's Name. 5 Characters exit in Jones's Name. 6 Characters exit in Martin's Name. 5 Characters exit in Blake's Name. 5 Characters exit in Clark's Name. 5 Characters exit in Scott's Name. 4 Characters exit in King's Name. 6 Characters exit in Turner's Name. 5 Characters exit in Adams's Name. 5 Characters exit in James's Name. 4 Characters exit in Ford's Name. 6 Characters exit in Miller's Name. 14 rows selected. SQL> SELECT INITCAP (ename), job 2 FROM EMP 3 WHERE LENGTH (Job) =7; INITCAP (EN JOB ---------- --------Jones MANAGER Blake MANAGER Clark MANAGER Scott ANALYST Ford ANALYST 5 rows selected. SQL> SELECT INITCAP (ename), job 2 FROM EMP 3 WHERE 4 SUBSTR (job, 4, LENGTH (SUBSTR (Job, 4, 3))) ='AGE'; INITCAP (EN JOB ---------- --------Jones MANAGER Blake MANAGER Clark MANAGER 3 rows selected.

Instring Function 74 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

It returns the numeric position of a named character.

Syntax: INSTR (Column / Expression, char, m, n) The instr functions search string for substring that is supplied. The function returns an integer indicating the position of the character in string that is the first character of this occurrence. Searches for column or expression beginning with its mth character for the nth occurrence of char2, and returns the position of the character in char1, that is the first character of this occurrence. M can be positive or negative, if negative searches backward from the end of column or expression. The value of n should be positive. The default values of both m and n are 1. The return value is relative to the beginning of char1 regardless of the value of m, and is expressed in characters. If the search is unsuccessful, the return value is zero.
SQL> SELECT 2 STRING String, 3 INSTR ('STRING','R') Instring 4 FROM DUAL; STRING INSTRING ------ ---------STRING 3 1 row selected. SQL> SELECT 2 CORPORATE FOOR' String, 3 INSTR ('CORPORATE FOOR','OR', 3, 2) Instring 4 FROM DUAL; STRING INSTRING -------------- ---------CORPORATE FOOR 13 1 row selected. SQL> SELECT 2 CORPORATE FOOR' String, 3 INSTR ('CORPORATE FOOR','OR',-3, 2) Instring 4 FROM DUAL; STRING INSTRING -------------- ---------CORPORATE FOOR 2 1 row selected. SQL> SELECT job, INSTR (job,'A', 1, 2) Position

75

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 FROM EMP 3 WHERE job='MANAGER'; JOB POSITION --------- ---------MANAGER 4 MANAGER 4 MANAGER 4 3 rows selected. SQL> SELECT job, INSTR (job,'A', 2, 2) Position 2 FROM EMP 3 WHERE job='MANAGER'; JOB POSITION --------- ---------MANAGER 4 MANAGER 4 MANAGER 4 3 rows selected. SQL> SELECT job, INSTR (job,'A', 3, 2) Position 2 FROM EMP 3 WHERE job='MANAGER'; JOB POSITION --------- ---------MANAGER 0 MANAGER 0 MANAGER 0 3 rows selected. SQL> SELECT job, INSTR (job,'A', 2) Position 2 FROM EMP 3 WHERE job='MANAGER'; JOB POSITION --------- ---------MANAGER 2 MANAGER 2 MANAGER 2 3 rows selected.

Lpad Function Pads the character value right justified to a total width of n character positions. The default padding character is space. Syntax: LPAD (Char1, n, char2) 76 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT 2 Page 1' string, 3 LPAD ('Page 1', 15,'*.') Lpadded 4 FROM DUAL; STRING LPADDED ------ --------------Page 1 *.*.*.*.*Page 1 1 row selected. SQL> SELECT 2 Page 1' String, 3 LPAD ('Page 1', 15) Lpadded 4 FROM DUAL; STRING LPADDED ------ --------------Page 1 Page 1 1 row selected. SQL> SELECT ename, LPAD (ename, 10,'-') Lpadded 2 FROM EMP 3 WHERE Sal>=2500; ENAME LPADDED ---------- ---------JONES -----JONES BLAKE -----BLAKE SCOTT -----SCOTT KING ------KING FORD ------FORD 5 rows selected.

Rpad Function Pads the character value left justified to a total width of n character positions. The default padding character is space. Syntax: RPAD (Char1, n, char2)
SQL> SELECT 2 Page 1' string, 3 rPAD ('Page 1', 15,'*.') Rpadded 4 FROM DUAL; STRING RPADDED ------ --------------Page 1 Page 1*.*.*.*.*

77

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row selected. SQL> SELECT 2 Page 1' String, 3 RPAD ('Page 1', 15) Rpadded 4 FROM DUAL; STRING RPADDED ------ --------------Page 1 Page 1 1 row selected. SQL> SELECT ename, RPAD (ename, 10,'-') Rpadded 2 FROM EMP 3 WHERE Sal>=2500; ENAME RPADDED ---------- ---------JONES JONES----BLAKE BLAKE----SCOTT SCOTT----KING KING-----FORD FORD-----5 rows selected. SQL> SELECT ename, 2 LPAD (ename, 10,'-') Lpadded, 3 RPAD (ename, 10,'-') Rpadded 4 FROM EMP; ENAME LPADDED RPADDED ---------- ---------- ---------SMITH -----SMITH SMITH----ALLEN -----ALLEN ALLEN----WARD ------WARD WARD-----JONES -----JONES JONES----MARTIN ----MARTIN MARTIN---BLAKE -----BLAKE BLAKE----CLARK -----CLARK CLARK----SCOTT -----SCOTT SCOTT----KING ------KING KING-----TURNER ----TURNER TURNER---ADAMS -----ADAMS ADAMS----JAMES -----JAMES JAMES----FORD ------FORD FORD-----MILLER ----MILLER MILLER---14 rows selected. SQL> SELECT Ename, 2 LPAD (RPAD (ename, 10,'-'), 15,'-') Centered

78

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 FROM EMP; ENAME CENTERED ---------- --------------SMITH -----SMITH----ALLEN -----ALLEN----WARD -----WARD-----JONES -----JONES----MARTIN -----MARTIN---BLAKE -----BLAKE----CLARK -----CLARK----SCOTT -----SCOTT----KING -----KING-----TURNER -----TURNER---ADAMS -----ADAMS----JAMES -----JAMES----FORD -----FORD-----MILLER -----MILLER---14 rows selected.

Ltrim Function It enables to trim heading characters from a character string. All the leftmost characters that appear in the set are removed. Syntax: LTIRM (Char, SET)
SQL> SELECT 2 xtzXxyLAST WORD' String, 3 LTRIM ('xtzXxyLAST WORD','xy') Ltrimmed 4 FROM DUAL; STRING LTRIMMED --------------- -------------XtzXxyLAST WORD tzXxyLAST WORD 1 row selected. SQL> SELECT job, LTRIM (job,'MAN') Ltrimmed 2 FROM EMP 3 WHERE job LIKE 'MANAGER'; JOB LTRIMMED --------- --------MANAGER GER MANAGER GER MANAGER GER 3 rows selected.

Rtrim Function It enables the trimming of trailing characters from a characters string. All the right most characters that appear in the set are removed. 79 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Syntax: RTRIM (Char, SET)


SQL> SELECT 2 BROWNINGyxXxy string, 3 RTRIM ('BROWNINGyxXxy','xy') Rtrimmed 4 FROM DUAL; STRING RTRIMMED ------------- ----------BROWNINGyxXxy BROWNINGyxX 1 row selected. SQL> ED Wrote file afiedt.buf 1 SELECT job, RTRIM (job,'ER') Job 2 FROM EMP 3* WHERE LTRIM (Job,'MAN') LIKE 'GER' SQL> / JOB JOB --------- --------MANAGER MANAG MANAGER MANAG MANAGER MANAG 3 rows selected.

Trim Function (8i) It enables to trim heading or trailing character or both from a character string. If leading is specified concentrates on leading characters. If trailing is specified concentrates on trailing characters. If both or none is specified concentrates both on leading and trailing. Returns the varchar2 type. Syntax: TRIM (LEADING / TRAILING / BOTH, Trimchar FROM TrimSource)
SQL> ED Wrote file afiedt.buf 1 SELECT 2 MITHSS String, 3 TRIM ('S' FROM 'MITHSS') Trimmed 4* FROM DUAL SQL> / STRING TRIM ------ ---MITHSS MITH

80

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row selected. SQL> SELECT 2 SSMITH String, 3 TRIM ('S' FROM 'SSMITH') Trimmed 4 FROM DUAL; STRING TRIM ------ ---SSMITH MITH 1 row selected. SQL> SELECT 2 SSMITHSS String, 3 TRIM ('S' FROM 'SSMITHSS') Trimmed 4 FROM DUAL; SRING TRIM -------- ---SSMITHSS MITH 1 row selected. SQL> SELECT 2 SSMITHSS String, 3 TRIM (TRAILING 'S' FROM 'SSMITHSS') Trimmed 4 FROM DUAL; STRING TRIMME -------- -----SSMITHSS SSMITH 1 row selected. SQL> SELECT 2 SSMITHSS String, 3 TRIM (LEADING 'S' FROM 'SSMITHSS') Trimmed 4 FROM DUAL; STRING TRIMME -------- -----SSMITHSS MITHSS 1 row selected. SQL> SELECT 2 SSMITHSS String, 3 TRIM (BOTH 'S' FROM 'SSMITHSS') Trimmed 4 FROM DUAL; STRING TRIM -------- ----

81

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SSMITHSS MITH 1 row selected.

Replace Function It returns the every occurrence of search string replaced by the replacement string. If the replacement string is omitted or null, all occurrences of search string are removed. It substitutes one string for another as well as removes character strings. Syntax: REPLACE (Char, Search_Str, Replace_Str)
SQL> SELECT 2 JACK AND JUE' String, 3 REPLACE ('JACK AND JUE','J','BL') Replaced 4 FROM DUAL; STRING REPLACED ------------ -------------JACK AND JUE BLACK AND BLUE 1 row selected. SQL> SELECT ename, 2 REPLACE (JOB,'MAN','DAM') Replaced 3 FROM EMP; ENAME REPLACED ---------- --------------------------SMITH CLERK ALLEN SALESDAM WARD SALESDAM JONES DAMAGER MARTIN SALESDAM BLAKE DAMAGER CLARK DAMAGER SCOTT ANALYST KING PRESIDENT TURNER SALESDAM ADAMS CLERK JAMES CLERK FORD ANALYST MILLER CLERK 14 rows selected. SQL> ED Wrote file afiedt.buf 1 SELECT ename,

82

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 REPLACE (JOB,'MAN','DAM') Replaced 3 FROM EMP 4* WHERE job='MANAGER' SQL> / ENAME REPLACED ---------- --------------------------JONES DAMAGER BLAKE DAMAGER CLARK DAMAGER 3 rows selected. SQL> SELECT job, REPLACE (job,'P') 2 FROM EMP 3 WHERE job='PRESIDENT'; JOB REPLACE (J --------- --------PRESIDENT RESIDENT 1 row selected. SQL> ED Wrote file afiedt.buf 1 SELECT job, 2 REPLACE (job,'MAN','EXCUTIVE') 3 FROM EMP 4* WHERE job='SALESMAN' SQL> / JOB REPLACE (JOB,'MAN','EXCUTIVE') --------- -----------------------------------------------------------------------SALESMAN SALESEXCUTIVE SALESMAN SALESEXCUTIVE SALESMAN SALESEXCUTIVE SALESMAN SALESEXCUTIVE 4 rows selected.

Translate Function Used to translate character by character in a string. Syntax: TRANSLATE (Char, From, To) It returns a char with all occurrences of each character in From replaced by its corresponding character in To. Characters in char that are not in from are not replaced. The argument from can contain more characters that to. If the extra character appears in char, they are removed from the return value. 83 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT job, TRANSLATE (job,'P','') 2 FROM EMP 3 WHERE job='PRESIDENT'; JOB TRANSLATE --------- --------PRESIDENT 1 row selected. SQL> SELECT job, 2 TRANSLATE (job,'MN','DM') 3 FROM EMP 4 WHERE job='MANAGER'; JOB TRANSLATE --------- --------MANAGER DAMAGER MANAGER DAMAGER MANAGER DAMAGER 3 rows selected. SQL> SELECT job, 2 TRANSLATE (job,'A','O') 3 FROM EMP 4 WHERE job='SALESMAN'; JOB TRANSLATE --------- --------SALESMAN SOLESMON SALESMAN SOLESMON SALESMAN SOLESMON SALESMAN SOLESMON 4 rows selected.

Chr Function It returns a character having the ASCII equivalent to n. It returns the equivalent for n in database character set or national character set. Syntax: CHR (n) CHR (n USING NCHAR_CS)
SQL> SELECT CHR (67) ||CHR (65) ||CHR (84) Sample 2 FROM DUAL; SAM --CAT

84

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row selected. SQL> SELECT 2 CHR (16705 Using NCHAR_CS) 3 FROM DUAL; C 1 row selected.

ASCII Function It returns the ASCII representation in the character database set of the first characters of the char. Syntax: ASCII (Char)

SQL> SELECT ASCII ('A'), ASCII ('APPLE') 2 FROM DUAL; ASCII (a') ASCII ('APPLE') ---------- -------------65 65 1 row selected.

NUMBER Functions These functions accept numeric input and return numeric values as output. Many functions return values that are accurate to 38 decimal digits. Round Function Syntax: ROUND (n, m) It returns n rounded to m places right of the decimal point. If m is omitted, n is rounded to 0, places. M can be negative, and rounds off the digits to the left of the decimal point. M must be an integer.
SQL> SELECT 15.193 Num1, ROUND (15.193, 1) Rounded 2 FROM DUAL; NUM1 ROUNDED ---------- ---------15.193 15.2 1 row selected. SQL> SELECT 15.193 Num1, ROUND (15.193,-1) Rounded

85

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 FROM DUAL; NUM1 ROUNDED ---------- ---------15.193 20 1 row selected. SQL> SELECT 2 45.923 Num1, 3 ROUND (45.923, 2) Rounded, 4 ROUND (45.923, 0) Rounded, 5 ROUND (45.923,-1) Rounded 6 FROM DUAL; NUM1 ROUNDED ROUNDED ---------- ---------- ---------- ---------45.923 45.92 46 50 1 row selected. ROUNDED

Truncate Function Syntax: TRUNC (n, m) It returns n truncated to m decimal places. If m is omitted, n is truncated to 0 decimal places. N can be negative to truncate m digits left of the decimal point.
SQL> ED Wrote file afiedt.buf 1 SELECT 2 15.79 Num1, 3 TRUNC (15.79, 1) Truncated 4* FROM DUAL SQL> / NUM1 TRUNCATED ---------- ---------15.79 15.7 1 row selected. SQL> SELECT 2 15.79 Num1, 3 TRUNC (15.79,-1) Truncated 4 FROM DUAL; NUM1 TRUNCATED ---------- ---------15.79 10 1 row selected.

86

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> ED Wrote file afiedt.buf 1 SELECT 2 45.923 Num1, 3 TRUNC (45.923, 2) Truncated, 4 TRUNC (45.923) Truncated, 5 TRUNC (45.923, 1) Truncated, 6 TRUNC (45.923,-1) Truncated 7* FROM DUAL SQL> / NUM1 TRUNCATED TRUNCATED TRUNCATED TRUNCATED ---------- ---------- ---------- ---------- ---------45.923 45.92 45 45.9 40 1 row selected.

Ceil Function Syntax: CEIL (n) Returns the smallest integer greater than or equal to n. The adjustment is done to the highest nearest decimal value. SQL> SELECT 15.7 Num1, CEIL (15.7) Celled 2 FROM DUAL; NUM1 CELLED ---------- ---------15.7 16 1 row selected. SQL> SELECT 2 14.27 Num1, 3 CEIL (14.27) Celled, 4 CEIL (14.2) Celled, 5 CEIL (14) Celled 6 FROM DUAL; NUM1 CELLED CELLED ---------- ---------- ---------- ---------14.27 15 15 14 1 row selected. Floor Function Syntax: FLOOR (n) Returns the largest integer less than or equal than n. The adjustment is done to the lowest nearest decimal values. 87 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By CELLED

[ K . Sekhar ]

SQL> SELECT 15.7 Num1, 2 FLOOR (15.7) Floor 3 FROM DUAL; NUM1 FLOOR ---------- ---------15.7 15 1 row selected. SQL> SELECT 2 14.27 Num1, 3 FLOOR (14.27) Floor, 4 FLOOR (14.2) Floor, 5 FLOOR (14) Floor 6 FROM DUAL; NUM1 FLOOR FLOOR ---------- ---------- ---------- ---------14.27 14 14 14 1 row selected. FLOOR

MODULUS Function Syntax: MOD (m, n) It returns remainder of m divided by n. It returns m if n is 0.


SQL> Ed Wrote file afiedt.buf 1 SELECT 2 MOD (11, 4) Modulus, 3 MOD (10, 2) Modulus 4* FROM DUAL SQL> / MODULUS MODULUS ---------- ---------3 0 1 row selected.

Power Function Syntax: POWER (m, n) Returns m raised to the nth power. The base m and the exponent n can be any numbers. 88 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

If m is negative, n must be an integer.

SQL> SELECT 2 POWER (3, 2) Power, 3 POWER (-3, 2) Power 4 FROM DUAL; POWER POWER ---------- ---------9 9 1 row selected. SQL> SELECT 2 POWER (-3.5,-2) Power, 3 POWER (3,-2.5) Power 4 FROM DUAL; POWER POWER ---------- ---------.081632653 .06415003 1 row selected. SQL> SELECT 2 POWER (-3.5, 2.5) Power, 3 POWER (3.5,-2.5) Power 4 FROM DUAL; POWER (-3.5, 2.5) Power, * ERROR at line 2: ORA-01428: argument '-3.5' is out of range

Square Root Function Syntax: SQRT (n) It returns root of n as real value. The value of n cannot be negative.
SQL> SELECT 2 SQRT (25) 3 FROM DUAL; SQRT (25) ---------5 1 row selected.

Absolute Function

89

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Syntax: ABS (n) It returns the absolute value of n.


SQL> SELECT ABS (-15) 2 FROM DUAL; ABS (-15) ---------15 1 row selected. SQL> SELECT sal, comm, sal-comm, ABS (Sal-comm) 2 FROM EMP 3 WHERE comm=1400; SAL COMM SAL-COMM ABS (SAL-COMM) ---------- ---------- ---------- ------------1250 1400 -150 150 1 row selected.

Sign Function Syntax: SIGN (n) It returns the sign, specification of a number. If n < 0, Returns -1. If n = 0, Returns 0. If n > 0, Returns 1.
SQL> SELECT SIGN (-15), SIGN (15), SIGN (0) 2 FROM DUAL; SIGN (-15) SIGN (15) ---------- ---------- ----------1 1 0 1 row selected. SQL> SELECT sal, comm, SIGN (Sal-comm) 2 FROM EMP 3 WHERE SIGN (Sal-comm) =-1; SAL COMM SIGN (SAL-COMM) ---------- ---------- -------------1250 1400 -1 1 row selected. SIGN (0)

Working with Dates 90 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Oracle stores dates in an internal numeric format. The dates in oracle range from January 1, 4712 BC to December 31, 9999 AD. The default display and input format for any date is DD-MON-YY. The internal date format represents Century <- Year <- Month <- Day <- Hours <- Minutes <- Seconds

Sysdate: It is a date function that returns current date and time. Sysdate is generally selected upon a dummy table.
SQL> SELECT SYSDATE 2 FROM DUAL; SYSDATE --------10-SEP-10 1 row selected.

Date Arithmetic As database stores dates as numbers, arithmetic operations can be implemented. Number constants can be added or subtracted upon dates. The operations that can be applied are Date + Number -> Returns date. Adds number of days to a date. Date Number -> Returns date. Subtracts number of days from a date. Date Date -> Returns number of days. Subtracts one date from another date. Date + Number / 24 -> Returns date. Adds number of hours to a date.
SQL> SELECT SYSDATE, SYSDATE + 3 2 FROM DUAL; SYSDATE SYSDATE+3 --------- --------10-SEP-10 13-SEP-10 1 row selected. SQL> SELECT SYSDATE, SYSDATE - 3, SYSDATE + 72/24 2 FROM DUAL; SYSDATE SYSDATE-3 SYSDATE+7 --------- --------- --------10-SEP-10 07-SEP-10 13-SEP-10 1 row selected.

91

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT ename, hiredate, hiredate + 3 2 FROM EMP; ENAME HIREDATE HIREDATE+ ---------- --------- --------SMITH 17-DEC-80 20-DEC-80 ALLEN 20-FEB-81 23-FEB-81 WARD 22-FEB-81 25-FEB-81 JONES 02-APR-81 05-APR-81 MARTIN 28-SEP-81 01-OCT-81 BLAKE 01-MAY-81 04-MAY-81 CLARK 09-JUN-81 12-JUN-81 SCOTT 19-APR-87 22-APR-87 KING 17-NOV-81 20-NOV-81 TURNER 08-SEP-81 11-SEP-81 ADAMS 23-MAY-87 26-MAY-87 JAMES 03-DEC-81 06-DEC-81 FORD 03-DEC-81 06-DEC-81 MILLER 23-JAN-82 26-JAN-82 14 rows selected. SQL> SELECT ename, hiredate, hiredate - 3 2 FROM EMP; ENAME HIREDATE HIREDATE---------- --------- --------SMITH 17-DEC-80 14-DEC-80 ALLEN 20-FEB-81 17-FEB-81 WARD 22-FEB-81 19-FEB-81 JONES 02-APR-81 30-MAR-81 MARTIN 28-SEP-81 25-SEP-81 BLAKE 01-MAY-81 28-APR-81 CLARK 09-JUN-81 06-JUN-81 SCOTT 19-APR-87 16-APR-87 KING 17-NOV-81 14-NOV-81 TURNER 08-SEP-81 05-SEP-81 ADAMS 23-MAY-87 20-MAY-87 JAMES 03-DEC-81 30-NOV-81 FORD 03-DEC-81 30-NOV-81 MILLER 23-JAN-82 20-JAN-82 14 rows selected. SQL> SELECT ename, hiredate, SYSDATE - hiredate 2 FROM EMP; ENAME HIREDATE SYSDATE-HIREDATE ---------- --------- ---------------SMITH 17-DEC-80 10859.8577 ALLEN 20-FEB-81 10794.8577 WARD 22-FEB-81 10792.8577 JONES 02-APR-81 10753.8577 MARTIN 28-SEP-81 10574.8577

92

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

BLAKE 01-MAY-81 10724.8577 CLARK 09-JUN-81 10685.8577 SCOTT 19-APR-87 8545.85765 KING 17-NOV-81 10524.8577 TURNER 08-SEP-81 10594.8577 ADAMS 23-MAY-87 8511.85765 JAMES 03-DEC-81 10508.8577 FORD 03-DEC-81 10508.8577 MILLER 23-JAN-82 10457.8577 14 rows selected. SQL> SELECT ename, (SYSDATE - hiredate) / 7 Weeks 2 FROM EMP 3 WHERE deptno=10; ENAME WEEKS ---------- ---------CLARK 1526.55115 KING 1503.55115 MILLER 1493.97973 3 rows selected.

Date Functions Add Months Function Syntax: ADD_MONTHS (D, n) It returns the date D plus or minus n months. The argument n can be any positive or negative integer.
SQL> SELECT SYSDATE, ADD_MONTHS (hiredate, 2) 2 FROM EMP 3 WHERE deptno=20; SYSDATE ADD_MONTH --------- --------10-SEP-10 17-FEB-81 10-SEP-10 02-JUN-81 10-SEP-10 19-JUN-87 10-SEP-10 23-JUL-87 10-SEP-10 03-FEB-82 5 rows selected. SQL> Ed Wrote file afiedt.buf 1 SELECT Sal, ADD_MONTHS (hiredate, 2) 2 FROM EMP 3* WHERE deptno=20 SQL> /

93

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SAL ADD_MONTH ---------- --------800 17-FEB-81 2975 02-JUN-81 3000 19-JUN-87 1100 23-JUL-87 3000 03-FEB-82 5 rows selected. SQL> SELECT SYSDATE, ADD_MONTHS (SYSDATE, 2) 2 FROM DUAL; SYSDATE ADD_MONTH --------- --------10-SEP-10 10-NOV-10 1 row selected.

Months_between Function Syntax: MONTHS_BETWEN (D1, D2) It returns number of months between dates d1 and d2. It d1 is later than d2 the result is positive, else negative. If d1 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, SYSDATE, 2 MONTHS_BETWEEN (SYSDATE, hiredate) 3 FROM EMP; ENAME HIREDATE SYSDATE MONTHS_BETWEEN (SYSDATE, HIREDATE) ---------- --------- --------- -------------------------------SMITH 17-DEC-80 10-SEP-10 356.802048 ALLEN 20-FEB-81 10-SEP-10 354.705274 WARD 22-FEB-81 10-SEP-10 354.640758 JONES 02-APR-81 10-SEP-10 353.285919 MARTIN 28-SEP-81 10-SEP-10 347.44721 BLAKE 01-MAY-81 10-SEP-10 352.318177 CLARK 09-JUN-81 10-SEP-10 351.060113 SCOTT 19-APR-87 10-SEP-10 280.737532 KING 17-NOV-81 10-SEP-10 345.802048 TURNER 08-SEP-81 10-SEP-10 348.092371 ADAMS 23-MAY-87 10-SEP-10 279.6085 JAMES 03-DEC-81 10-SEP-10 345.253661 FORD 03-DEC-81 10-SEP-10 345.253661 MILLER 23-JAN-82 10-SEP-10 343.6085 14 rows selected. SQL> SELECT Empno, hiredate, 2 MONTHS_BETWEEN (SYSDATE, hiredate) 3 FROM EMP

94

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

4 WHERE MONTHS_BETWEEN (SYSDATE, hiredate) <200; No rows selected

Next Day Function Syntax: NEXT_DAY (d, Char) It returns the date of the first week day named by char that is later than the dated. The char must be day of the week in the sessions date language. The day of the week can be full name or the abbreviation.
SQL> SELECT SYSDATE, NEXT_DAY (SYSDATE,'WED') 2 FROM DUAL; SYSDATE NEXT_DAY ( --------- --------10-SEP-10 15-SEP-10 1 row selected. SQL> SELECT sal, hiredate, NEXT_DAY (hiredate,'MONDAY') 2 FROM EMP; SAL HIREDATES NEXT_DAY ( ---------- --------- --------800 17-DEC-80 22-DEC-80 1600 20-FEB-81 23-FEB-81 1250 22-FEB-81 23-FEB-81 2975 02-APR-81 06-APR-81 1250 28-SEP-81 05-OCT-81 2850 01-MAY-81 04-MAY-81 2450 09-JUN-81 15-JUN-81 3000 19-APR-87 20-APR-87 5000 17-NOV-81 23-NOV-81 1500 08-SEP-81 14-SEP-81 1100 23-MAY-87 25-MAY-87 950 03-DEC-81 07-DEC-81 3000 03-DEC-81 07-DEC-81 1300 23-JAN-82 25-JAN-82 14 rows selected.

Last_Day Function Syntax: LAST_DAY (D) It returns the date of the last day of the month that containsd. Mostly used to determine how many days are left in the current month.
SQL> SELECT SYSDATE, LAST_DAY (SYSDATE) LastDay 2 FROM DUAL; SYSDATE LASTDAY

95

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

--------- --------10-SEP-10 30-SEP-10 1 row selected. SQL> SELECT LAST_DAY (SYSDATE) Last, SYSDATE, 2 LAST_DAY (SYSDATE)-SYSDATE Daysleft 3 FROM DUAL; LAST SYSDATE DAYSLEFT --------- --------- ---------30-SEP-10 10-SEP-10 20 1 row selected.

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 SYSDATE, ROUND (SYSDATE,'DAY') 2 FROM DUAL 3; SYSDATE ROUND (SYS --------- --------10-SEP-10 12-SEP-10 1 row selected. SQL> SELECT SYSDATE, ROUND (SYSDATE,'MONTH') 2 FROM DUAL; SYSDATE ROUND (SYS --------- --------10-SEP-10 01-SEP-10 1 row selected. SQL> SELECT SYSDATE, ROUND (SYSDATE,'YEAR') 2 FROM DUAL; SYSDATE ROUND (SYS --------- --------10-SEP-10 01-JAN-11 1 row selected.

Truncating Dates Syntax: TRUNC (Date, Format) 96 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Date is truncated to the nearest date with the time portion of the day truncated to the specified unit. If format is omitted date is truncated to the nearest day.

SQL> SELECT SYSDATE, TRUNC (SYSDATE,'DAY') 2 FROM DUAL; SYSDATE TRUNC (SYS --------- --------10-SEP-10 05-SEP-10 1 row selected. SQL> SELECT SYSDATE, TRUNC (SYSDATE,'MONTH') 2 FROM DUAL; SYSDATE TRUNC (SYS --------- --------10-SEP-10 01-SEP-10 1 row selected. SQL> SELECT SYSDATE, TRUNC (SYSDATE,'YEAR') 2 FROM DUAL; SYSDATE TRUNC (SYS --------- --------10-SEP-10 01-JAN-10 1 row selected.

Conversion Functions The conversion functions convert a value from one data type to another. The data type conversion in oracle is of two types Implicit data type conversion Explicit data type conversion Implicit Data type Conversion Implicit data type conversion work according to the convention specified by oracle. The assignment succeeds if the oracle server can convert the data type of the value. Char to number conversions succeed only if the character strings represent a valid number. Char to number conversions succeed only if the character strings represent the default format of date DD-MON-YY. In Assignment Operation Varchar2 / char -> number Varchar2 / char -> date Number -> varchar2 Date -> varchar2 97 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

In Expressions Varchar2 / char Varchar2 / char

-> number -> date

Explicit Data type Conversion Sql provides three function to convert a value from one data type to another. The explicit conversion functions are To_cahr -> to character conversion. To_date -> to date conversion. To_number -> to number conversion. To_char Conversion Function This function can be used in two different flavors. To_char ( number conversion ) To_char ( date conversion ) To_char (number conversion) Syntax: TO_CHAR (NUMBER, fmt, nslparms) Converts number of number data type to a value of varcahr2 data type. Fmt is the optional number format, that can be used. The nlsparms specifies the characters returned by the number format element. To_char ( date conversion ) Syntax: TO_CHAR( DATE, fmt, nlsparams ) Converts date of date data type to a value of varchar2 data type in the format specified. fmt is the optional date format that can be used. The nlsparams specifies the language in which month and day names and abbreviations are returned. Working With Number Format Models Format Model A format model is a character literal that describes the format of date or number data stored in a character string. Decimal Indicator: D -> 99D99 It returns the specified position of the decimal character. The default delimiter is period . Only one decimal indicator can be specified in a number format model.
SQL> SELECT 1234,TO_CHAR(1234,'999D99') 2 FROM DUAL; 1234 TO_CHAR ---------- -------

98

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1234 ####### 1 row selected. SQL> SELECT 1234,TO_CHAR(1234,'99D99') 2 FROM DUAL; 1234 TO_CHA ---------- -----1234 ###### 1 row selected.

Scientific Notation Indicator: EEEE -> 9.9EEEE Returns a numeric value using scientific notation.
SQL> SELECT 2 1234, 3 TO_CHAR(1234,'9.9EEEE'), 4 TO_CHAR(1234,'9.99EEEE') 5 FROM DUAL; 1234 TO_CHAR(1 TO_CHAR(12 ---------- --------- ---------1234 1.2E+03 1.23E+03 1 row selected.

Group Separator: G -> 9G999 Returns the specified position of the group separator. Multiple group separators can be specified.
SQL> SELECT 1234567,TO_CHAR(1234567,'99G99G999') 2 FROM DUAL; 1234567 TO_CHAR(12 ---------- ---------1234567 12,34,567 1 row selected. SQL> SELECT Sal,TO_CHAR(sal,'99G99D99') 2 FROM EMP; SAL TO_CHAR(S ---------- --------800 8,00.00 1600 16,00.00 1250 12,50.00 2975 29,75.00 1250 12,50.00 2850 28,50.00 2450 24,50.00

99

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3000 5000 1500 1100 950 3000 1300

30,00.00 50,00.00 15,00.00 11,00.00 9,50.00 30,00.00 13,00.00

14 rows selected.

Local Currency Indicator: L -> L999 OR 999L Returns the specified position of the local currency symbol.
SQL> SELECT 1234,TO_CHAR(1234,'L9999') 2 FROM DUAL; 1234 TO_CHAR(1234,'L ---------- --------------1234 $1234 1 row selected. SQL> SELECT sal,TO_CHAR(sal,'L999999') Currency 2 FROM EMP 3 WHERE deptno=10; SAL CURRENCY ---------- ----------------2450 $2450 5000 $5000 1300 $1300 3 rows selected. SQL> SELECT Sal, 2 TO_CHAR(sal,'L99G999D99','NLS_CURRENCY=IndRupees') Sal 3 FROM EMP 4 WHERE Deptno=20; SAL SAL ---------- -------------------800 IndRupees800.00 2975 IndRupees2,975.00 3000 IndRupees3,000.00 1100 IndRupees1,100.00 3000 IndRupees3,000.00 5 rows selected.

Trailing Minus Indicator: MI -> 9999MI Returns negative value with a trailing minus sign -. Returns positive value with a trailing blank. MI Format should be declared as trailing argument only. 100 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> ED Wrote file afiedt.buf 1 SELECT -10000,TO_CHAR(-10000,'L99G999D99MI') 2* FROM DUAL SQL> / -10000 TO_CHAR(-10000,'L99G ---------- --------------------10000 $10,000.001 row selected. SQL> SELECT sal,comm, 2 TO_CHAR(comm-sal,'L99999MI') 3 FROM EMP 4 WHERE Deptno IN(10,20,30); SAL COMM TO_CHAR(COMM-SAL ---------- ---------- ---------------800 1600 300 $13001250 500 $7502975 1250 1400 $150 2850 2450 3000 5000 1500 0 $15001100 950 3000 1300 14 rows selected.

Negative Number Indicator PR -> 9999PR Returns negative number in <>. It can appear only as trailing declaration.
SQL> SELECT TO_CHAR(-1000,'L99G999D99PR') 2 FROM DUAL; TO_CHAR(-1000,'L99G99 --------------------<$1,000.00> 1 row selected. SQL> SELECT sal,comm,comm-sal, 2 TO_CHAR(comm-sal,'L99999PR')

101

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 FROM EMP; SAL COMM COMM-SAL TO_CHAR(COMM-SAL, ---------- ---------- ---------- ----------------800 1600 300 -1300 <$1300> 1250 500 -750 <$750> 2975 1250 1400 150 $150 2850 2450 3000 5000 1500 0 -1500 <$1500> 1100 950 3000 1300 14 rows selected.

Roman Number Indicator: RN OR rn RN -> Returns upper roman number. rn -> Returns lower roman number. The value can be an integer between 1 and 3999.
SQL> SELECT 1000,TO_CHAR(1000,'RN'),TO_CHAR(1000,'rn') 2 FROM DUAL; 1000 TO_CHAR(1000,'R TO_CHAR(1000,'R ---------- --------------- --------------1000 M m 1 row selected.

Sign Indicator: S -> S9999 or 9999S Returns negative value with a leading minus sign. Returns positive value with a leading plus sign. S can appear as first or last value.
SQL> SELECT 1000,TO_CHAR(1000,'S9999'), 2 TO_CHAR(-1000,'S9999') 3 FROM DUAL; 1000 TO_CH TO_CH ---------- ----- ----1000 +1000 -1000 1 row selected. SQL> SELECT TO_CHAR(1000,'9999S'), 2 TO_CHAR(-1000,'9999S')

102

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 FROM DUAL; TO_CH TO_CH ----- ----1000+ 10001 row selected. SQL> SELECT SAL,TO_CHAR(sal,'S999999'), 2 TO_CHAR(sal,'99999S') 3 FROM EMP; SAL TO_CHAR TO_CHA ---------- ------- -----800 +800 800+ 1600 +1600 1600+ 1250 +1250 1250+ 2975 +2975 2975+ 1250 +1250 1250+ 2850 +2850 2850+ 2450 +2450 2450+ 3000 +3000 3000+ 5000 +5000 5000+ 1500 +1500 1500+ 1100 +1100 1100+ 950 +950 950+ 3000 +3000 3000+ 1300 +1300 1300+ 14 rows selected. SQL> SELECT sal,comm,TO_CHAR(comm-sal,'S99999'), 2 TO_CHAR(comm-sal,'99999S') 3 FROM EMP; SAL COMM TO_CHA TO_CHA ---------- ---------- ------ -----800 1600 300 -1300 13001250 500 -750 7502975 1250 1400 +150 150+ 2850 2450 3000 5000 1500 0 -1500 15001100 950 3000 1300 14 rows selected.

103

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Hexadecimal Indicator: X -> XXXX Returns the hexadecimal value of the specified number of digits. If the number is not an integer, oracle rounds it to an integer. Accepts only positive values or 0.
SQL> SELECT 1000,TO_CHAR(1000,'XXXX') 2 FROM DUAL; 1000 TO_CH ---------- ----1000 3E8 1 row selected. SQL> SELECT ename,sal, 2 TO_CHAR(sal,'XXXXX') HexSal 3 FROM EMP; ENAME SAL HEXSAL ---------- ---------- -----SMITH 800 320 ALLEN 1600 640 WARD 1250 4E2 JONES 2975 B9F MARTIN 1250 4E2 BLAKE 2850 B22 CLARK 2450 992 SCOTT 3000 BB8 KING 5000 1388 TURNER 1500 5DC ADAMS 1100 44C JAMES 950 3B6 FORD 3000 BB8 MILLER 1300 514 14 rows selected.

Group Separator: , -> 9,999 Returns a comma in the specified position. Multiple commas can be specified.
SQL> SELECT 10000,TO_CHAR(10000,'99,999.99') 2 FROM DUAL; 10000 TO_CHAR(10 ---------- ---------10000 10,000.00 1 row selected. SQL> SELECT ename,sal,TO_CHAR(sal,'99,999.99')

104

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 FROM EMP; ENAME SAL TO_CHAR(SA ---------- ---------- ---------SMITH 800 800.00 ALLEN 1600 1,600.00 WARD 1250 1,250.00 JONES 2975 2,975.00 MARTIN 1250 1,250.00 BLAKE 2850 2,850.00 CLARK 2450 2,450.00 SCOTT 3000 3,000.00 KING 5000 5,000.00 TURNER 1500 1,500.00 ADAMS 1100 1,100.00 JAMES 950 950.00 FORD 3000 3,000.00 MILLER 1300 1,300.00 14 rows selected.

Decimal Indicator: . -> 99.99 Returns a decimal point, at the specified position. Only one period can be specified in a number format model.
SQL> SELECT ename,sal,TO_CHAR(sal,'99,999.99') 2 FROM EMP; ENAME SAL TO_CHAR(SA ---------- ---------- ---------SMITH 800 800.00 ALLEN 1600 1,600.00 WARD 1250 1,250.00 JONES 2975 2,975.00 MARTIN 1250 1,250.00 BLAKE 2850 2,850.00 CLARK 2450 2,450.00 SCOTT 3000 3,000.00 KING 5000 5,000.00 TURNER 1500 1,500.00 ADAMS 1100 1,100.00 JAMES 950 950.00 FORD 3000 3,000.00 MILLER 1300 1,300.00 14 rows selected. SQL> SELECT 10000,TO_CHAR(10000,'L99,999.99') 2 FROM DUAL; 10000 TO_CHAR(10000,'L99,9 ---------- -------------------10000 $10,000.00

105

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row selected. SQL> SELECT Ename,sal,TO_CHAR(sal,'L99,999.99') 2 FROM EMP; ENAME SAL TO_CHAR(SAL,'L99,999 ---------- ---------- -------------------SMITH 800 $800.00 ALLEN 1600 $1,600.00 WARD 1250 $1,250.00 JONES 2975 $2,975.00 MARTIN 1250 $1,250.00 BLAKE 2850 $2,850.00 CLARK 2450 $2,450.00 SCOTT 3000 $3,000.00 KING 5000 $5,000.00 TURNER 1500 $1,500.00 ADAMS 1100 $1,100.00 JAMES 950 $950.00 FORD 3000 $3,000.00 MILLER 1300 $1,300.00 14 rows selected.

Dollar Indicator: $ -> $9999 Returns value with a leading dollar sign.
SQL> SELECT 10000,TO_CHAR(10000,'$99,999.99') 2 FROM DUAL; 10000 TO_CHAR(100 ---------- ----------10000 $10,000.00 1 row selected. SQL> SELECT ename,sal,TO_CHAR(sal,'$99,999.99') 2 FROM EMP; ENAME SAL TO_CHAR(SAL ---------- ---------- ----------SMITH 800 $800.00 ALLEN 1600 $1,600.00 WARD 1250 $1,250.00 JONES 2975 $2,975.00 MARTIN 1250 $1,250.00 BLAKE 2850 $2,850.00 CLARK 2450 $2,450.00 SCOTT 3000 $3,000.00 KING 5000 $5,000.00 TURNER 1500 $1,500.00 ADAMS 1100 $1,100.00 JAMES 950 $950.00

106

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

FORD MILLER

3000 $3,000.00 1300 $1,300.00

14 rows selected.

Zero Indicator: 0 -> 0999 OR 9990 Returns leading or trailing zeros.


SQL> SELECT 10000,TO_CHAR(10000,'09999999'), 2 TO_CHAR(10000,'099999990') 3 FROM DUAL; 10000 TO_CHAR(1 TO_CHAR(10 ---------- --------- ---------10000 00010000 000010000 1 row selected. SQL> SELECT ename,sal,TO_CHAR(sal,'$099,999.99') 2 FROM EMP; ENAME SAL TO_CHAR(SAL, ---------- ---------- -----------SMITH 800 $000,800.00 ALLEN 1600 $001,600.00 WARD 1250 $001,250.00 JONES 2975 $002,975.00 MARTIN 1250 $001,250.00 BLAKE 2850 $002,850.00 CLARK 2450 $002,450.00 SCOTT 3000 $003,000.00 KING 5000 $005,000.00 TURNER 1500 $001,500.00 ADAMS 1100 $001,100.00 JAMES 950 $000,950.00 FORD 3000 $003,000.00 MILLER 1300 $001,300.00 14 rows selected.

Digit Place Marker: 9 -> 9999 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,'99999'), 2 TO_CHAR(600-1000,'999999') 3 FROM DUAL; 1000 600 TO_CHA TO_CHAR ---------- ---------- ------ ------1000 600 400 -400 1 row selected.

107

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT 20.25,20,TO_CHAR(20.25-20,'999999') 2 FROM DUAL; 20.25 20 TO_CHAR ---------- ---------- ------20.25 20 0 1 row selected.

ISO Currency Indicator: C -> C9999 Returns specified position of the ISO currency symbol.
SQL> SELECT 1000,TO_CHAR(1000,'C9999.99') 2 FROM DUAL; 1000 TO_CHAR(1000,'C ---------- --------------1000 USD1000.00 1 row selected. SQL> SELECT ename,sal,TO_CHAR(sal,'C9999.99') 2 FROM EMP; ENAME SAL TO_CHAR(SAL,'C9 ---------- ---------- --------------SMITH 800 USD800.00 ALLEN 1600 USD1600.00 WARD 1250 USD1250.00 JONES 2975 USD2975.00 MARTIN 1250 USD1250.00 BLAKE 2850 USD2850.00 CLARK 2450 USD2450.00 SCOTT 3000 USD3000.00 KING 5000 USD5000.00 TURNER 1500 USD1500.00 ADAMS 1100 USD1100.00 JAMES 950 USD950.00 FORD 3000 USD3000.00 MILLER 1300 USD1300.00 14 rows selected.

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. The total length of a date format model cannot exceed 22 characters. Date Format Elements A data format model is composed of one or more date format elements. 108 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

For input format models, format items cannot appear twice, and format items that represent 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, periods and colons.

AD or A.D. / BC or B.C. Indicator Indicates AD / BC with or without periods.


SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'AD') 2 FROM DUAL; SYSDATE TO --------- -11-SEP-10 AD 1 row selected. SQL> ED Wrote file afiedt.buf 1 SELECT TO_CHAR(SYSDATE,'B.C.'), 2 TO_CHAR(SYSDATE,'A.D.') 3* FROM DUAL SQL> / TO_C TO_C ---- ---A.D. A.D. 1 row selected. SQL> SELECT ename,sal,hiredate,TO_CHAR(hiredate,'A.D.') 2 FROM EMP; ENAME SAL HIREDATE TO_C ---------- ---------- --------- ---SMITH 800 17-DEC-80 A.D. ALLEN 1600 20-FEB-81 A.D. WARD 1250 22-FEB-81 A.D. JONES 2975 02-APR-81 A.D. MARTIN 1250 28-SEP-81 A.D. BLAKE 2850 01-MAY-81 A.D. CLARK 2450 09-JUN-81 A.D. SCOTT 3000 19-APR-87 A.D. KING 5000 17-NOV-81 A.D. TURNER 1500 08-SEP-81 A.D. ADAMS 1100 23-MAY-87 A.D. JAMES 950 03-DEC-81 A.D. FORD 3000 03-DEC-81 A.D. MILLER 1300 23-JAN-82 A.D. 14 rows selected.

109

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Meridian Indicator: AM OR A.M. / PM OR P.M. It indicates meridian indicator with or without periods.
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'A.M.'), 2 TO_CHAR(SYSDATE,'PM') 3 FROM DUAL; SYSDATE TO_C TO --------- ---- -11-SEP-10 A.M. AM 1 row selected. SQL> SELECT ename,sal,hiredate,TO_CHAR(hiredate,'AM') 2 FROM EMP; ENAME SAL HIREDATE TO ---------- ---------- --------- -SMITH 800 17-DEC-80 AM ALLEN 1600 20-FEB-81 AM WARD 1250 22-FEB-81 AM JONES 2975 02-APR-81 AM MARTIN 1250 28-SEP-81 AM BLAKE 2850 01-MAY-81 AM CLARK 2450 09-JUN-81 AM SCOTT 3000 19-APR-87 AM KING 5000 17-NOV-81 AM TURNER 1500 08-SEP-81 AM ADAMS 1100 23-MAY-87 AM JAMES 950 03-DEC-81 AM FORD 3000 03-DEC-81 AM MILLER 1300 23-JAN-82 AM 14 rows selected.

Century Indicator: CC/SCC Indicates the century, s prefixes BC date with -.


SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'CC-AD') 2 FROM DUAL; SYSDATE TO_CH --------- ----11-SEP-10 21-AD 1 row selected. SQL> SELECT sal,hiredate, 2 TO_CHAR(hiredate,'SCC-AD') 3 FROM EMP; SAL HIREDATE TO_CHA ---------- --------- ------

110

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

800 17-DEC-80 20-AD 1600 20-FEB-81 20-AD 1250 22-FEB-81 20-AD 2975 02-APR-81 20-AD 1250 28-SEP-81 20-AD 2850 01-MAY-81 20-AD 2450 09-JUN-81 20-AD 3000 19-APR-87 20-AD 5000 17-NOV-81 20-AD 1500 08-SEP-81 20-AD 1100 23-MAY-87 20-AD 950 03-DEC-81 20-AD 3000 03-DEC-81 20-AD 1300 23-JAN-82 20-AD 14 rows selected.

Numeric Week Day Indicator: D -> (1-7) Returns the week day number.
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'D') 2 FROM DUAL; SYSDATE T --------- 11-SEP-10 7 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'D') 2 FROM EMP; ENAME HIREDATE T ---------- --------- SMITH 17-DEC-80 4 ALLEN 20-FEB-81 6 WARD 22-FEB-81 1 JONES 02-APR-81 5 MARTIN 28-SEP-81 2 BLAKE 01-MAY-81 6 CLARK 09-JUN-81 3 SCOTT 19-APR-87 1 KING 17-NOV-81 3 TURNER 08-SEP-81 3 ADAMS 23-MAY-87 7 JAMES 03-DEC-81 5 FORD 03-DEC-81 5 MILLER 23-JAN-82 7 14 rows selected.

Week Day Spelling Indicator: -> Day. Pads to a length of 9 characters.


SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'DAY')

111

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 FROM DUAL; SYSDATE TO_CHAR(S --------- --------11-SEP-10 SATURDAY 1 row selected. SQL> ED Wrote file afiedt.buf 1 SELECT saL,hiredate,TO_CHAR(hiredate,'DAY') 2 FROM EMP 3* WHERE TO_CHAR(hiredate,'DAY')='WEDNESDAY' SQL> / SAL HIREDATE TO_CHAR(H ---------- --------- --------800 17-DEC-80 WEDNESDAY 1 row selected.

Month Day Indicator: DD It indicates the day of the month (1-31)


SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'DD-DAY') 2 FROM DUAL; SYSDATE TO_CHAR(SYSD --------- -----------11-SEP-10 11-SATURDAY 1 row selected. SQL> SELECT hiredate,TO_CHAR(hiredate,'DD-DAY') 2 FROM EMP; HIREDATE TO_CHAR(HIRE --------- -----------17-DEC-80 17-WEDNESDAY 20-FEB-81 20-FRIDAY 22-FEB-81 22-SUNDAY 02-APR-81 02-THURSDAY 28-SEP-81 28-MONDAY 01-MAY-81 01-FRIDAY 09-JUN-81 09-TUESDAY 19-APR-87 19-SUNDAY 17-NOV-81 17-TUESDAY 08-SEP-81 08-TUESDAY 23-MAY-87 23-SATURDAY 03-DEC-81 03-THURSDAY 03-DEC-81 03-THURSDAY 23-JAN-82 23-SATURDAY

112

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

14 rows selected. SQL> SELECT hiredate,TO_CHAR(hiredate,'DD-DAY') 2 FROM EMP 3 WHERE 4 TO_CHAR(hiredate,'DD-DAY')='03-WEDNESDAY'; no rows selected

Year Day Indicator: DDD It indicates the day of the year (1-366)
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'DDD') 2 FROM DUAL;

SYSDATE TO_ --------- --11-SEP-10 254 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'DDD') 2 FROM EMP 3 WHERE TO_CHAR(hiredate,'DAY')='WEDNESDAY'; ENAME HIREDATE TO_ ---------- --------- --SMITH 17-DEC-80 352 1 row selected.

Abbreviated Week Day: DY It indicates the abbreviated name of the week day.
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'D-DY-DAY') 2 FROM DUAL; SYSDATE TO_CHAR(SYSDATE --------- --------------11-SEP-10 7-SAT-SATURDAY 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'D-DY-DAY') 2 FROM EMP 3 WHERE Deptno IN(10,20); ENAME HIREDATE TO_CHAR(HIREDAT ---------- --------- --------------SMITH 17-DEC-80 4-WED-WEDNESDAY

113

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

JONES 02-APR-81 5-THU-THURSDAY CLARK 09-JUN-81 3-TUE-TUESDAY SCOTT 19-APR-87 1-SUN-SUNDAY KING 17-NOV-81 3-TUE-TUESDAY ADAMS 23-MAY-87 7-SAT-SATURDAY FORD 03-DEC-81 5-THU-THURSDAY MILLER 23-JAN-82 7-SAT-SATURDAY 8 rows selected.

ISO Standard Year Week Indicator: IW Specifies the week of the year (1 52 or 1 53) based on the ISO standard.
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'IW') 2 FROM DUAL; SYSDATE TO --------- -11-SEP-10 36 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'IW') 2 FROM EMP; ENAME HIREDATE TO ---------- --------- -SMITH 17-DEC-80 51 ALLEN 20-FEB-81 08 WARD 22-FEB-81 08 JONES 02-APR-81 14 MARTIN 28-SEP-81 40 BLAKE 01-MAY-81 18 CLARK 09-JUN-81 24 SCOTT 19-APR-87 16 KING 17-NOV-81 47 TURNER 08-SEP-81 37 ADAMS 23-MAY-87 21 JAMES 03-DEC-81 49 FORD 03-DEC-81 49 MILLER 23-JAN-82 03 14 rows selected.

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,IY,I.
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'IYYY') 2 FROM DUAL; SYSDATE TO_C

114

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

--------- ---11-SEP-10 2010 1 row selected. SQL> ED Wrote file afiedt.buf 1 SELECT ename,hiredate,TO_CHAR(hiredate,'IYYY') 2 FROM EMP 3* WHERE TO_CHAR(Hiredate,'DAY')='WEDNESDAY' SQL> / ENAME HIREDATE TO_C ---------- --------- ---SMITH 17-DEC-80 1980 1 row selected.

Four Digit Year Indicator: YYYY OR SYYYY Returns 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 SYSDATE,TO_CHAR(SYSDATE,'YYYY') 2 FROM DUAL; SYSDATE TO_C --------- ---11-SEP-10 2010 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'YYYY') 2 FROM EMP 3 WHERE deptno=20; ENAME HIREDATE TO_C ---------- --------- ---SMITH 17-DEC-80 1980 JONES 02-APR-81 1981 SCOTT 19-APR-87 1987 ADAMS 23-MAY-87 1987 FORD 03-DEC-81 1981 5 rows selected.

Spelled Year Indicator: YEAR OR SYEAR Returns the numerical year in spelling. S prefixes BC dates with -. 115 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'YEAR') 2 FROM DUAL; SYSDATE TO_CHAR(SYSDATE,'YEAR') --------- -----------------------------------------11-SEP-10 TWENTY TEN 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'YEAR') 2 FROM EMP; ENAME HIREDATE TO_CHAR(HIREDATE,'YEAR') ---------- --------- -----------------------------------------SMITH 17-DEC-80 NINETEEN EIGHTY ALLEN 20-FEB-81 NINETEEN EIGHTY-ONE WARD 22-FEB-81 NINETEEN EIGHTY-ONE JONES 02-APR-81 NINETEEN EIGHTY-ONE MARTIN 28-SEP-81 NINETEEN EIGHTY-ONE BLAKE 01-MAY-81 NINETEEN EIGHTY-ONE CLARK 09-JUN-81 NINETEEN EIGHTY-ONE SCOTT 19-APR-87 NINETEEN EIGHTY-SEVEN KING 17-NOV-81 NINETEEN EIGHTY-ONE TURNER 08-SEP-81 NINETEEN EIGHTY-ONE ADAMS 23-MAY-87 NINETEEN EIGHTY-SEVEN JAMES 03-DEC-81 NINETEEN EIGHTY-ONE FORD 03-DEC-81 NINETEEN EIGHTY-ONE MILLER 23-JAN-82 NINETEEN EIGHTY-TWO 14 rows selected.

Week of the Month Indicator: w Specifies the week of the month (1 5 ). Week starts on the first day of month and ends on the seventh day.
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'W') 2 FROM DUAL; SYSDATE T --------- 11-SEP-10 2 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,' 2 W') 3 FROM EMP; ENAME HIREDATE TO ---------- --------- -SMITH 17-DEC-80

116

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER 20-FEB-81 3 22-FEB-81 4 02-APR-81 1 28-SEP-81 4 01-MAY-81 1 09-JUN-81 2 19-APR-87 3 17-NOV-81 3 08-SEP-81 2 23-MAY-87 4 03-DEC-81 1 03-DEC-81 1 23-JAN-82 4

14 rows selected.

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> ED Wrote file afiedt.buf 1 SELECT SYSDATE,TO_CHAR(SYSDATE,'WW')

117

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2* FROM DUAL SQL> / SYSDATE TO --------- -11-SEP-10 37 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'WW') 2 FROM EMP; ENAME HIREDATE TO ---------- --------- -SMITH 17-DEC-80 51 ALLEN 20-FEB-81 08 WARD 22-FEB-81 08 JONES 02-APR-81 14 MARTIN 28-SEP-81 39 BLAKE 01-MAY-81 18 CLARK 09-JUN-81 23 SCOTT 19-APR-87 16 KING 17-NOV-81 46 TURNER 08-SEP-81 36 ADAMS 23-MAY-87 21 JAMES 03-DEC-81 49 FORD 03-DEC-81 49 MILLER 23-JAN-82 04 14 rows selected.

Quarter of the Year Indicator: Q Returns the quarter or the year. Quarter starting with the month of January and ending with every three months.
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'Q') 2 FROM DUAL; SYSDATE T --------- 11-SEP-10 3 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'Q') 2 FROM EMP; ENAME HIREDATE T ---------- --------- SMITH 17-DEC-80 4 ALLEN 20-FEB-81 1 WARD 22-FEB-81 1 JONES 02-APR-81 2

118

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

MARTIN 28-SEP-81 3 BLAKE 01-MAY-81 2 CLARK 09-JUN-81 2 SCOTT 19-APR-87 2 KING 17-NOV-81 4 TURNER 08-SEP-81 3 ADAMS 23-MAY-87 2 JAMES 03-DEC-81 4 FORD 03-DEC-81 4 MILLER 23-JAN-82 1 14 rows selected.

Julian Day Indicator: J Returns the Julian day of the given date. It is the number of days since January 1, 4712 BC. Numbers specified with J must be integers.
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'Q') 2 FROM DUAL; SYSDATE T --------- 11-SEP-10 3 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'Q') 2 FROM EMP; ENAME HIREDATE T ---------- --------- SMITH 17-DEC-80 4 ALLEN 20-FEB-81 1 WARD 22-FEB-81 1 JONES 02-APR-81 2 MARTIN 28-SEP-81 3 BLAKE 01-MAY-81 2 CLARK 09-JUN-81 2 SCOTT 19-APR-87 2 KING 17-NOV-81 4 TURNER 08-SEP-81 3 ADAMS 23-MAY-87 2 JAMES 03-DEC-81 4 FORD 03-DEC-81 4 MILLER 23-JAN-82 1 14 rows selected.

Numeric Month Indicator: MM 119 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Returns the numeric abbreviation of the month.

SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'MM-YYYY') 2 FROM DUAL; SYSDATE TO_CHAR --------- ------11-SEP-10 09-2010 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'DD-MM-YYYY') 2 FROM EMP 3 WHERE TO_CHAR(hiredate,'MM')=12; ENAME HIREDATE TO_CHAR(HI ---------- --------- ---------SMITH 17-DEC-80 17-12-1980 JAMES 03-DEC-81 03-12-1981 FORD 03-DEC-81 03-12-1981 3 rows selected.

Abbreviated Month Indicator : MON Returns the abbreviated name of the month.
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'MM-MON') 2 FROM DUAL; SYSDATE TO_CHA --------- -----11-SEP-10 09-SEP 1 row selected.

Month Spelling Indicator : MONTH Spells the name of the month, padded to a length of 9 characters.
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'MON-MONTH') 2 FROM DUAL; SYSDATE TO_CHAR(SYSDA --------- ------------11-SEP-10 SEP-SEPTEMBER 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'MONTH,YYYY') 2 FROM EMP ; ENAME HIREDATE TO_CHAR(HIREDA ---------- --------- -------------SMITH 17-DEC-80 DECEMBER ,1980 ALLEN 20-FEB-81 FEBRUARY ,1981 WARD 22-FEB-81 FEBRUARY ,1981 JONES 02-APR-81 APRIL ,1981

120

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

MARTIN 28-SEP-81 SEPTEMBER,1981 BLAKE 01-MAY-81 MAY ,1981 CLARK 09-JUN-81 JUNE ,1981 SCOTT 19-APR-87 APRIL ,1987 KING 17-NOV-81 NOVEMBER ,1981 TURNER 08-SEP-81 SEPTEMBER,1981 ADAMS 23-MAY-87 MAY ,1987 JAMES 03-DEC-81 DECEMBER ,1981 FORD 03-DEC-81 DECEMBER ,1981 MILLER 23-JAN-82 JANUARY ,1982 14 rows selected.

Twelve Hour Clock Mode: HH OR HH12 Returns the hour of the day in twelve hour clock mode.
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'HH'), 2 TO_CHAR(SYSDATE,'HH12,AM') 3 FROM DUAL; SYSDATE TO TO_CH --------- -- ----11-SEP-10 08 08,AM 1 row selected. SQL> SELECT ename,hiredate,TO_CHAR(hiredate,'HH12 : AM') 2 FROM EMP; ENAME HIREDATE TO_CHAR ---------- --------- ------SMITH 17-DEC-80 12 : AM ALLEN 20-FEB-81 12 : AM WARD 22-FEB-81 12 : AM JONES 02-APR-81 12 : AM MARTIN 28-SEP-81 12 : AM BLAKE 01-MAY-81 12 : AM CLARK 09-JUN-81 12 : AM SCOTT 19-APR-87 12 : AM KING 17-NOV-81 12 : AM TURNER 08-SEP-81 12 : AM ADAMS 23-MAY-87 12 : AM JAMES 03-DEC-81 12 : AM FORD 03-DEC-81 12 : AM MILLER 23-JAN-82 12 : AM 14 rows selected.

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') 2 FROM DUAL;

121

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SYSDATE TO --------- -11-SEP-10 08 1 row selected.

Minutes Indicator: MI Returns the minutes from the given date (0 59).
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'MI'), 2 TO_CHAR(SYSDATE,'HH:MI') 3 FROM DUAL; SYSDATE TO TO_CH --------- -- ----11-SEP-10 36 08:36 1 row selected. SQL> SELECT ename,Sal,TO_CHAR(hiredate,'HH:MI') 2 FROM EMP 3 WHERE job='CLERK'; ENAME SAL TO_CH ---------- ---------- ----SMITH 800 12:00 ADAMS 1100 12:00 JAMES 950 12:00 MILLER 1300 12:00 4 rows selected.

Roman Month Indicator: RM Returns the roman numeral month (1 X11).


SQL> ED Wrote file afiedt.buf 1 SELECT SYSDATE,TO_CHAR(SYSDATE,'RM'), 2 TO_CHAR(SYSDATE,'DD-RM-YY') 3* FROM DUAL SQL> / SYSDATE TO_C TO_CHAR(SY --------- ---- ---------11-SEP-10 IX 11-IX -10 1 row selected. SQL> SELECT ename,Sal,TO_CHAR(hiredate,'DD-RM-YY') 2 FROM EMP;

122

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ENAME SAL TO_CHAR(HI ---------- ---------- ---------SMITH 800 17-XII -80 ALLEN 1600 20-II -81 WARD 1250 22-II -81 JONES 2975 02-IV -81 MARTIN 1250 28-IX -81 BLAKE 2850 01-V -81 CLARK 2450 09-VI -81 SCOTT 3000 19-IV -87 KING 5000 17-XI -81 TURNER 1500 08-IX -81 ADAMS 1100 23-V -87 JAMES 950 03-XII -81 FORD 3000 03-XII -81 MILLER 1300 23-I -82 14 rows selected.

Seconds Indicator: SS Returns seconds from the given date (0 59).


SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'SS'), 2 TO_CHAR(SYSDATE,'HH:MI:SS') 3 FROM DUAL; SYSDATE TO TO_CHAR( --------- -- -------11-SEP-10 28 08:42:28 1 row selected. SQL> ED Wrote file afiedt.buf 1 SELECT SYSDATE, 2 TO_CHAR(SYSDATE,'DD-MONTH-YYYY,HH:MI:SS A.M.') 3* FROM DUAL SQL> / SYSDATE TO_CHAR(SYSDATE,'DD-MONTH-YYYY, --------- ------------------------------11-SEP-10 11-SEPTEMBER-2010,08:43:27 A.M. 1 row selected. SQL> Ed Wrote file afiedt.buf 1 SELECT ename,sal,hiredate, 2 TO_CHAR(hiredate,'HH24:MI:SS') 3 FROM EMP 4* WHERE deptno IN(10,30) SQL> /

123

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ENAME SAL HIREDATE TO_CHAR( ---------- ---------- --------- -------ALLEN 1600 20-FEB-81 00:00:00 WARD 1250 22-FEB-81 00:00:00 MARTIN 1250 28-SEP-81 00:00:00 BLAKE 2850 01-MAY-81 00:00:00 CLARK 2450 09-JUN-81 00:00:00 KING 5000 17-NOV-81 00:00:00 TURNER 1500 08-SEP-81 00:00:00 JAMES 950 03-DEC-81 00:00:00 MILLER 1300 23-JAN-82 00:00:00 9 rows selected.

Seconds Past Mid Night: SSSSS Display seconds past midnight (0 86399).
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'SSSSS') 2 FROM DUAL; SYSDATE TO_CH --------- ----11-SEP-10 31612 1 row selected.

Date Format Punctuators: The punctuation marks that can be used in date formats are. -, /, !, ., ;, :, text Date Format Element Suffixes: TH OR SP TH -> Suffixes the ordinal number with ST or ND or RD, or TH. Example: DDTH -> 20TH
SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'DDTH,MONTH,YYYY') 2 FROM DUAL; SYSDATE TO_CHAR(SYSDATE,'DD --------- ------------------11-SEP-10 11TH,SEPTEMBER,2010 1 row selected. SQL> SELECT ename,sal,hiredate, 2 TO_CHAR(hiredate,'DDTH,MONTH,YYYY') 3 FROM EMP; ENAME SAL HIREDATE TO_CHAR(HIREDATE,'D ---------- ---------- --------- ------------------SMITH 800 17-DEC-80 17TH,DECEMBER ,1980 ALLEN 1600 20-FEB-81 20TH,FEBRUARY ,1981

124

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

1250 22-FEB-81 22ND,FEBRUARY ,1981 2975 02-APR-81 02ND,APRIL ,1981 1250 28-SEP-81 28TH,SEPTEMBER,1981 2850 01-MAY-81 01ST,MAY ,1981 2450 09-JUN-81 09TH,JUNE ,1981 3000 19-APR-87 19TH,APRIL ,1987 5000 17-NOV-81 17TH,NOVEMBER ,1981 1500 08-SEP-81 08TH,SEPTEMBER,1981 1100 23-MAY-87 23RD,MAY ,1987 950 03-DEC-81 03RD,DECEMBER ,1981 3000 03-DEC-81 03RD,DECEMBER ,1981 1300 23-JAN-82 23RD,JANUARY ,1982

14 rows selected.

SP -> Spells ordinal Numbers.


Example: DDSP -> TWENTY. SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'DDSP,MONTH,YYYY') 2 FROM DUAL; SYSDATE TO_CHAR(SYSDATE,'DDSP,MONTH --------- --------------------------11-SEP-10 ELEVEN,SEPTEMBER,2010 1 row selected. SQL> SELECT ename,sal,hiredate, 2 TO_CHAR(hiredate,'DDSP,MONTH,YYYY') 3 FROM EMP; ENAME SAL HIREDATE TO_CHAR(HIREDATE,'DDSP,MONT ---------- ---------- --------- --------------------------SMITH 800 17-DEC-80 SEVENTEEN,DECEMBER ,1980 ALLEN 1600 20-FEB-81 TWENTY,FEBRUARY ,1981 WARD 1250 22-FEB-81 TWENTY-TWO,FEBRUARY ,1981 JONES 2975 02-APR-81 TWO,APRIL ,1981 MARTIN 1250 28-SEP-81 TWENTY-EIGHT,SEPTEMBER,1981 BLAKE 2850 01-MAY-81 ONE,MAY ,1981 CLARK 2450 09-JUN-81 NINE,JUNE ,1981 SCOTT 3000 19-APR-87 NINETEEN,APRIL ,1987 KING 5000 17-NOV-81 SEVENTEEN,NOVEMBER ,1981 TURNER 1500 08-SEP-81 EIGHT,SEPTEMBER,1981 ADAMS 1100 23-MAY-87 TWENTY-THREE,MAY ,1987 JAMES 950 03-DEC-81 THREE,DECEMBER ,1981 FORD 3000 03-DEC-81 THREE,DECEMBER ,1981 MILLER 1300 23-JAN-82 TWENTY-THREE,JANUARY ,1982 14 rows selected. SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'DDSPTH,MONTH,YYYY') 2 FROM DUAL; SYSDATE TO_CHAR(SYSDATE,'DDSPTH,MONTH

125

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

--------- ----------------------------11-SEP-10 ELEVENTH,SEPTEMBER,2010 1 row selected. SQL> SELECT ename,sal,hiredate, 2 TO_CHAR(hiredate,'DDSPTH,MONTH,YYYY') 3 FROM EMP; ENAME SAL HIREDATE TO_CHAR(HIREDATE,'DDSPTH,MONT ---------- ---------- --------- ----------------------------SMITH 800 17-DEC-80 SEVENTEENTH,DECEMBER ,1980 ALLEN 1600 20-FEB-81 TWENTIETH,FEBRUARY ,1981 WARD 1250 22-FEB-81 TWENTY-SECOND,FEBRUARY ,1981 JONES 2975 02-APR-81 SECOND,APRIL ,1981 MARTIN 1250 28-SEP-81 TWENTY-EIGHTH,SEPTEMBER,1981 BLAKE 2850 01-MAY-81 FIRST,MAY ,1981 CLARK 2450 09-JUN-81 NINTH,JUNE ,1981 SCOTT 3000 19-APR-87 NINETEENTH,APRIL ,1987 KING 5000 17-NOV-81 SEVENTEENTH,NOVEMBER ,1981 TURNER 1500 08-SEP-81 EIGHTH,SEPTEMBER,1981 ADAMS 1100 23-MAY-87 TWENTY-THIRD,MAY ,1987 JAMES 950 03-DEC-81 THIRD,DECEMBER ,1981 FORD 3000 03-DEC-81 THIRD,DECEMBER ,1981 MILLER 1300 23-JAN-82 TWENTY-THIRD,JANUARY ,1982 14 rows selected. SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,'DDSPTH,MONTH,YYYYSP') 2 FROM DUAL; SYSDATE TO_CHAR(SYSDATE,'DDSPTH,MONTH,YYYYSP') --------- ------------------------------------------------------------------11-SEP-10 ELEVENTH,SEPTEMBER,TWO THOUSAND TEN 1 row selected.

Date Format Elements Restrictions: The suffixes when added to date return values always in English. Date suffixes are valid only on output, hence cannot be used to insert a date into the database. Format Model Modifiers: Fill Mode Indicator: Format Model Modifiers: Fill Mode Indicator: FM It suppresses blank padding in the return value of the to_char function. Format Exact: FX It specifies exact matching for the character argument and date format model.
SQL> ED

126

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Wrote file afiedt.buf 1 SELECT SYSDATE, 2 TO_CHAR(SYSDATE,'DDSPTH,MONTH,YYYYSP'), 3 TO_CHAR(SYSDATE,'FMDDSPTH MONTH YYYYSP') 4* FROM DUAL SQL> / SYSDATE TO_CHAR(SYSDATE,'DDSPTH,MONTH,YYYYSP') --------- ------------------------------------------------------------------TO_CHAR(SYSDATE,'FMDDSPTHMONTHYYYYSP') ------------------------------------------------------------------11-SEP-10 ELEVENTH,SEPTEMBER,TWO THOUSAND TEN ELEVENTH SEPTEMBER TWO THOUSAND TEN 1 row selected.

TO_NUMBER Function Syntax: TO_NUMBER(Char, fmt, nlsparam) It converts 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', 2 TO_NUMBER('$10,000.00','L99,999.99') 3 FROM DUAL; '$10,000.0 TO_NUMBER('$10,000.00','L99,999.99') ---------- -----------------------------------$10,000.00 10000 1 row selected. SQL> SELECT '$1,000.00', 2 TO_NUMBER('$1,000.00','L99,999.99') + 500 3 FROM DUAL; '$1,000.0 TO_NUMBER('$1,000.00','L99,999.99')+500 --------- --------------------------------------$1,000.00 1500 1 row selected.

To Date Function Syntax: TO_DATE(Char, fmt, nlsparam) Converts given char of char or varcahr2 data type to a value of date data type. The fmt is a an optional date format specifying the format of char.
SQL> ED Wrote file afiedt.buf

127

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 SELECT ename,hiredate, 2 ADD_MONTHS(TO_DATE('17-DEC-1980','DD-MON-YY'),3) 3 FROM EMP 4* WHERE hiredate='17-DEC-1980' SQL> / ENAME HIREDATE ADD_MONTH ---------- --------- --------SMITH 17-DEC-80 17-MAR-81 1 row selected. SQL> SELECT ename,hiredate, 2 ADD_MONTHS(TO_DATE('1980-DECEMBER-17', 3 'YYYY-MONTH-DD'),3) 4 FROM EMP 5 WHERE hiredate='17-DEC-1980'; ENAME HIREDATE ADD_MONTH ---------- --------- --------SMITH 17-DEC-80 17-MAR-81 1 row selected. SQL> ED Wrote file afiedt.buf 1 SELECT ename,hiredate, 2 ADD_MONTHS(TO_DATE('1980-DECEMBER-17','YYYY-MONTH-DD'),3) 3 FROM EMP 4 WHERE 5* TO_CHAR(hiredate,'FMYYYY-MONTH-DD')='1980-DECEMBER-17' SQL> / ENAME HIREDATE ADD_MONTH ---------- --------- --------SMITH 17-DEC-80 17-MAR-81 1 row selected. SQL> SELECT '12-AUGUST-2007', 2 TO_DATE('12-AUGUST-2007','DD-MONTH-YYYY')+3 3 FROM DUAL; '12-AUGUST-200 TO_DATE(' -------------- --------12-AUGUST-2007 15-AUG-07 1 row selected.

Let Us Revisit INSERT Statement Once Again 128 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Working With Invalid Numbers


SQL> CREATE TABLE sampins 2 ( 3 samplenum NUMBER(6), 4 sampledate DATE 5 ); Table created. SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 TO_NUMBER('1,23,456','9G99G999'), 5 SYSDATE 6 ); 1 row created. SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 TO_NUMBER('1,23,457-','9G99G999MI'), 5 SYSDATE 6 ); 1 row created.

Working With Invalid Dates


SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 123458, 5 '02-AUG-07' 6 ); 1 row created. SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 123459, 5 SYSDATE 6 ); 1 row created. SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 123460, 5 TO_DATE('02-AUGUST-2007,06:45:36 P.M.', 6 'DD-MONTH-YYYY,HH:MI:SS P.M.')

129

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7 ); 1 row created.

Inserting B.C. Dates Into Tables


SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 123461, 5 '02-AUG-07' 6 ); 1 row created. SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 123462, 5 TO_DATE('02-AUG-2007 B.C.', 6 'DD-MON-YYYY B.C.') 7 ); 1 row created. SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 123463, 5 TO_DATE(988216,'J') 6 ); 1 row created.

Watch These Inserts:


SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 123464, 5 '02-AUG-07' 6 ); 1 row created. SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 123465, 5 '02-AUG-07' 6 ); 1 row created.

130

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 123466, 5 '02-AUG-07' 6 ); 1 row created. SQL> INSERT INTO 2 sampins(samplenum, sampledate) 3 values( 4 123467, 5 '02-AUG-07' 6 ); 1 row created.

RR Date Format Element The RR date format element is similar to the YY date format element. The RR format element provides additional flexibility for storing date values in other centuries. The RR date format element allows to store the date to the previous as well as the next centuries. The RR format element 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 RRRR format element. Chart of Identification Last two digits of the year managed by clock last two digits of the year you supplied 0 to 49 50 to 99

0 To 49 50 To 99

Returns the date in current century Returns the date in the preceding century

Returns the date in the next century Returns the date in current century

Let Us See Some Combinations


SQL> SELECT 2 TO_CHAR( 3 ADD_MONTHS(hiredate,1), 4 'DD-MON-YYYY' 5 ) "next month" 6 FROM EMP 7 WHERE ename='SMITH'; next month -----------

131

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

17-JAN-1981 1 row selected. SQL> SELECT 2 CONCAT( 3 CONCAT(ename,' is a '), 4 job 5 ) Designation 6 FROM EMP 7 WHERE Empno=7900; DESIGNATION ------------------------JAMES is a CLERK 1 row selected. SQL> SELECT 2 TO_CHAR( 3 ADD_MONTHS( 4 LAST_DAY(hiredate),5 5 ),'DD-MON-YYYY' 6 ) "FIVE MONTHS" 7 FROM EMP 8 WHERE ename='MARTIN'; FIVE MONTHS ----------28-FEB-1982 1 row selected. SQL> ED Wrote file afiedt.buf 1 SELECT 2 TRUNC( 3 TO_DATE('27-OCT-92','DD-MON-YY'), 4 'YEAR' 5 ) "New Year" 6* FROM DUAL SQL> / New Year --------01-JAN-92 1 row selected. SQL> SELECT 2 MONTHS_BETWEEN( 3 TO_DATE( 4 '02-02-1995','MM-DD-YYYY'

132

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

5 ), 6 TO_DATE( 7 '01-01-1995','MM-DD-YYYY' 8 ) 9 ) MONTHS 10 FROM DUAL; MONTHS ---------1.03225806 1 row selected. SQL> SELECT NEXT_DAY('15-MAR-98','TUESDAY') "Next Day" 2 FROM DUAL; Next Day --------17-MAR-98 1 row selected. SQL> SELECT Ename, 2 NVL(TO_CHAR(Comm),'Not Applicable') "Commission" 3 FROM EMP 4 WHERE Deptno=30; ENAME Commission ---------- ---------------------------------------ALLEN 300 WARD 500 MARTIN 1400 BLAKE Not Applicable TURNER 0 JAMES Not Applicable 6 rows selected. SQL> SELECT 2 ROUND( 3 TO_DATE('27-OCT-92','DD-MON-YY'),'YEAR' 4 ) "New Year" 5 FROM DUAL; New Year --------01-JAN-93 1 row selected. SQL> SELECT TO_CHAR(hiredate,'MONTH DD,YYYY') 2 FROM EMP 3 WHERE ename='BLAKE';

133

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

TO_CHAR(HIREDATE, ----------------MAY 01,1981 1 row selected. SQL> SELECT ename, 2 TO_CHAR(hiredate,'FMMONTH,DD YYYY') Hiredate 3 FROM EMP 4 WHERE deptno=20; ENAME HIREDATE ---------- ----------------SMITH DECEMBER,17 1980 JONES APRIL,2 1981 SCOTT APRIL,19 1987 ADAMS MAY,23 1987 FORD DECEMBER,3 1981 5 rows selected. SQL> SELECT 2 TO_CHAR( 3 TO_DATE('27-OCT-98','DD-MON-RR'), 4 'YYYY' 5 ) 6 YEAR 7 FROM DUAL; YEAR ---1998 1 row selected. SQL> SELECT 2 TO_CHAR( 3 TO_DATE('27-OCT-17','DD-MON-RR'), 4 'YYYY' 5 ) Year 6 FROM DUAL; YEAR ---2017 1 row selected. Assumption: Queries are issued between year 1950 1999. SQL> SELECT 2 TO_CHAR 3 ( 4 TO_DATE('27-OCT-98','DD-MON-RR'),

134

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

5 'YYYY' 6 ) Year 7 FROM DUAL; YEAR ---1998 1 row selected. SQL> SELECT 2 TO_CHAR 3 ( 4 TO_DATE('27-OCT-17','DD-MON-RR'), 5 'YYYY' 6 ) Year 7 FROM DUAL; YEAR ---2017 1 row selected. Assumption: Queries are issued between year 2000 2049 SQL> SELECT 2 TO_CHAR(SYSDATE,'FMDDTH')||' of '|| 3 TO_CHAR(SYSDATE,'MONTH')||' , '|| 4 TO_CHAR(SYSDATE,'YYYY') Idea 5 FROM DUAL; IDEA -----------------------11TH of SEPTEMBER , 2010 1 row selected. SQL> SELECT 2 TO_CHAR(SYSDATE,'FMDAY')||'''s Special' "MENU" 3 FROM DUAL; MENU ------------------SATURDAY's Special 1 row selected. SQL> SELECT ename,job, 2 NVL(TO_CHAR(mgr),'Supreme Authority') "Managers" 3 FROM EMP 4 ORDER BY Sal DESC; ENAME JOB Managers ---------- --------- ----------------------------------------

135

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

KING PRESIDENT Supreme Authority SCOTT ANALYST 7566 FORD ANALYST 7566 JONES MANAGER 7839 BLAKE MANAGER 7839 CLARK MANAGER 7839 ALLEN SALESMAN 7698 TURNER SALESMAN 7698 MILLER CLERK 7782 WARD SALESMAN 7698 MARTIN SALESMAN 7698 ADAMS CLERK 7788 JAMES CLERK 7698 SMITH CLERK 7902 14 rows selected.

Spelling a Number
SQL> SELECT 2 TO_CHAR( 3 TO_DATE('&GiveNumber','J'), 4 'JSP' 5 ) "Spelled Number" 6 FROM DUAL; Enter value for givenumber: 1005 Old 3: TO_DATE('&GiveNumber','J'), New 3: TO_DATE('1005','J'), Spelled Number ----------------ONE THOUSAND FIVE 1 row selected. SQL> / Enter value for givenumber: 11100 Old 3: TO_DATE('&GiveNumber','J'), New 3: TO_DATE('11100','J'), Spelled Number --------------------------ELEVEN THOUSAND ONE HUNDRED 1 row selected.

Selecting a Date Specific to Its Century


SQL> SELECT 2 TO_CHAR( 3 TO_DATE(hiredate,'DD-MON-RRRR'), 4 'DD-MON-YYY' 5 ) Hiredate 6 FROM EMP;

136

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

HIREDATE ---------17-DEC-980 20-FEB-981 22-FEB-981 02-APR-981 28-SEP-981 01-MAY-981 09-JUN-981 19-APR-987 17-NOV-981 08-SEP-981 23-MAY-987 03-DEC-981 03-DEC-981 23-JAN-982 14 rows selected.

Text Encryption
SQL> SELECT 2 'SATISH KUMAR YELLANKI' OrgName, 3 TRANSLATE( 4 'SATISH KUMAR YELLANKI', 5 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 6 '1234567890!@#$%^&*()-=_+;,.' 7 ) EncryptedName 8 FROM DUAL; ORGNAME ENCRYPTEDNAME --------------------- --------------------SATISH KUMAR YELLANKI (1)9(8 !-#1* ;5@@1$!9 1 row selected.

Text Decryption
SQL> ED Wrote file afiedt.buf 1 SELECT 2 '(1)9(8 !-#1* ;5@@1$!9' EncryptedName, 3 TRANSLATE( 4 '(1)9(8 !-#1* ;5@@1$!9', 5 '1234567890!@#$%^&*()-=_+;,.', 6 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 7 ) DecryptedName 8* FROM DUAL SQL> / ENCRYPTEDNAME DECRYPTEDNAME

137

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

--------------------- --------------------(1)9(8 !-#1* ;5@@1$!9 SATISH KUMAR YELLANKI 1 row selected.

Let Us Leap For Aggregating the Data Aggregate or Group Functions: These functions return a single row based on groups of rows. These functions can appear in select lists and having clauses only. These functions operate on sets of rows to give one result per group. The sets may be the whole table or the table split into groups.

Guidelines to use Group Functions: Distinct makes the function to consider only non duplicate values. All makes the function to consider every value including duplicates. Syntax: GroupFunctionName (distinct / all col ) The data types for arguments may be char, varchar2, number or date. All group functions except count(*) ignore null values. To substitute a value for null value, use the NVL function. When a group function is declared in a select list, no single row columns should be declared. When a group function is declared in a select list, other columns can be declared, but they should be grouped columns, and all the non functional columns should be declared into a group by clause. Average Function Syntax: AVG(distinct / all col) It returns the average value of column. It ignores NULL values.
SQL> SELECT AVG(Sal),AVG(DISTINCT Sal) 2 FROM EMP; AVG(SAL) AVG(DISTINCTSAL) ---------- ---------------2073.21429 2064.58333 1 row selected. SQL> SELECT AVG(comm),AVG(DISTINCT comm) 2 FROM EMP; AVG(COMM) AVG(DISTINCTCOMM) ---------- ----------------550 550

138

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row selected.

Sum Function Syntax: SUM(DISTINCT / ALL col) It returns the sum value of column. It ignores NULL values.
SQL> SELECT SUM(Sal),SUM(DISTINCT Sal) 2 FROM EMP; SUM(SAL) SUM(DISTINCTSAL) ---------- ---------------29025 24775 1 row selected. SQL> SELECT SUM(comm),SUM(DISTINCT comm) 2 FROM EMP; SUM(COMM) SUM(DISTINCTCOMM) ---------- ----------------2200 2200 1 row selected.

Maximum Function Syntax: MAX(DISTINCT / ALL col) It returns the maximum value of column. It ignores NULL values.
SQL> SELECT MAX(Sal),MAX(DISTINCT Sal) 2 FROM EMP; MAX(SAL) MAX(DISTINCTSAL) ---------- ---------------5000 5000 1 row selected. SQL> SELECT MAX(comm),MAX(DISTINCT comm) 2 FROM EMP; MAX(COMM) MAX(DISTINCTCOMM) ---------- ----------------1400 1400 1 row selected.

Minimum Function 139 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Syntax: MIN(DISTINCT / ALL col) It returns the minimum value of the column. It ignores NULL values.
SQL> SELECT MIN(Sal),MIN(DISTINCT Sal) 2 FROM EMP; MIN(SAL) MIN(DISTINCTSAL) ---------- ---------------800 800 1 row selected. SQL> SELECT MIN(comm),MIN(DISTINCT comm) 2 FROM EMP; MIN(COMM) MIN(DISTINCTCOMM) ---------- ----------------0 0 1 row selected.

Standard Deviation Function Syntax: STDDEV(DISTINCT / ALL col) It returns the standard deviation of the column. It ignores NULL values.
SQL> SELECT STDDEV(Sal),STDDEV(DISTINCT Sal) 2 FROM EMP; STDDEV(SAL) STDDEV(DISTINCTSAL) ----------- ------------------1182.50322 1229.95096 1 row selected. SQL> SELECT STDDEV(comm),STDDEV(DISTINCT comm) 2 FROM EMP; STDDEV(COMM) STDDEV(DISTINCTCOMM) ------------ -------------------602.771377 602.771377 1 row selected.

Variance Function Syntax: VARIANCE(DISTINCT / ALL col) It returns the variance of N. It ignores the NULL values. 140 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT VARIANCE(Sal),VARIANCE(DISTINCT Sal) 2 FROM EMP; VARIANCE(SAL) VARIANCE(DISTINCTSAL) ------------- --------------------1398313.87 1512779.36 1 row selected. SQL> SELECT VARIANCE(comm),VARIANCE(DISTINCT comm) 2 FROM EMP; VARIANCE(COMM) VARIANCE(DISTINCTCOMM) -------------- ---------------------363333.333 363333.333 1 row selected.

Count Function Syntax: COUNT(* / DISTINCT / ALL col) It returns the number of rows in the query. If * is used returns all rows, including duplicated and NULLs. It can be used to specify the count of all rows or only distinct values of col.
SQL> SELECT COUNT(*) 2 FROM EMP; COUNT(*) ---------14 1 row selected. SQL> SELECT COUNT(job),COUNT(DISTINCT job) 2 FROM EMP; COUNT(JOB) COUNT(DISTINCTJOB) ---------- -----------------14 5 1 row selected. SQL> SELECT COUNT(Sal),COUNT(comm) 2 FROM EMP; COUNT(SAL) COUNT(COMM)

141

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

---------- ----------14 4 1 row selected. SQL> SELECT COUNT(Empno),COUNT(DISTINCT mgr) 2 FROM EMP; COUNT(EMPNO) COUNT(DISTINCTMGR) ------------ -----------------14 6 1 row selected.

Creating Groups of Data The group by clause is used to decide the rows in a table into groups. Syntax 1: SLEECT ColumnName1, ColumnName2, . FROM TableName Where condition(s) Group by columnName(s) Order by column(s); Syntax 2: Select ColumnName,GRP_fun(column) From TableName Where condition(s) Group by columnName(s) Order by column(s); Guidelines to Use Group By Clause: If the group function is included in a select clause, we should not use individual result columns. The extra non group functional columns should be declared in the group by clause. Using where clause, rows can be pre excluded before dividing them into groups. Column aliases cannot be used in group by clause. By default, rows are sorted by ascending order of the columns included in the group by list. The column applied upon group by clause need not be part of select list.
SQL> SELECT deptno 2 FROM EMP 3 GROUP BY deptno; DEPTNO ---------10 20 30

142

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 rows selected. SQL> SELECT job 2 FROM EMP 3 GROUP BY job; JOB --------ANALYST CLERK MANAGER PRESIDENT SALESMAN 5 rows selected. SQL> SELECT mgr 2 FROM EMP 3 GROUP BY mgr; MGR ---------7566 7698 7782 7788 7839 7902 7 rows selected. SQL> SELECT TO_CHAR(hiredate,'YYYY') YearGroup 2 FROM EMP; YEAR ---1980 1981 1981 1981 1981 1981 1981 1987 1981 1981 1987 1981 1981 1982 14 rows selected.

143

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT TO_CHAR(hiredate,'MONTH') MonthGroup 2 FROM EMP 3 GROUP BY TO_CHAR(hiredate,'MONTH'); MONTHGROU --------APRIL DECEMBER FEBRUARY JANUARY JUNE MAY NOVEMBER SEPTEMBER 8 rows selected. SQL> SELECT TO_CHAR(hiredate,'YYYY') YearGroup 2 FROM EMP 3 GROUP BY TO_CHAR(hiredate,'YYYY'); YEAR ---1980 1981 1982 1987 4 rows selected. SQL> SELECT TO_CHAR(hiredate,'MONTH') MonthGroup 2 FROM EMP 3 WHERE TO_CHAR(hiredate,'MONTH')<> 'SEPTEMBER' 4 GROUP BY TO_CHAR(hiredate,'MONTH'); MONTHGROU --------APRIL DECEMBER FEBRUARY JANUARY JUNE MAY NOVEMBER 7 rows selected.

Creating Group Wise Summaries


SQL> SELECT deptno,AVG(Sal) 2 FROM EMP 3 GROUP BY deptno;

144

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

DEPTNO AVG(SAL) ---------- ---------10 2916.66667 20 2175 30 1566.66667 3 rows selected. SQL> SELECT deptno,AVG(Sal) 2 FROM EMP 3 GROUP BY deptno 4 ORDER BY AVG(Sal); DEPTNO AVG(SAL) ---------- ---------30 1566.66667 20 2175 10 2916.66667 3 rows selected. SQL> SELECT deptno,MIN(Sal),MAX(Sal) 2 FROM EMP 3 GROUP BY deptno; DEPTNO MIN(SAL) MAX(SAL) ---------- ---------- ---------10 1300 5000 20 800 3000 30 950 2850 3 rows selected. SQL> SELECT deptno,job,SUM(Sal) 2 FROM EMP 3 GROUP BY deptno, job; DEPTNO JOB SUM(SAL) ---------- --------- ---------10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 9 rows selected.

NOTE: The above specification falls under the principle of groups within groups.
SQL> SELECT deptno,MIN(Sal),MAX(Sal)

145

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 FROM EMP 3 WHERE job='CLERK' 4 GROUP BY deptno; DEPTNO MIN(SAL) MAX(SAL) ---------- ---------- ---------10 1300 1300 20 800 1100 30 950 950 3 rows selected. SQL> SELECT deptno,SUM(Sal),AVG(Sal) 2 FROM EMP 3 WHERE job='CLERK' 4 GROUP BY deptno; DEPTNO SUM(SAL) AVG(SAL) ---------- ---------- ---------10 1300 1300 20 1900 950 30 950 950 3 rows selected.

Excluding Groups of Results Having Clause It is used to specify which groups are to be displayed The clause is used to filter data that is associated with group functions. Syntax: Select column, group_function From table [ Where condition(s)] [ Group by group_by_expr] [Having group_by_condition(s)] [Order by column_name / ails]; Steps Performs By Having Clause: First the rows are grouped. Second the group function is applied to the identified groups. Third the groups that match the criteria in the having clause are displayed. The having clause can precede group by clause, but it is more logical to declare it after group by clause. 146 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Group by clause can be used, without a group function in the select list. If rows 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 does not guarantee the existence of having clause, but the existence of having clause demands the existence of group by clause.

SQL> SELECT deptno,AVG(Sal) 2 FROM EMP 3 GROUP BY deptno 4 HAVING MAX(Sal)>2900; DEPTNO AVG(SAL) ---------- ---------10 2916.66667 20 2175 2 rows selected. SQL> SELECT job, SUM(Sal) Payroll 2 FROM EMP 3 WHERE job NOT LIKE 'SALES%' 4 GROUP BY job 5 HAVING SUM(Sal)>5000 6 ORDER BY SUM(Sal); JOB PAYROLL --------- ---------ANALYST 6000 MANAGER 8275 2 rows selected. SQL> ED Wrote file afiedt.buf 1 SELECT deptno,MIN(Sal),MAX(Sal) 2 FROM EMP 3 WHERE job='CLERK' 4 GROUP BY deptno 5* HAVING MIN(Sal)<1000 SQL> / DEPTNO MIN(SAL) MAX(SAL) ---------- ---------- ---------20 800 1100 30 950 950 2 rows selected. SQL> SELECT deptno,SUM(Sal) 2 FROM EMP 3 GROUP BY deptno 4 HAVING COUNT(deptno)>3;

147

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

DEPTNO SUM(SAL) ---------- ---------20 10875 30 9400 2 rows selected. SQL> SELECT deptno,AVG(Sal),MAX(Sal),MIN(Sal) 2 FROM EMP 3 GROUP BY deptno 4 HAVING COUNT(*)>3; DEPTNO AVG(SAL) MAX(SAL) MIN(SAL) ---------- ---------- ---------- ---------20 2175 3000 800 30 1566.66667 2850 950 2 rows selected. SQL> SELECT deptno,AVG(Sal),SUM(Sal) 2 FROM EMP 3 GROUP BY deptno 4 HAVING AVG(Sal)>2500; DEPTNO AVG(SAL) SUM(SAL) ---------- ---------- ---------10 2916.66667 8750 1 row selected. SQL> SELECT deptno,job,SUM(Sal),AVG(Sal) 2 FROM EMP 3 GROUP BY deptno, job 4 HAVING AVG(Sal)>2500; DEPTNO JOB SUM(SAL) AVG(SAL) ---------- --------- ---------- ---------10 PRESIDENT 5000 5000 20 ANALYST 6000 3000 20 MANAGER 2975 2975 30 MANAGER 2850 2850 4 rows selected.

Nesting of Group Functions: Group function can be nested to a depth of two levels.
SQL> Ed Wrote file afiedt.buf 1 SELECT MAX(AVG(Sal)) 2 FROM EMP 3* GROUP BY deptno

148

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> / MAX(AVG(SAL)) ------------2916.66667 1 row selected. SQL> SELECT MAX(SUM(Sal)),MIN(SUM(Sal)) 2 FROM EMP 3 GROUP BY deptno; MAX(SUM(SAL)) MIN(SUM(SAL)) ------------- ------------10875 8750 1 row selected. SQL> SELECT MAX(SUM(SAL)),MIN(AVG(Sal)) 2 FROM EMP 3 GROUP BY job; MAX(SUM(SAL)) MIN(AVG(SAL)) ------------- ------------8275 1037.5 1 row selected.

Miscellaneous Functions Greatest Function Syntax: GREATEST(Expr1, Expr2, ..) Returns the greatest of the list of expr. All exprs after the first are implicitly converted to the data type of the first expr, before the comparison. Oracle compares the exprs using non padded comparison semantics. Character comparison is based on the value of the character in the data base character list.
SQL> SELECT GREATEST('HARRY','HARRIOT') 2 FROM DUAL; GREAT ----HARRY

149

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row selected. SQL> SELECT GREATEST(1000,2000,200) 2 FROM DUAL; GREATEST(1000,2000,200) ----------------------2000 1 row selected. SQL> ED Wrote file afiedt.buf 1 SELECT GREATEST('10-JUL-05','20-JUL-05') 2* FROM DUAL SQL> / GREATEST( --------20-JUL-05 1 row selected.

Least Function Syntax: LEAST(Expr1, Expr2, .) It returns the least of the list of exprs. All exprs after the first are implicitly converted to the data type of the first expr before the comparison.
SQL> SELECT LEAST('HARRY','HARRIOT') 2 FROM DUAL; LEAST(' ------HARRIOT 1 row selected. SQL> SELECT LEAST(1000,2000,200) 2 FROM DUAL; LEAST(1000,2000,200) -------------------200 1 row selected. SQL> SELECT LEAST('10-JUL-05','20-JUL-05') 2 FROM DUAL; LEAST('10

150

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

--------10-JUL-05 1 row selected.

User Function Syntax: USER It returns the current oracle users name within the varchar2 data type. The function cannot be used in condition of the check constraint.
SQL> SELECT USER 2 FROM DUAL; USER ----------------------SCOTT 1 row selected.

UID Function Syntax: UID It returns an integer that uniquely identifies the current user.
SQL> SELECT UID 2 FROM DUAL; UID ---------57 1 row selected. SQL> SELECT USER,UID 2 FROM DUAL; USER UID ------------------------------ ---------SCOTT 57 1 row selected.

USERENV Function Syntax: USERENV(Option) Returns information of varchar2 data type above the current session. The Values in Options are ISDBA -> Returns true if DBA role is enabled. 151 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

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 -> Returns the available auditing entry identifier. LANG -> Returns the ISD abbreviation for the language name. INSTANCE -> Returns the instance identification number of the current instance. CLIENT_INFO -> Returns up to 64 bytes of user session information.

SQL> SELECT USERENV('ISDBA') 2 FROM DUAL; USEREN -----FALSE 1 row selected. SQL> SELECT USERENV('LANGUAGE') 2 FROM DUAL; USERENV('LANGUAGE') ---------------------------------------------------AMERICAN_AMERICA.WE8MSWIN1252 1 row selected. SQL> SELECT USERENV('TERMINAL') 2 FROM DUAL; USERENV('TERMINA ---------------DEVALAPE-9A76D2 1 row selected. SQL> SELECT USERENV('SESSIONID') 2 FROM DUAL; USERENV('SESSIONID') -------------------4216 1 row selected. SQL> SELECT USERENV('LANG') 2 FROM DUAL; USERENV('LANG') ---------------------------------------------------US 1 row selected.

VSIZE Function 152 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Syntax: VSIZE(Expr) It returns the number of bytes in the internal representation of Expr. If expr is NULL, function returns NULL.
SQL> SELECT ename,VSIZE(Ename) 2 FROM EMP; ENAME VSIZE(ENAME) ---------- -----------SMITH 5 ALLEN 5 WARD 4 JONES 5 MARTIN 6 BLAKE 5 CLARK 5 SCOTT 5 KING 4 TURNER 6 ADAMS 5 JAMES 5 FORD 4 MILLER 6 14 rows selected. SQL> SELECT ename,sal,VSIZE(Sal) 2 FROM EMP; ENAME SAL VSIZE(SAL) ---------- ---------- ---------SMITH 800 2 ALLEN 1600 2 WARD 1250 3 JONES 2975 3 MARTIN 1250 3 BLAKE 2850 3 CLARK 2450 3 SCOTT 3000 2 KING 5000 2 TURNER 1500 2 ADAMS 1100 2 JAMES 950 3 FORD 3000 2 MILLER 1300 2 14 rows selected. SQL> SELECT ename,hiredate,VSIZE(Hiredate) 2 FROM EMP; ENAME HIREDATE VSIZE(HIREDATE)

153

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

---------- --------- --------------SMITH 17-DEC-80 ALLEN 20-FEB-81 WARD 22-FEB-81 JONES 02-APR-81 MARTIN 28-SEP-81 BLAKE 01-MAY-81 CLARK 09-JUN-81 SCOTT 19-APR-87 KING 17-NOV-81 TURNER 08-SEP-81 ADAMS 23-MAY-87 JAMES 03-DEC-81 FORD 03-DEC-81 MILLER 23-JAN-82 14 rows selected.

7 7 7 7 7 7 7 7 7 7 7 7 7 7

Soundex Function Syntax: SOUNDEX(CHAR) It returns a character string containing the phonetic representation of char. It allows comparison of words that are spelled differently, but sound alike in English.
SQL> SELECT ename 2 FROM EMP 3 WHERE SOUNDEX(ename)=SOUNDEX('SMYTHE'); ENAME ---------SMITH 1 row selected. SQL> SELECT ename,job 2 FROM EMP 3 WHERE SOUNDEX(job)=SOUNDEX('CLRK'); ENAME JOB ---------- --------SMITH CLERK ADAMS CLERK JAMES CLERK MILLER CLERK 4 rows selected. SQL> SELECT ename,job 2 FROM EMP 3 WHERE SOUNDEX(job)=SOUNDEX('manger'); ENAME JOB ---------- ---------

154

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

JONES BLAKE CLARK

MANAGER MANAGER MANAGER

3 rows selected.

155

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Let Us Increase the Integrity and Quality of Our Database

Data Integrity in Data Bases Data Integrity It is a store in which all the data values stored in the data base are correct. Enforcing data integrity ensures the quality of the data in the data base. Categories of Data Integrity Entity integrity. Domain integrity. Referential integrity. 156 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

User defined integrity.

Entity Integrity It defines a row as a unique entity for a particular table. Entity integrity enforces the integrity of the identifier columns, or the primary key of a table. Illustration: 1 Student Name Sampth Sampth Srinivas Srinivas Sampth Srinivas Illustration: 2 Student Name Sampth Sampth Srinivas Srinivas Sampth Srinivas Date of Birth 02-jan-76 02-jan-76 02-jan-76 02-jan-76 10-dec-80 02-jan-76 Date of Admission 15-jun-00 15-jun-00 15-jun-00 25-aug-02 25-aug-02 25-aug-02 Course Name MCA MBA MBA MBA MBA M.Sc Course Fee 25000.00 25000.00 25000.00 25000.00 25000.00 15000.00 Email ID sampath@gmail.com sampath@yahoo.com srinivas@gmail.com srinivas@yahoo.com sampath@rediff.com srinival@rediff.com Date of Birth 02-jan-76 02-jan-76 02-jan-76 02-jan-76 10-dec-80 02-jan-76 Date of Admission 15-jun-00 15-jun-00 15-jan-00 25-aug-02 25-aug-02 25-aug-02 Course Name MCA MBA MBA MBA MBA M.Sc Course Fee 25000.00 25000.00 25000.00 25000.00 25000.00 15000.00

Illustration: 3 Student ID 1000 1001 1002 1003 Student Name Sampth Sampth Srinivas Srinivas Date of Birth 02-jan-76 02-jan-76 02-jan-76 02-jan-76 Date of Admission 15-jun-00 15-jun-00 15-jun-00 25-aug-02 Course Name MCA MBA MBA MBA Course Fee 25000.00 25000.00 25000.00 25000.00 Email ID sampath@gmail.com sampath@yahoo.com srinivas@gmail.com srinivas@yahoo.com

157

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1004 1005

Sampth Srinivas

10-dec-80 02-jan-76

25-aug-02 25-aug-02

MBA M.Sc

25000.00 15000.00

sampath@rediff.com srinival@rediff.com

Domain Integrity Domain integrity validates the entries for a given column. It can enforced through. Restricting type ( date types ) By format ( check constraint ) By range of possible values using Foreign key constraint. Check constraint. Default key word. Not null constraint. Domain integrities major fact of concentration in on the data that is being collected in that column. Illustration: 4 Student ID 1000 1001 1002 1003 1004 1005 Student Name Sampth SAMPATH Srinivas SRINIVAS Sampth Srinivas Date of Birth 02-jan-76 02-jan-76 02-jan-76 02-jan-76 Date of Admission 15-jun-00 15-jun-00 15-jun-00 04-aug-07 25-aug-02 Course Name MCA MBA MBA MBA MBA M.Sc Course Fee 25000.00 25000.00 25000.00 25000.00 25000.00 15000.00 Email ID sampath@gmail.com srinivas@gmail.com srinivas@yahoo.com srinival@rediff.com

Referential Integrity It preserves the defined relationship between tables when records are entered or deleted. It ensures that key values are consistent across tables. When referential integrity is enforced, it prevents from.. Adding records to 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.

Illustration: 5 Course ID C001 C002 C003 158 Course Name MBA MCA M.Sc Course Fees 25000 25000 15000

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Students Information Student ID 1000 1001 1002 1003 1004 1005 Student Name Sampth SAMPATH Srinivas SRINIVAS Sampth Srinivas Date of Birth 02-jan-76 02-jan-76 02-jan-76 02-jan-76 Date of Admission 15-jun-00 15-jun-00 15-jun-00 04-aug-07 25-aug-02 Course Name MCA MBA MBA MBA MBA M.Sc Course ID C002 C001 C001 C001 C002 C003 Email ID sampath@gmail.com srinivas@gmail.com srinivas@yahoo.com srinival@rediff.com

User Defined Integrity It allow to define specific business rules that Do Not Fall into any one of the other integrity categories. These are business rules which can be handled at run time, usually designed using database triggers in pl/sql. These are rules generally specific to the organizational business process. Can be any situation that looks abnormal to the current systems process. Constraints in Oracle Constraints in data bases are used to define an integrity constraint, as a rule that restricts the values in a database. As per oracle there are six types of constraints Not null constraint. Unique constraint. Primary key constraint. Foreign key constraint. Check constraint. Ref constraint. Declaration Style Column level (or) in line style. Table level (or) out of line style. Column level: They are declared as part of the definition of an individual column or attribute. Usually applied when the constraint is specific to that column only. Table level: They are declared as part of the table definition. Definitely applied when the constraint is applied on combination of columns together. 159 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Note: Not null constraint is the only constraint which should be declared as inline only. Every constraint is managed by oracle with a constraint name in the meta data. Hence when we declare a constraint if we do not provide a constraint name oracle associates the constraint with name. Within a single user no two constraints can have the same name. Rather than depending on the oracle supplied constraint name, it is better to define our own name for all constraints. When constraints are named we should use constraint clause. The constraint clause can appear in Create and alter table statement. Create and alter view statement. Oracle does not support constraints on columns or attributes whose data type is User_defined objects. Nested tables and varray. Ref and lob. Exceptions Not null constraint is supported for an attribute whose data type is user_defined object, varray, ref, and lob. Not null, foreign key, and ref constraints are supported on a column of type ref. Not null constraint: A not null constraint prohibits a column from containing null values. Not null should be defined only at column level. The default constraint if not specified is NULL constraint. To satisfy the rule, every row in the table must contain a value for the column. Restrictions: Null or not null cannot be specified as view constraints. Null or not null cannot be specified for an attribute of an object. Syntax SQL> create table<table_name> ( Column_name1<data type>(width) not null, Column_name2<data type>(width) Constraint consName not null, Column_nameN<data type>(width) ); Illustration
SQL> CREATE TABLE students 2 ( 3 studno NUMBER(6) 4 CONSTRAINT StudnoNN NOT NULL,

160

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

5 studName VARCHAR2(25) 6 CONSTRAINT studNameNN NOT NULL, 7 courseName VARCHAR2(25) 8 CONSTRAINT courseNameNN NOT NULL, 9 JoinDate DATE NOT NULL 10 ); Table created.

UNIQUE Constraint The unique constraint designates a column as a unique key. A composite unique key designates a combination of columns as the unique key. A composite unique key is always declared at the table level. To satisfy a unique constraint, no two rows in the table can have the same value for the unique key. Unique key made up a single column can contain null values. Oracle creates an index implicitly on the unique key column. Restrictions: A table or view can have only one unique key column. Unique key cannot be implemented on columns having Lob, long, long row, varray, nested table, object, bfile, ref, timestamp with time zone. A composite unique key cannot have more than 32 columns. Same column or combination of column cannot be designated as both primary key and unique key. We cannot specify a unique key when creating a sub table or sub view in an inheritance hierarchy. The unique key can be specified only for the top level (root) table or view. Syntax SQL>create table<table_name> ( Column_name1 <data type> (width) unique, Column_name2 <data type>(width) Constraint consName unique, Column_NameN <data type>(width) ); Illustration: 1 Column level syntax
SQL> CREATE TABLE promotions 2 ( 3 promo_id NUMBER(6) 4 CONSTRAINT promoIDUNQ UNIQUE, 5 promoName VARCHAR2(20), 6 PromoCategory VARCHAR2(15), 7 PromoCost NUMBER(10,2),

161

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

8 PromoBegDate DATE, 9 PromoEndDate DATE 10 ); Table created.

Illustration: 2 Table Level Syntax


SQL> Ed Wrote file afiedt.buf 1 CREATE TABLE promotion 2 ( 3 promo_id NUMBER(6), 4 promoName VARCHAR2(20), 5 PromoCategory VARCHAR2(15), 6 PromoCost NUMBER(10,2), 7 PromoBegDate DATE, 8 PromoEndDate DATE, 9 CONSTRAINT PromIDUNQ UNIQUE(Promo_ID) 10* ) SQL> / Table created.

Illustration: 3 Composite UNIQUE Constraint Syntax


SQL> Ed Wrote file afiedt.buf 1 CREATE TABLE warehouse 2 ( 3 warehouseid NUMBER(6), 4 warehouseName VARCHAR2(30), 5 area NUMBER(4), 6 docktype VARCHAR2(50), 7 wateraccess VARCHAR2(10), 8 railaccess VARCHAR2(10), 9 parking VARCHAR2(10), 10 vclearance NUMBER(4), 11 CONSTRAINT WareHouseUNQ 12 UNIQUE(WarehouseID,warehouseName) 13* ) SQL> / Table created.

Illustration: 4 162 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> ED Wrote file afiedt.buf 1 CREATE TABLE students 2 ( 3 studid NUMBER(6) 4 CONSTRAINT StudidUNQ UNIQUE, 5 fname VARCHAR2(30), 6 dob DATE, 7 doj DATE, 8 EmailID VARCHAR2(50) 9 CONSTRAINT EmailIDUNQ UNIQUE 10* ) SQL> / Table created.

PRIMARY KEY Constraint A primary key constraint designates a column as the primary key of a table or view. A composite primary key designates a combination of columns as the primary key. When the constraint is declared at column level only primary key keyword is enough. A composite primary key is always defined at table level only. A primary key constraint combines a not null and unique constraint in one declaration. Restrictions: A table or view can have only one primary key. Primary key cannot be implemented on columns having Lob, long, long raw, varray, nested table, object, bfile, ref, timestamp with time zone The size of a primary key cannot exceed approximately one database block. A composite primary key cannot have exceed more than 32 columns. The same column or combination of columns cannot be designated both as primary key and unique key. Primary key cannot be specified when creating a sub table or sub view in an inheritance hierarchy. The primary key can be specified only for the top level (root) table or view. Syntax SQL> create table <table_name> ( Column_name1 <data type> (width) Constraint colNamePK primary key, Column_name2 <data type> (width), Column_nameN <data type> (width) ); Illustration: 1 Column Level Syntax: 163 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> CREATE TABLE locations 2 ( 3 locationId NUMBER(4) 4 CONSTRAINT locidpk PRIMARY KEY, 5 staddress VARCHAR2(40) NOT NULL, 6 postalcode VARCHAR2(6) 7 CONSTRAINT PCNN NOT NULL, 8 city VARCHAR2(30) 9 CONSTRAINT citynn NOT NULL 10 ); Table created.

Illustration: 2 Table Level Syntax


SQL> Ed Wrote file afiedt.buf 1 CREATE TABLE location 2 ( 3 locationId NUMBER(4), 4 staddress VARCHAR2(40) NOT NULL, 5 postalcode VARCHAR2(6) 6 CONSTRAINT PNN NOT NULL, 7 city VARCHAR2(30) 8 CONSTRAINT citnn NOT NULL, 9 CONSTRAINT locdpk PRIMARY KEY(locationId) 10* ) SQL> / Table created.

Analyze the Following Data for Primary Key saleID S001 S001 S002 S002 S002 S002 S003 S003 S003 S004 S005 S006 Illustration:2 164 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By custID C001 C001 C002 C002 C002 C002 C001 C001 C001 C003 C001 C002 prodID P001 P002 P003 P004 P010 P003 P005 P002 P015 P100 P002 P004 Qty 250.00 125.00 50.00 75.00 225.00 125.00 200.00 25.00 354.00 245.00 125.00 75.00 SaleDate 01-AUG-07 01-AUG-07 01-AUG-07 01-AUG-07 01-AUG-07 01-AUG-07 01-AUG-07 01-AUG-07 01-AUG-07 02-AUG-07 03-AUG-07 03-AUG-07 SaleDesc Cash Cash Cash Credit Credit Cash Credit Cash Credit Cash Cash Cash

[ K . Sekhar ]

SQL> CREATE TABLE salesinfo 2 ( 3 saleid NUMBER(6), 4 custid NUMBER(6), 5 prodid NUMBER(6), 6 quantity NUMBER(6) NOT NULL, 7 saledate DATE NOT NULL, 8 saledesc LONG NOT NULL, 9 CONSTRAINT prodcustidpk 10 PRIMARY KEY(saleid,prodid,custid) 11 ); Table created.

Primary key constraint with composite key constraint style. FOREIGN KEY Constraint It is also called as referential integrity constraint. It designates a column as foreign key and establishes a relation between the foreign key and a specified primary or unique key. A composite foreign key designates a combination of columns as the foreign key. The table or view containing the foreign key is called the child object. The table or view containing the referenced key is called the parent object. The foreign key and the referenced key can be in the same table or view. The corresponding column or columns of the foreign key and the referenced key must match in order and data type. A foreign key constraint can be defined on a single key column either inline or out of line. A composite foreign kept on attributes should e declared at table level or out of line style. We can designate the same column or combination of columns as both a foreign key and a primary or unique key. A composite foreign key constraint, must refer to a composite unique key or a composite primary key in the parent table or view. Restrictions: The foreign key columns cannot be applied on.. Lob, long, long raw, varray, nested table, object, bfile, ref, timestamp with time zone The referenced unique / primary key constraint or the parent table or view must already be detected. A composite foreign key cannot have more than 32 columns. The child and parent tables must be on the same database. To enable referential integrity across nodes of a distributed database triggers are used. References Clause: The references clause should be used when the foreign key constraint is inline. When the constraint is out of line, we must specify the foreign key, key word. ON Delete Clause: The on delete clause determines how oracle automatically maintains referential integrity if the referenced primary or unique key value is removed from master values. 165 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Cascade option can be specified if we want oracle to remove dependent foreign key values. Specify set null If we want oracle to convert dependent foreign key values to NULL. On delete clause cannot be specified for a view constraint. Declared on foreign key column only.

Things to Note Before We Apply Relations Relation Model Symbols

Entity or Table

Column or Attribute Relation or Association

Associative Entity or Table

Connection Line Types of Relations: Unary Relation. Binary Relation. Ternary Relation. N Ary Relation Relation Model Representation: Unary Relation:

or

----------

166

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Binary Relation:

Ternary Relation:

Relation Cardinality: One to one . -> 1..1 One to many. -> 1.* or 1:M Many to many -> *.* or M:N or M.N Relation State: Mandatory state. Optional state. Relation State With Cardinality:

One Mandatory Many

One Optional 167 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Many

Types of Tables To Be Identified in Design Process 1. Pure Masters: These are tables which contain only primary keys, and all the remaining columns are non keys. 2. Master Details: These are tables containing their own primary key and are also related to themselves or other tables with foreign keys. 3. Pure Details: These are tables which contain only foreign keys, related to other table or tables primary key. Steps Followed for Creating Foreign Key Constraint are as Follows: Setp1: create primary masters / pure masters
SQL> CREATE TABLE dept 2 ( 3 deptno NUMBER(2) 4 CONSTRAINT Deptno_PK PRIMARY KEY, 5 Dname VARCHAR2(20) 6 CONSTRAINT Dname_NN NOT NULL, 7 Location VARCHAR2(20) 8 CONSTRAINT Loc_NN NOT NULL 9 ); Table created.

Step2: create detailed / child Table These are tables which can contain primary key of their own as well as foreign keys referring to other primary masters or to themselves. These tables are also called as dependent tables or referential tables.
SQL> ED Wrote file afiedt.buf 1 CREATE TABLE Employees 2 ( 3 EMPloyeeID NUMBER(6) 4 CONSTRAINT EMP_id_pk PRIMARY KEY, 5 Ename VARCHAR2(30) 6 CONSTRAINT ename_NN NOT NULL, 7 designation VARCHAR2(30) 8 CONSTRAINT desig_NN NOT NULL, 9 managerId NUMBER(6) 10 CONSTRAINT Mgr_id_fk_self REFERENCES 11 Employees(EMPloyeeid) ON DELETE SET NULL,

168

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

12 hiredate DATE 13 CONSTRAINT hiredate_NN NOT NULL, 14 commission NUMBER(7,2), 15 deptid NUMBER(2) 16 CONSTRAINT deptid_FK 17 REFERENCES DEPT(Deptno) ON DELETE CASCADE 18* ) SQL> / Table created.

Working With Composite Keys Step 1: create pure masters


SQL> CREATE TABLE samplemaster1 2 ( 3 sampleid1 NUMBER(4) 4 CONSTRAINT samp_id1_PK PRIMARY KEY, 5 sampname1 VARCHAR2(20) 6 CONSTRAINT sampname1_NN NOT NULL, 7 sampdate1 DATE 8 CONSTRAINT Sampdate1_NN NOT NULL 9 ); Table created. SQL> ED Wrote file afiedt.buf 1 CREATE TABLE samplemaster2 2 ( 3 sampleid2 NUMBER(4) 4 CONSTRAINT samp_id2_PK PRIMARY KEY, 5 sampname2 VARCHAR2(20) 6 CONSTRAINT sampname2_NN NOT NULL, 7 sampdate2 DATE 8 CONSTRAINT Sampdate2_NN NOT NULL 9* ) SQL> / Table created.

Step 2: create the pure details


SQL> Ed Wrote file afiedt.buf 1 CREATE TABLE sampref

169

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 ( 3 sampidref1 NUMBER(4) 4 CONSTRAINT sampidref1_FK 5 REFERENCES samplemaster1(sampleid1), 6 sampidref2 NUMBER(4) 7 CONSTRAINT sampidref2_FK 8 REFERENCES samplemaster2(sampleid2), 9 sampnameref VARCHAR2(20), 10 Sampdateref DATE, 11 CONSTRAINT sampref_comm_PK 12 PRIMARY KEY(sampidref1,sampidref2) 13* ) SQL> / Table created.

CHECK Constraint It defines a condition that each row must satisfy. To satisfy the constraint, each row in the table must make the condition either true or unknown. Oracle does not verify the check conditions are mutually exclusive. Restrictions The condition of a check constraint can refer to any column in the same table, but it cannot refer to columns of other tables. The constructs that cannot be included are. Queries to refer to values in other rows Calls to functions sysdate, uid, user, userenv. The pseudo columns currval, nextval, level or rownum. Date constant that are not fully specified. A single column can have multiple check constraints that can reference the column in the definition. There is no limit to the number of check constraints that can be defined on a column. The check constraints can be defined at the column level or table level. Default Option The default option is given to maintain a default value in a column. The option 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. Example
SQL> CREATE TABLE dept 2 ( 3 deptno NUMBER(2) 4 CONSTRAINT CHEK_Deptno 5 CHECK(Deptno BETWEEN 10 AND 90),

170

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

6 dname VARCHAR2(15) CONSTRAINT CHE_dname_UP 7 CHECK(dname=UPPER(dname)) DISABLE, 8 loc VARCHAR2(15) 9 CONSTRAINT CHK_loc CHECK(loc IN( 10 'DALLAS', 11 'BOSTON', 12 'NEW YORK', 13 'CHICAGO' 14 ) 15 ) 16 ); Table created. SQL> Ed Wrote file afiedt.buf 1 CREATE TABLE EMP 2 ( 3 Empno NUMBER(4) 4 CONSTRAINT pr_EMPno PRIMARY KEY, 5 Ename VARCHAR2(25) NOT NULL 6 CONSTRAINT chk_ename 7 CHECK(ename=UPPER(ename)), 8 job VARCHAR2(30) 9 CONSTRAINT job_NN NOT NULL, 10 CONSTRAINT chk_job 11 CHECK(job=UPPER(job)), 12 mgr NUMBER(4), 13 hiredate DATE 14 DEFAULT SYSDATE, 15 Sal NUMBER(7,2) 16 CONSTRAINT sal_NN NOT NULL, 17 CONSTRAINT chk_sal 18 CHECK(Sal BETWEEN 2000 AND 100000), 19 comm NUMBER(7,2), 20 deptno NUMBER(2), 21 CONSTRAINT tot_sal_chk CHECK(sal+comm<=100000) 22* ) SQL> / Table created.

Constraints Maintenance Adding Constraints to Table A constraint can be added to a table at any time after the table was created by using alter table statement, using add clause. Syntax SQL> ALTER TABLE <TableName> ADD [ CONSTRAINT <ConstraintName> ] 171 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

CONS_TYPE ( Column_Name); The constraint name in the syntax is optional, but recommended.

Guidelines We can add, drop, enable or disable a constraint, but cannot modify the physical structure of the table. A not null can be added to existing column by using the modify clause of the alter table statement. Not null can be defined only when the table contains no rows. Example
SQL> ALTER TABLE EMP 2 ADD CONSTRAINT EMP_mgr_FK 3 FOREIGN KEY(mgr) REFERENCES EMP(Empno); Table altered.

Dropping Constraints To drop a constraint identify the constraint name from the User_constraints 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 constraints also to be dropped. When a constraint is dropped, the constraint is no longer enforced and is no longer available in the data dictionary. Syntax SQL> ALTER TABLE<Table_Name> DROP PRIMARY KEY / UNIQUE ( Column) / CONSTRAINT ConstraintName [ CASCADE ]; Example
SQL> ALTER TABLE dept 2 DROP PRIMARY KEY CASCADE; ALTER TABLE dept * ERROR at line 1: ORA-02441: Cannot drop nonexistent primary key SQL> ALTER TABLE EMP 2 DROP CONSTRAINT EMP_mgr_FK; Table altered.

Enabling Constraints The constraint can be enabled without dropping it or re-creating it. 172 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

The alter table statement with the enable clause is used for the purpose.

Syntax SQL> ALTER TABLE <Table_Name> ENABLE CONSTRAINT <ConstraintName>; Guidelines Enabling a constraint applies to all the data in the table at a time. When an unique or primary key constraint is enabled, the unique or primary key index is automatically created. The enable clause can be used both in create table as well as alter table statements. Examples
SQL> ALTER TABLE EMP 2 ENABLE 3 CONSTRAINT EMP_EMPno_FK; ALTER TABLE EMP * ERROR at line 1: ORA-02430: cannot enable constraint (EMP_EMPNO_FK) - no such constraint

Viewing Constraints To view all constraints on a table query upon the data dictionary USER_CONSTRAINTS. The codes that are revealed are. C -> CHECK P -> PRIMARY KEY R -> REFERENTIAL INTEGRITY U -> UNIQUE KEY Example
SQL> ED Wrote file afiedt.buf 1 SELECT 2 CONSTRAINT_NAME, 3 CONSTRAINT_TYPE, 4 SEARCH_CONDITION 5 FROM USER_CONSTRAINTS 6* WHERE TABLE_NAME='EMP' SQL> / CONSTRAINT_NAME C SEARCH_CONDITION ------------------------------ - ---------------------------------SYS_C005486 C "ENAME" IS NOT NULL JOB_NN C "JOB" IS NOT NULL SAL_NN C "SAL" IS NOT NULL CHK_ENAME C ename=UPPER(ename) CHK_JOB C job=UPPER(job) CHK_SAL C Sal BETWEEN 2000 AND 100000

173

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

TOT_SAL_CHK PR_EMPNO 8 rows selected.

C sal+comm<=100000 P

Viewing the Columns Associated With Constraints The name of the columns that are involved in constraints can be known by querying the user_cons_columns data dictionary view. Example
SQL> SELECT 2 CONSTRAINT_NAME, 3 COLUMN_NAME 4 FROM USER_CONS_COLUMNS 5 WHERE TABLE_NAME='EMP'; CONSTRAINT_NAME -----------------------------COLUMN_NAME -------------------------------------------------PR_EMPNO EMPNO TOT_SAL_CHK COMM TOT_SAL_CHK SAL CHK_SAL SAL CHK_JOB JOB CHK_ENAME ENAME SAL_NN SAL JOB_NN JOB SYS_C005486 ENAME 9 rows selected.

174

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

175

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Let Us Make Ourselves More Stronger Using Multi Table Queries

JOINS A join is a query that combines rows from two or more tables, views, or materialized views. A join is performed whenever multiple tables appear in the queries from clause. The queries select list can select any columns from any of these tables. The common column names within the tables should qualify all references to these columns.
SQL> SELECT 2 EMPno,ename,dname,loc 3 FROM EMP,dept; EMPNO ENAME DNAME LOC ---------- ---------- -------------- ------------7839 KING ACCOUNTING NEW YORK 7698 BLAKE ACCOUNTING NEW YORK 7782 CLARK ACCOUNTING NEW YORK 7566 JONES ACCOUNTING NEW YORK 7654 MARTIN ACCOUNTING NEW YORK 7499 ALLEN ACCOUNTING NEW YORK 7844 TURNER ACCOUNTING NEW YORK 7900 JAMES ACCOUNTING NEW YORK 7521 WARD ACCOUNTING NEW YORK 7902 FORD ACCOUNTING NEW YORK 7369 SMITH ACCOUNTING NEW YORK 7788 SCOTT ACCOUNTING NEW YORK 7876 ADAMS ACCOUNTING NEW YORK 7934 MILLER ACCOUNTING NEW YORK 7839 KING RESEARCH DALLAS

176

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7698 BLAKE RESEARCH DALLAS 7782 CLARK RESEARCH DALLAS 7566 JONES RESEARCH DALLAS 7654 MARTIN RESEARCH DALLAS 7499 ALLEN RESEARCH DALLAS 7844 TURNER RESEARCH DALLAS 7900 JAMES RESEARCH DALLAS 7521 WARD RESEARCH DALLAS 7902 FORD RESEARCH DALLAS 7369 SMITH RESEARCH DALLAS 7788 SCOTT RESEARCH DALLAS 7876 ADAMS RESEARCH DALLAS 7934 MILLER RESEARCH DALLAS 7839 KING SALES CHICAGO 7698 BLAKE SALES CHICAGO 7782 CLARK SALES CHICAGO 7566 JONES SALES CHICAGO 7654 MARTIN SALES CHICAGO 7499 ALLEN SALES CHICAGO 7844 TURNER SALES CHICAGO 7900 JAMES SALES CHICAGO 7521 WARD SALES CHICAGO 7902 FORD SALES CHICAGO 7369 SMITH SALES CHICAGO 7788 SCOTT SALES CHICAGO 7876 ADAMS SALES CHICAGO 7934 MILLER SALES CHICAGO 7839 KING OPERATIONS BOSTON 7698 BLAKE OPERATIONS BOSTON 7782 CLARK OPERATIONS BOSTON 7566 JONES OPERATIONS BOSTON 7654 MARTIN OPERATIONS BOSTON 7499 ALLEN OPERATIONS BOSTON 7844 TURNER OPERATIONS BOSTON 7900 JAMES OPERATIONS BOSTON 7521 WARD OPERATIONS BOSTON 7902 FORD OPERATIONS BOSTON 7369 SMITH OPERATIONS BOSTON 7788 SCOTT OPERATIONS BOSTON 7876 ADAMS OPERATIONS BOSTON 7934 MILLER OPERATIONS BOSTON 56 rows selected. SQL> SELECT 2 EMPno,ename,sal,grade 3 FROM EMP, salgrade; EMPNO ENAME SAL GRADE ---------- ---------- ---------- ---------7839 KING 5000 1 7698 BLAKE 2850 1 7782 CLARK 2450 1 7566 JONES 2975 1

177

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7654 MARTIN 7499 ALLEN 7844 TURNER 7900 JAMES 7521 WARD 7902 FORD 7369 SMITH 7788 SCOTT 7876 ADAMS 7934 MILLER 7839 KING 7698 BLAKE 7782 CLARK 7566 JONES 7654 MARTIN 7499 ALLEN 7844 TURNER 7900 JAMES 7521 WARD 7902 FORD 7369 SMITH 7788 SCOTT 7876 ADAMS 7934 MILLER 7839 KING 7698 BLAKE 7782 CLARK 7566 JONES 7654 MARTIN 7499 ALLEN 7844 TURNER 7900 JAMES 7521 WARD 7902 FORD 7369 SMITH 7788 SCOTT 7876 ADAMS 7934 MILLER 7839 KING 7698 BLAKE 7782 CLARK 7566 JONES 7654 MARTIN 7499 ALLEN 7844 TURNER 7900 JAMES 7521 WARD 7902 FORD 7369 SMITH 7788 SCOTT 7876 ADAMS 7934 MILLER 7839 KING 7698 BLAKE

1250 1600 1500 950 1250 3000 800 3000 1100 1300 5000 2850 2450 2975 1250 1600 1500 950 1250 3000 800 3000 1100 1300 5000 2850 2450 2975 1250 1600 1500 950 1250 3000 800 3000 1100 1300 5000 2850 2450 2975 1250 1600 1500 950 1250 3000 800 3000 1100 1300 5000 2850

1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5

178

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7782 CLARK 7566 JONES 7654 MARTIN 7499 ALLEN 7844 TURNER 7900 JAMES 7521 WARD 7902 FORD 7369 SMITH 7788 SCOTT 7876 ADAMS 7934 MILLER 70 rows selected. SQL> Ed Wrote file afiedt.buf

2450 2975 1250 1600 1500 950 1250 3000 800 3000 1100 1300

5 5 5 5 5 5 5 5 5 5 5 5

1 SELECT 2 EMPno,ename,dname,loc, grade 3* FROM EMP,dept, salgrade SQL> / EMPNO ENAME DNAME LOC GRADE ---------- ---------- -------------- ------------- ---------7839 KING ACCOUNTING NEW YORK 1 7698 BLAKE ACCOUNTING NEW YORK 1 7782 CLARK ACCOUNTING NEW YORK 1 7566 JONES ACCOUNTING NEW YORK 1 7654 MARTIN ACCOUNTING NEW YORK 1 7499 ALLEN ACCOUNTING NEW YORK 1 7844 TURNER ACCOUNTING NEW YORK 1 7900 JAMES ACCOUNTING NEW YORK 1 7521 WARD ACCOUNTING NEW YORK 1 7902 FORD ACCOUNTING NEW YORK 1 7369 SMITH ACCOUNTING NEW YORK 1 7788 SCOTT ACCOUNTING NEW YORK 1 7876 ADAMS ACCOUNTING NEW YORK 1 7934 MILLER ACCOUNTING NEW YORK 1 7839 KING ACCOUNTING NEW YORK 2 7698 BLAKE ACCOUNTING NEW YORK 2 7782 CLARK ACCOUNTING NEW YORK 2 7566 JONES ACCOUNTING NEW YORK 2 7654 MARTIN ACCOUNTING NEW YORK 2 7499 ALLEN ACCOUNTING NEW YORK 2 7844 TURNER ACCOUNTING NEW YORK 2 7900 JAMES ACCOUNTING NEW YORK 2 7521 WARD ACCOUNTING NEW YORK 2 7902 FORD ACCOUNTING NEW YORK 2 7369 SMITH ACCOUNTING NEW YORK 2 7788 SCOTT ACCOUNTING NEW YORK 2 7876 ADAMS ACCOUNTING NEW YORK 2 7934 MILLER ACCOUNTING NEW YORK 2 7839 KING ACCOUNTING NEW YORK 3

179

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7698 BLAKE ACCOUNTING NEW YORK 7782 CLARK ACCOUNTING NEW YORK 7566 JONES ACCOUNTING NEW YORK 7654 MARTIN ACCOUNTING NEW YORK 7499 ALLEN ACCOUNTING NEW YORK 7844 TURNER ACCOUNTING NEW YORK 7900 JAMES ACCOUNTING NEW YORK 7521 WARD ACCOUNTING NEW YORK 7902 FORD ACCOUNTING NEW YORK 7369 SMITH ACCOUNTING NEW YORK 7788 SCOTT ACCOUNTING NEW YORK 7876 ADAMS ACCOUNTING NEW YORK 7934 MILLER ACCOUNTING NEW YORK 7839 KING ACCOUNTING NEW YORK 7698 BLAKE ACCOUNTING NEW YORK 7782 CLARK ACCOUNTING NEW YORK 7566 JONES ACCOUNTING NEW YORK 7654 MARTIN ACCOUNTING NEW YORK 7499 ALLEN ACCOUNTING NEW YORK 7844 TURNER ACCOUNTING NEW YORK 7900 JAMES ACCOUNTING NEW YORK 7521 WARD ACCOUNTING NEW YORK 7902 FORD ACCOUNTING NEW YORK 7369 SMITH ACCOUNTING NEW YORK 7788 SCOTT ACCOUNTING NEW YORK 7876 ADAMS ACCOUNTING NEW YORK 7934 MILLER ACCOUNTING NEW YORK 7839 KING ACCOUNTING NEW YORK 7698 BLAKE ACCOUNTING NEW YORK 7782 CLARK ACCOUNTING NEW YORK 7566 JONES ACCOUNTING NEW YORK 7654 MARTIN ACCOUNTING NEW YORK 7499 ALLEN ACCOUNTING NEW YORK 7844 TURNER ACCOUNTING NEW YORK 7900 JAMES ACCOUNTING NEW YORK 7521 WARD ACCOUNTING NEW YORK 7902 FORD ACCOUNTING NEW YORK 7369 SMITH ACCOUNTING NEW YORK 7788 SCOTT ACCOUNTING NEW YORK 7876 ADAMS ACCOUNTING NEW YORK 7934 MILLER ACCOUNTING NEW YORK 7839 KING RESEARCH DALLAS 7698 BLAKE RESEARCH DALLAS 7782 CLARK RESEARCH DALLAS 7566 JONES RESEARCH DALLAS 7654 MARTIN RESEARCH DALLAS 7499 ALLEN RESEARCH DALLAS 7844 TURNER RESEARCH DALLAS 7900 JAMES RESEARCH DALLAS 7521 WARD RESEARCH DALLAS 7902 FORD RESEARCH DALLAS 7369 SMITH RESEARCH DALLAS 7788 SCOTT RESEARCH DALLAS 7876 ADAMS RESEARCH DALLAS

3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 1 1 1 1 1 1 1 1 1 1 1 1 1

180

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7934 MILLER RESEARCH DALLAS 7839 KING RESEARCH DALLAS 7698 BLAKE RESEARCH DALLAS 7782 CLARK RESEARCH DALLAS 7566 JONES RESEARCH DALLAS 7654 MARTIN RESEARCH DALLAS 7499 ALLEN RESEARCH DALLAS 7844 TURNER RESEARCH DALLAS 7900 JAMES RESEARCH DALLAS 7521 WARD RESEARCH DALLAS 7902 FORD RESEARCH DALLAS 7369 SMITH RESEARCH DALLAS 7788 SCOTT RESEARCH DALLAS 7876 ADAMS RESEARCH DALLAS EMPNO ENAME DNAME LOC ---------- ---------- -------------- ------------- ---------7934 MILLER RESEARCH DALLAS 7839 KING RESEARCH DALLAS 7698 BLAKE RESEARCH DALLAS 7782 CLARK RESEARCH DALLAS 7566 JONES RESEARCH DALLAS 7654 MARTIN RESEARCH DALLAS 7499 ALLEN RESEARCH DALLAS 7844 TURNER RESEARCH DALLAS 7900 JAMES RESEARCH DALLAS 7521 WARD RESEARCH DALLAS 7902 FORD RESEARCH DALLAS 7369 SMITH RESEARCH DALLAS 7788 SCOTT RESEARCH DALLAS 7876 ADAMS RESEARCH DALLAS 7934 MILLER RESEARCH DALLAS 7839 KING RESEARCH DALLAS 7698 BLAKE RESEARCH DALLAS 7782 CLARK RESEARCH DALLAS 7566 JONES RESEARCH DALLAS 7654 MARTIN RESEARCH DALLAS 7499 ALLEN RESEARCH DALLAS 7844 TURNER RESEARCH DALLAS 7900 JAMES RESEARCH DALLAS 7521 WARD RESEARCH DALLAS 7902 FORD RESEARCH DALLAS 7369 SMITH RESEARCH DALLAS 7788 SCOTT RESEARCH DALLAS 7876 ADAMS RESEARCH DALLAS 7934 MILLER RESEARCH DALLAS 7839 KING RESEARCH DALLAS 7698 BLAKE RESEARCH DALLAS 7782 CLARK RESEARCH DALLAS 7566 JONES RESEARCH DALLAS 7654 MARTIN RESEARCH DALLAS 7499 ALLEN RESEARCH DALLAS 7844 TURNER RESEARCH DALLAS 7900 JAMES RESEARCH DALLAS

1 2 2 2 2 2 2 2 2 2 2 2 2 2 GRADE 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5

181

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7521 WARD RESEARCH DALLAS 7902 FORD RESEARCH DALLAS 7369 SMITH RESEARCH DALLAS 7788 SCOTT RESEARCH DALLAS 7876 ADAMS RESEARCH DALLAS 7934 MILLER RESEARCH DALLAS 7839 KING SALES CHICAGO 7698 BLAKE SALES CHICAGO 7782 CLARK SALES CHICAGO 7566 JONES SALES CHICAGO 7654 MARTIN SALES CHICAGO 7499 ALLEN SALES CHICAGO 7844 TURNER SALES CHICAGO 7900 JAMES SALES CHICAGO 7521 WARD SALES CHICAGO 7902 FORD SALES CHICAGO 7369 SMITH SALES CHICAGO 7788 SCOTT SALES CHICAGO 7876 ADAMS SALES CHICAGO 7934 MILLER SALES CHICAGO 7839 KING SALES CHICAGO 7698 BLAKE SALES CHICAGO 7782 CLARK SALES CHICAGO 7566 JONES SALES CHICAGO 7654 MARTIN SALES CHICAGO 7499 ALLEN SALES CHICAGO 7844 TURNER SALES CHICAGO 7900 JAMES SALES CHICAGO 7521 WARD SALES CHICAGO 7902 FORD SALES CHICAGO 7369 SMITH SALES CHICAGO 7788 SCOTT SALES CHICAGO 7876 ADAMS SALES CHICAGO 7934 MILLER SALES CHICAGO 7839 KING SALES CHICAGO 7698 BLAKE SALES CHICAGO 7782 CLARK SALES CHICAGO 7566 JONES SALES CHICAGO 7654 MARTIN SALES CHICAGO 7499 ALLEN SALES CHICAGO 7844 TURNER SALES CHICAGO 7900 JAMES SALES CHICAGO 7521 WARD SALES CHICAGO 7902 FORD SALES CHICAGO 7369 SMITH SALES CHICAGO 7788 SCOTT SALES CHICAGO 7876 ADAMS SALES CHICAGO 7934 MILLER SALES CHICAGO 7839 KING SALES CHICAGO 7698 BLAKE SALES CHICAGO 7782 CLARK SALES CHICAGO 7566 JONES SALES CHICAGO 7654 MARTIN SALES CHICAGO 7499 ALLEN SALES CHICAGO

5 5 5 5 5 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4

182

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7844 TURNER 7900 JAMES 7521 WARD 7902 FORD 7369 SMITH 7788 SCOTT

SALES SALES SALES SALES SALES SALES

CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO

4 4 4 4 4 4 GRADE 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3

EMPNO ENAME DNAME LOC ---------- ---------- -------------- ------------- ---------7876 ADAMS SALES CHICAGO 7934 MILLER SALES CHICAGO 7839 KING SALES CHICAGO 7698 BLAKE SALES CHICAGO 7782 CLARK SALES CHICAGO 7566 JONES SALES CHICAGO 7654 MARTIN SALES CHICAGO 7499 ALLEN SALES CHICAGO 7844 TURNER SALES CHICAGO 7900 JAMES SALES CHICAGO 7521 WARD SALES CHICAGO 7902 FORD SALES CHICAGO 7369 SMITH SALES CHICAGO 7788 SCOTT SALES CHICAGO 7876 ADAMS SALES CHICAGO 7934 MILLER SALES CHICAGO 7839 KING OPERATIONS BOSTON 7698 BLAKE OPERATIONS BOSTON 7782 CLARK OPERATIONS BOSTON 7566 JONES OPERATIONS BOSTON 7654 MARTIN OPERATIONS BOSTON 7499 ALLEN OPERATIONS BOSTON 7844 TURNER OPERATIONS BOSTON 7900 JAMES OPERATIONS BOSTON 7521 WARD OPERATIONS BOSTON 7902 FORD OPERATIONS BOSTON 7369 SMITH OPERATIONS BOSTON 7788 SCOTT OPERATIONS BOSTON 7876 ADAMS OPERATIONS BOSTON 7934 MILLER OPERATIONS BOSTON 7839 KING OPERATIONS BOSTON 7698 BLAKE OPERATIONS BOSTON 7782 CLARK OPERATIONS BOSTON 7566 JONES OPERATIONS BOSTON 7654 MARTIN OPERATIONS BOSTON 7499 ALLEN OPERATIONS BOSTON 7844 TURNER OPERATIONS BOSTON 7900 JAMES OPERATIONS BOSTON 7521 WARD OPERATIONS BOSTON 7902 FORD OPERATIONS BOSTON 7369 SMITH OPERATIONS BOSTON 7788 SCOTT OPERATIONS BOSTON 7876 ADAMS OPERATIONS BOSTON 7934 MILLER OPERATIONS BOSTON 7839 KING OPERATIONS BOSTON

183

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7698 BLAKE OPERATIONS BOSTON 7782 CLARK OPERATIONS BOSTON 7566 JONES OPERATIONS BOSTON 7654 MARTIN OPERATIONS BOSTON 7499 ALLEN OPERATIONS BOSTON 7844 TURNER OPERATIONS BOSTON 7900 JAMES OPERATIONS BOSTON 7521 WARD OPERATIONS BOSTON 7902 FORD OPERATIONS BOSTON 7369 SMITH OPERATIONS BOSTON 7788 SCOTT OPERATIONS BOSTON 7876 ADAMS OPERATIONS BOSTON 7934 MILLER OPERATIONS BOSTON 7839 KING OPERATIONS BOSTON 7698 BLAKE OPERATIONS BOSTON 7782 CLARK OPERATIONS BOSTON 7566 JONES OPERATIONS BOSTON 7654 MARTIN OPERATIONS BOSTON 7499 ALLEN OPERATIONS BOSTON 7844 TURNER OPERATIONS BOSTON 7900 JAMES OPERATIONS BOSTON 7521 WARD OPERATIONS BOSTON 7902 FORD OPERATIONS BOSTON 7369 SMITH OPERATIONS BOSTON 7788 SCOTT OPERATIONS BOSTON 7876 ADAMS OPERATIONS BOSTON 7934 MILLER OPERATIONS BOSTON 7839 KING OPERATIONS BOSTON 7698 BLAKE OPERATIONS BOSTON 7782 CLARK OPERATIONS BOSTON 7566 JONES OPERATIONS BOSTON 7654 MARTIN OPERATIONS BOSTON 7499 ALLEN OPERATIONS BOSTON 7844 TURNER OPERATIONS BOSTON 7900 JAMES OPERATIONS BOSTON 7521 WARD OPERATIONS BOSTON 7902 FORD OPERATIONS BOSTON 7369 SMITH OPERATIONS BOSTON 7788 SCOTT OPERATIONS BOSTON 7876 ADAMS OPERATIONS BOSTON 7934 MILLER OPERATIONS BOSTON 280 rows selected. SQL> SELECT 2 EMPno,ename,dept.deptno,dname,loc 3 FROM EMP,dept;

3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5

EMPNO ENAME DEPTNO DNAME LOC ---------- ---------- ---------- -------------- ------------7839 KING 10 ACCOUNTING NEW YORK 7698 BLAKE 10 ACCOUNTING NEW YORK 7782 CLARK 10 ACCOUNTING NEW YORK 7566 JONES 10 ACCOUNTING NEW YORK

184

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7654 MARTIN 7499 ALLEN 7844 TURNER 7900 JAMES 7521 WARD 7902 FORD 7369 SMITH 7788 SCOTT 7876 ADAMS 7934 MILLER 7839 KING 7698 BLAKE 7782 CLARK 7566 JONES 7654 MARTIN 7499 ALLEN 7844 TURNER 7900 JAMES 7521 WARD 7902 FORD 7369 SMITH 7788 SCOTT 7876 ADAMS 7934 MILLER 7839 KING 7698 BLAKE 7782 CLARK 7566 JONES 7654 MARTIN 7499 ALLEN 7844 TURNER 7900 JAMES 7521 WARD 7902 FORD 7369 SMITH 7788 SCOTT 7876 ADAMS 7934 MILLER 7839 KING 7698 BLAKE 7782 CLARK 7566 JONES 7654 MARTIN 7499 ALLEN 7844 TURNER 7900 JAMES 7521 WARD 7902 FORD 7369 SMITH 7788 SCOTT 7876 ADAMS 7934 MILLER 56 rows selected.

10 ACCOUNTING NEW YORK 10 ACCOUNTING NEW YORK 10 ACCOUNTING NEW YORK 10 ACCOUNTING NEW YORK 10 ACCOUNTING NEW YORK 10 ACCOUNTING NEW YORK 10 ACCOUNTING NEW YORK 10 ACCOUNTING NEW YORK 10 ACCOUNTING NEW YORK 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 20 RESEARCH DALLAS 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON 40 OPERATIONS BOSTON

185

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

JOIN Condition Many join queries contain where clause, which compares two columns, each from a different table. 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 columns in the join conditions 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. To execute a join of three of more tables Oracle first joins two of the tables based on the join conditions comparing these columns and then joins the result to another join. Table1 Join 01 Table 2

Result 01

Join 02

Table 3

Result 02 The oracle optimizer determines the order in which oracle should join the tables based on. Given join condition(s). Indexes upon the tables. Statistics for the tables. The lob columns cannot be specified in the where clause, when the where clause contains any joins.

Syntax Where Table1.Column1 = Table2.Column2 Guidelines When writing a select statement that joins tables, precede the column name with the table name for clarity and enhance database access. If the same column name appears in more than one table, the column name must be prefixed with the table name. To join n tables together, we need a minimum of n-1 join conditions. The above rule does not apply, if the table contains a concatenated primary key. Equi Joins or Simple Joins or Inner Joins An equijoin is a join with a join condition containing an equality operator. It combines rows that have equivalent values for the specified columns. 186 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

The total size of columns in the equijoin condition in a single table may be limited to the size of a data block minus some overhead. The size of the data block is specified by the initialization parameter DB_BLOCK_SIZE.

Qualifying Ambiguous Column Names: The names of the column names should be qualified in the where clause, with the table name to avoid ambiguity. If there are no common column names between the two tables, the qualification is not necessary but it is better.
SQL> SELECT 2 EMP.EMPno Empno, 3 EMP.ename ename, 4 EMP.deptno deptno, 5 dept.deptno deptno, 6 dept.dname dname, 7 dept.loc loc 8 FROM EMP,dept 9 WHERE EMP.deptno=dept.deptno; EMPNO ENAME DEPTNO DEPTNO DNAME LOC ---------- ---------- ---------- ---------- -------------- ------------7839 KING 10 10 ACCOUNTING NEW YORK 7698 BLAKE 30 30 SALES CHICAGO 7782 CLARK 10 10 ACCOUNTING NEW YORK 7566 JONES 20 20 RESEARCH DALLAS 7654 MARTIN 30 30 SALES CHICAGO 7499 ALLEN 30 30 SALES CHICAGO 7844 TURNER 30 30 SALES CHICAGO 7900 JAMES 30 30 SALES CHICAGO 7521 WARD 30 30 SALES CHICAGO 7902 FORD 20 20 RESEARCH DALLAS 7369 SMITH 20 20 RESEARCH DALLAS 7788 SCOTT 20 20 RESEARCH DALLAS 7876 ADAMS 20 20 RESEARCH DALLAS 7934 MILLER 10 10 ACCOUNTING NEW YORK 14 rows selected. SQL> SELECT 2 EMPno,ename,EMP.deptno,loc 3 FROM EMP,dept 4 WHERE EMP.deptno=dept.deptno AND 5 job=UPPER('manager'); EMPNO ENAME DEPTNO LOC ---------- ---------- ---------- ------------7698 BLAKE 30 CHICAGO 7782 CLARK 10 NEW YORK 7566 JONES 20 DALLAS 3 rows selected.

187

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT 2 EMPno,ename,Sal*12 AnnSal,EMP.deptno,loc 3 FROM EMP,dept 4 WHERE EMP.deptno=dept.deptno; EMPNO ENAME ANNSAL DEPTNO LOC ---------- ---------- ---------- ---------- ------------7839 KING 60000 10 NEW YORK 7698 BLAKE 34200 30 CHICAGO 7782 CLARK 29400 10 NEW YORK 7566 JONES 35700 20 DALLAS 7654 MARTIN 15000 30 CHICAGO 7499 ALLEN 19200 30 CHICAGO 7844 TURNER 18000 30 CHICAGO 7900 JAMES 11400 30 CHICAGO 7521 WARD 15000 30 CHICAGO 7902 FORD 36000 20 DALLAS 7369 SMITH 9600 20 DALLAS 7788 SCOTT 36000 20 DALLAS 7876 ADAMS 13200 20 DALLAS 7934 MILLER 15600 10 NEW YORK 14 rows selected.

Using Table Aliases: Tables aliases can be used instead of original table names. A table alias gives an alternate name for the existing queried table. Table aliases help in keeping the sql code smaller, hence using less memory. The table alias is specified in the from clause. Guidelines: A table alias can be up to 30 characters in length. If a 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. A table alias should be meaningful and should be maintained as short as possible. A table alias is valid only for the current select statement only.
SQL> SELECT 2 e.EMPno,e.ename,d.deptno,d.dname 3 FROM EMP e,dept d 4 WHERE e.deptno=d.deptno; EMPNO ENAME DEPTNO DNAME ---------- ---------- ---------- -------------7839 KING 10 ACCOUNTING 7698 BLAKE 30 SALES 7782 CLARK 10 ACCOUNTING 7566 JONES 20 RESEARCH 7654 MARTIN 30 SALES 7499 ALLEN 30 SALES 7844 TURNER 30 SALES

188

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7900 JAMES 7521 WARD 7902 FORD 7369 SMITH 7788 SCOTT 7876 ADAMS 7934 MILLER 14 rows selected.

30 SALES 30 SALES 20 RESEARCH 20 RESEARCH 20 RESEARCH 20 RESEARCH 10 ACCOUNTING

SQL> SELECT 2 e.ename,e.job,d.deptno,d.dname,d.loc 3 FROM EMP e,dept d 4 WHERE e.deptno=d.deptno AND 5 e.job IN('ANALYST','MANAGER'); ENAME JOB DEPTNO DNAME LOC ---------- --------- ---------- -------------- ------------BLAKE MANAGER 30 SALES CHICAGO CLARK MANAGER 10 ACCOUNTING NEW YORK JONES MANAGER 20 RESEARCH DALLAS FORD ANALYST 20 RESEARCH DALLAS SCOTT ANALYST 20 RESEARCH DALLAS 5 rows selected. SQL> SELECT 2 e.ename,e.job,d.dname,d.loc 3 FROM EMP e,dept d 4 WHERE e.deptno=d.deptno AND 5 d.dname<>'SALES'; ENAME JOB DNAME LOC ---------- --------- -------------- ------------KING PRESIDENT ACCOUNTING NEW YORK CLARK MANAGER ACCOUNTING NEW YORK JONES MANAGER RESEARCH DALLAS FORD ANALYST RESEARCH DALLAS SMITH CLERK RESEARCH DALLAS SCOTT ANALYST RESEARCH DALLAS ADAMS CLERK RESEARCH DALLAS MILLER CLERK ACCOUNTING NEW YORK 8 rows selected.

Self Joins It is a join of a table to itself. The same table appears twice in the from clause and is followed by table aliases. The table aliases must qualify the column names in the join condition. To perform a self join, oracle combines and returns rows of the table that satisfy the join condition. Syntax 189 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> select columns From table1 t1, table t2 Where t1.column1=t2.column2 Illustrations
SQL> SELECT 2 e1.ename "Employees Name", 3 e2.ename "Managers Name" 4 FROM EMP e1,EMP e2 5 WHERE e1.mgr=e2.EMPno; Employees N Managers N ---------- ---------JONES KING CLARK KING BLAKE KING WARD BLAKE JAMES BLAKE TURNER BLAKE ALLEN BLAKE MARTIN BLAKE MILLER CLARK SCOTT JONES FORD JONES SMITH FORD ADAMS SCOTT 13 rows selected. SQL> SELECT 2 e1.ename||'''s Managers is '|| 3 e2.ename "Employees And Managers " 4 FROM EMP e1,EMP e2 5 WHERE e1.mgr=e2.EMPno; Employees And Managers ----------------------------------JONES's Managers is KING CLARK's Managers is KING BLAKE's Managers is KING WARD's Managers is BLAKE JAMES's Managers is BLAKE TURNER's Managers is BLAKE ALLEN's Managers is BLAKE MARTIN's Managers is BLAKE MILLER's Managers is CLARK SCOTT's Managers is JONES FORD's Managers is JONES SMITH's Managers is FORD ADAMS's Managers is SCOTT 13 rows selected.

190

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT 2 e1.ename||'Works For '|| 3 e2.ename "Employees And Managers " 4 FROM EMP e1,EMP e2 5 WHERE (e1.mgr=e2.EMPno) AND 6 e1.job='CLERK'; Employees And Managers -----------------------------JAMES Works For BLAKE SMITH Works For FORD ADAMS Works For SCOTT MILLER Works For CLARK 4 rows selected.

Cartesian Products The Cartesian product is a join query that does not contain a join condition. During Cartesian product oracle combines each row of one table with each row of the other. If tends to generate a large number of rows and the result is rarely useful.
SQL> SELECT 2 ename,job,dname 3 FROM EMP,dept; ENAME JOB DNAME ---------- --------- -------------KING PRESIDENT ACCOUNTING BLAKE MANAGER ACCOUNTING CLARK MANAGER ACCOUNTING JONES MANAGER ACCOUNTING MARTIN SALESMAN ACCOUNTING ALLEN SALESMAN ACCOUNTING TURNER SALESMAN ACCOUNTING JAMES CLERK ACCOUNTING WARD SALESMAN ACCOUNTING FORD ANALYST ACCOUNTING SMITH CLERK ACCOUNTING SCOTT ANALYST ACCOUNTING ADAMS CLERK ACCOUNTING MILLER CLERK ACCOUNTING KING PRESIDENT RESEARCH BLAKE MANAGER RESEARCH CLARK MANAGER RESEARCH JONES MANAGER RESEARCH MARTIN SALESMAN RESEARCH ALLEN SALESMAN RESEARCH TURNER SALESMAN RESEARCH JAMES CLERK RESEARCH WARD SALESMAN RESEARCH FORD ANALYST RESEARCH

191

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SMITH CLERK RESEARCH SCOTT ANALYST RESEARCH ADAMS CLERK RESEARCH MILLER CLERK RESEARCH KING PRESIDENT SALES BLAKE MANAGER SALES CLARK MANAGER SALES JONES MANAGER SALES MARTIN SALESMAN SALES ALLEN SALESMAN SALES TURNER SALESMAN SALES JAMES CLERK SALES WARD SALESMAN SALES FORD ANALYST SALES SMITH CLERK SALES SCOTT ANALYST SALES ADAMS CLERK SALES MILLER CLERK SALES KING PRESIDENT OPERATIONS BLAKE MANAGER OPERATIONS CLARK MANAGER OPERATIONS JONES MANAGER OPERATIONS MARTIN SALESMAN OPERATIONS ALLEN SALESMAN OPERATIONS TURNER SALESMAN OPERATIONS JAMES CLERK OPERATIONS WARD SALESMAN OPERATIONS FORD ANALYST OPERATIONS SMITH CLERK OPERATIONS SCOTT ANALYST OPERATIONS ADAMS CLERK OPERATIONS MILLER CLERK OPERATIONS 56 rows selected. SQL> SELECT 2 ename,job,dname 3 FROM EMP,dept 4 WHERE job='MANAGER'; ENAME JOB DNAME ---------- --------- -------------BLAKE MANAGER ACCOUNTING BLAKE MANAGER RESEARCH BLAKE MANAGER SALES BLAKE MANAGER OPERATIONS CLARK MANAGER ACCOUNTING CLARK MANAGER RESEARCH CLARK MANAGER SALES CLARK MANAGER OPERATIONS JONES MANAGER ACCOUNTING JONES MANAGER RESEARCH JONES MANAGER SALES JONES MANAGER OPERATIONS

192

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

12 rows selected.

Non Equi Join It is a join condition that is executed when no column in one table corresponds directly to a column in the other table. The data in the tables in directly not related but indirectly or logically related through proper values.
SQL> SELECT 2 e.ename,e.sal,s.grade 3 FROM EMP e,salgrade s 4 WHERE e.sal BETWEEN s.losal AND s.hisal; ENAME SAL GRADE ---------- ---------- ---------SMITH 800 1 JAMES 950 1 ADAMS 1100 1 MARTIN 1250 2 WARD 1250 2 MILLER 1300 2 TURNER 1500 3 ALLEN 1600 3 CLARK 2450 4 BLAKE 2850 4 JONES 2975 4 FORD 3000 4 SCOTT 3000 4 KING 5000 5 14 rows selected. SQL> SELECT 2 e.ename,e.sal,s.grade 3 FROM EMP e,salgrade s 4 WHERE (e.sal>=s.losal AND e.sal<=s.hisal) AND s.grade=1; ENAME SAL GRADE ---------- ---------- ---------JAMES 950 1 SMITH 800 1 ADAMS 1100 1 3 rows selected.

Outer Joins 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 those rows from one table for which no rows from the outer satisfy the join condition. To perform an outer join of tables A and B and returns all rows from A, apply the outer join operator (+) to all columns of table B. 193 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

For all rows in A that have no matching rows in B oracle returns NULL for any select list expressions containing columns of B.

Syntax: SQL> select Table1.column, Table2.column From Table1, Table2 Where Table1.column (+) = Table2.column; SQL>select Table1.column, Table2.column From Table1, Table2 Where Table1.column = Table2.column (+); Rules and Restrictions: The (+) operator can appear only in the where clause. The (+) operator can appear in the context of the left correlation in the from clause, and can be applied only to a column of a table or view. If A and B are joined by multiple join condition, we must use the (+) operator in all of these conditions. The (+) operator can be applied only to a column, not to an arbitrary expressions. A condition containing the (+) operator cannot be combined with another condition using the or logical operator. A condition cannot use the IN comparison operator to compare a column marked with the (+) operator with an expression. A condition cannot compare any column marked with the (+) operator with a sub query.
SQL> SELECT 2 e.ename,d.deptno,d.dname 3 FROM EMP e,dept d 4 WHERE e.deptno(+)=d.deptno 5 ORDER BY e.deptno; ENAME DEPTNO DNAME ---------- ---------- -------------KING 10 ACCOUNTING CLARK 10 ACCOUNTING MILLER 10 ACCOUNTING JONES 20 RESEARCH SCOTT 20 RESEARCH ADAMS 20 RESEARCH SMITH 20 RESEARCH FORD 20 RESEARCH BLAKE 30 SALES MARTIN 30 SALES ALLEN 30 SALES TURNER 30 SALES JAMES 30 SALES WARD 30 SALES 40 OPERATIONS

194

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

15 rows selected. SQL> SELECT 2 e.ename,d.deptno,d.dname 3 FROM EMP e,dept d 4 WHERE e.deptno(+)=d.deptno 5 AND e.deptno(+)=10 6 ORDER BY e.deptno; ENAME DEPTNO DNAME ---------- ---------- -------------KING 10 ACCOUNTING CLARK 10 ACCOUNTING MILLER 10 ACCOUNTING 30 SALES 40 OPERATIONS 20 RESEARCH 6 rows selected. SQL> ED Wrote file afiedt.buf 1 SELECT 2 e.ename,d.deptno,d.dname 3 FROM EMP e,dept d 4 WHERE e.deptno=d.deptno(+) 5 AND e.deptno(+)=10 6* ORDER BY e.deptno SQL> / ENAME DEPTNO DNAME ---------- ---------- -------------KING 10 ACCOUNTING CLARK 10 ACCOUNTING MILLER 10 ACCOUNTING 3 rows selected. SQL> Ed Wrote file afiedt.buf 1 SELECT 2 e.ename Employees, 3 NVL(m.ename, 'Supreme Authority') Manager 4 FROM EMP e,EMP m 5* WHERE e.mgr=m.EMPno(+) SQL> / EMPLOYEE MANAGER ---------- ---------------JONES KING CLARK KING BLAKE KING

195

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

WARD BLAKE JAMES BLAKE TURNER BLAKE ALLEN BLAKE MARTIN BLAKE MILLER CLARK SCOTT JONES FORD JONES SMITH FORD ADAMS SCOTT KING Supreme Authority 14 rows selected.

Joining Data From More Than Two Table Joins can be established 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 2 C.name,o.ordid,i.itemId,i.itemtot.o.total 3 FROM customer c,ord o,item i 4 WHERE 5 c.custid=o.custid AND 6 o.ordid=i.ordid AND 7 c.name='TKB SPORT SHOP'; C.name,o.ordid,i.itemId,i.itemtot.o.total * ERROR at line 2: ORA-00904: "I"."ITEMTOT"."O"."TOTAL": invalid identifier SQL> SELECT 2 e.ename,e.deptno,m.ename Manager,m.deptno 3 FROM EMP e,dept d,EMP m 4 WHERE 5 e.mgr=m.EMPno AND 6 e.deptno=d.deptno; ENAME DEPTNO MANAGER DEPTNO ---------- ---------- ---------- ---------JONES 20 KING 10 CLARK 10 KING 10 BLAKE 30 KING 10 WARD 30 BLAKE 30 JAMES 30 BLAKE 30 TURNER 30 BLAKE 30 ALLEN 30 BLAKE 30 MARTIN 30 BLAKE 30 MILLER 10 CLARK 10 SCOTT 20 JONES 20 FORD 20 JONES 20 SMITH 20 FORD 20 ADAMS 20 SCOTT 20

196

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

13 rows selected. SQL> Ed Wrote file afiedt.buf 1 SELECT 2 e.ename ename, 3 dname, 4 e.sal esal, 5 se.grade egrade, 6 m.sal msal, 7 sm.grade mgrade 8 FROM EMP e,dept d,EMP m,salgrade se,salgrade sm 9 WHERE 10 e.deptno=d.deptno AND 11 e.mgr=m.EMPno AND 12 e.sal BETWEEN se.losal AND se.hisal AND 13* m.sal BETWEEN sm.losal AND sm.hisal SQL> / ENAME DNAME ESAL EGRADE MSAL MGRADE ---------- -------------- ---------- ---------- ---------- ---------SMITH RESEARCH 800 1 3000 4 JAMES SALES 950 1 2850 4 ADAMS RESEARCH 1100 1 3000 4 MARTIN SALES 1250 2 2850 4 WARD SALES 1250 2 2850 4 MILLER ACCOUNTING 1300 2 2450 4 TURNER SALES 1500 3 2850 4 ALLEN SALES 1600 3 2850 4 CLARK ACCOUNTING 2450 4 5000 5 BLAKE SALES 2850 4 5000 5 JONES RESEARCH 2975 4 5000 5 FORD RESEARCH 3000 4 2975 4 SCOTT RESEARCH 3000 4 2975 4 13 rows selected.

Categories of Joins Oracle Proprietary Joins (8i and Prior) Equi join Non-Eql join Outer join Self join ANSI SQL : 1999 Compliant Joins Cross joins Natural joins Using clause Full or two sided outer joins 197 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Arbitrary join conditions for outer joins

ISR OR ANSI Jons Cross Join


SQL> SELECT 2 ename,dept.deptno,dname,loc 3 FROM EMP CROSS JOIN dept 4 WHERE EMP.deptno=dept.deptno; ENAME DEPTNO DNAME LOC ---------- ---------- -------------- ------------KING 10 ACCOUNTING NEW YORK BLAKE 30 SALES CHICAGO CLARK 10 ACCOUNTING NEW YORK JONES 20 RESEARCH DALLAS MARTIN 30 SALES CHICAGO ALLEN 30 SALES CHICAGO TURNER 30 SALES CHICAGO JAMES 30 SALES CHICAGO WARD 30 SALES CHICAGO FORD 20 RESEARCH DALLAS SMITH 20 RESEARCH DALLAS SCOTT 20 RESEARCH DALLAS ADAMS 20 RESEARCH DALLAS MILLER 10 ACCOUNTING NEW YORK 14 rows selected.

Natural Join
SQL> SELECT 2 ename,deptno,dname,loc 3 FROM EMP NATURAL JOIN dept; ENAME DEPTNO DNAME LOC ---------- ---------- -------------- ------------KING 10 ACCOUNTING NEW YORK BLAKE 30 SALES CHICAGO CLARK 10 ACCOUNTING NEW YORK JONES 20 RESEARCH DALLAS MARTIN 30 SALES CHICAGO ALLEN 30 SALES CHICAGO TURNER 30 SALES CHICAGO JAMES 30 SALES CHICAGO WARD 30 SALES CHICAGO FORD 20 RESEARCH DALLAS SMITH 20 RESEARCH DALLAS SCOTT 20 RESEARCH DALLAS ADAMS 20 RESEARCH DALLAS MILLER 10 ACCOUNTING NEW YORK

198

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

14 rows selected.

Using Clause
SQL> SELECT 2 ename,deptno,dname,loc 3 FROM EMP JOIN dept 4 USING(deptno); ENAME DEPTNO DNAME LOC ---------- ---------- -------------- ------------KING 10 ACCOUNTING NEW YORK BLAKE 30 SALES CHICAGO CLARK 10 ACCOUNTING NEW YORK JONES 20 RESEARCH DALLAS MARTIN 30 SALES CHICAGO ALLEN 30 SALES CHICAGO TURNER 30 SALES CHICAGO JAMES 30 SALES CHICAGO WARD 30 SALES CHICAGO FORD 20 RESEARCH DALLAS SMITH 20 RESEARCH DALLAS SCOTT 20 RESEARCH DALLAS ADAMS 20 RESEARCH DALLAS MILLER 10 ACCOUNTING NEW YORK 14 rows selected.

Inner Join
SQL> SELECT 2 ename,dept.deptno,dname,loc 3 FROM EMP JOIN dept 4 ON EMP.deptno=dept.deptno; ENAME DEPTNO DNAME LOC ---------- ---------- -------------- ------------KING 10 ACCOUNTING NEW YORK BLAKE 30 SALES CHICAGO CLARK 10 ACCOUNTING NEW YORK JONES 20 RESEARCH DALLAS MARTIN 30 SALES CHICAGO ALLEN 30 SALES CHICAGO TURNER 30 SALES CHICAGO JAMES 30 SALES CHICAGO WARD 30 SALES CHICAGO FORD 20 RESEARCH DALLAS SMITH 20 RESEARCH DALLAS SCOTT 20 RESEARCH DALLAS ADAMS 20 RESEARCH DALLAS MILLER 10 ACCOUNTING NEW YORK 14 rows selected.

199

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Self Join
SQL> SELECT 2 e.ename Employees, 3 m.ename Manager 4 FROM EMP e INNER JOIN EMP m 5 ON(e.mgr=m.EMPno); EMPLOYEE MANAGER ---------- ---------JONES KING CLARK KING BLAKE KING WARD BLAKE JAMES BLAKE TURNER BLAKE ALLEN BLAKE MARTIN BLAKE MILLER CLARK SCOTT JONES FORD JONES SMITH FORD ADAMS SCOTT 13 rows selected.

Join on More Than Two Tables


SQL> Ed Wrote file afiedt.buf 1 SELECT 2 ename,sal,grade,dept.deptno,dname 3 FROM EMP JOIN dept 4 ON EMP.deptno=dept.deptno 5 JOIN salgrade 6* ON EMP.sal BETWEEN losal AND hisal SQL> / ENAME SAL GRADE DEPTNO DNAME ---------- ---------- ---------- ---------- -------------SMITH 800 1 20 RESEARCH JAMES 950 1 30 SALES ADAMS 1100 1 20 RESEARCH MARTIN 1250 2 30 SALES WARD 1250 2 30 SALES MILLER 1300 2 10 ACCOUNTING TURNER 1500 3 30 SALES ALLEN 1600 3 30 SALES CLARK 2450 4 10 ACCOUNTING BLAKE 2850 4 30 SALES JONES 2975 4 20 RESEARCH FORD 3000 4 20 RESEARCH SCOTT 3000 4 20 RESEARCH

200

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

KING

5000

10 ACCOUNTING

14 rows selected. SQL> SELECT 2 e.ename,m.ename,sal,grade,d.deptno,dname 3 FROM EMP e INNER JOIN dept d 4 ON e.deptno=d.deptno 5 INNER JOIN EMP m 6 ON e.EMPno=m.mgr 7 INNER JOIN salgrade s 8 ON e.sal BETWEEN losal AND hisal; ENAME ENAME SAL GRADE DEPTNO DNAME ---------- ---------- ---------- ---------- ---------- -------------KING BLAKE 2850 5 10 ACCOUNTING KING CLARK 2450 5 10 ACCOUNTING KING JONES 2975 5 10 ACCOUNTING BLAKE MARTIN 1250 4 30 SALES BLAKE ALLEN 1600 4 30 SALES BLAKE TURNER 1500 4 30 SALES BLAKE JAMES 950 4 30 SALES BLAKE WARD 1250 4 30 SALES JONES FORD 3000 4 20 RESEARCH FORD SMITH 800 4 20 RESEARCH JONES SCOTT 3000 4 20 RESEARCH SCOTT ADAMS 1100 4 20 RESEARCH CLARK MILLER 1300 4 10 ACCOUNTING 13 rows selected.

Right Outer Join


SQL> SELECT 2 ename,dept.deptno,dname,loc 3 FROM EMP RIGHT JOIN dept 4 ON EMP.deptno=dept.deptno; ENAME DEPTNO DNAME LOC ---------- ---------- -------------- ------------KING 10 ACCOUNTING NEW YORK BLAKE 30 SALES CHICAGO CLARK 10 ACCOUNTING NEW YORK JONES 20 RESEARCH DALLAS MARTIN 30 SALES CHICAGO ALLEN 30 SALES CHICAGO TURNER 30 SALES CHICAGO JAMES 30 SALES CHICAGO WARD 30 SALES CHICAGO FORD 20 RESEARCH DALLAS SMITH 20 RESEARCH DALLAS SCOTT 20 RESEARCH DALLAS ADAMS 20 RESEARCH DALLAS MILLER 10 ACCOUNTING NEW YORK

201

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

40 OPERATIONS 15 rows selected.

BOSTON

Left Outer Join


SQL> SELECT 2 ename,dept.deptno,dname,loc 3 FROM EMP LEFT JOIN dept 4 ON EMP.deptno=dept.deptno; ENAME DEPTNO DNAME LOC ---------- ---------- -------------- ------------MILLER 10 ACCOUNTING NEW YORK CLARK 10 ACCOUNTING NEW YORK KING 10 ACCOUNTING NEW YORK ADAMS 20 RESEARCH DALLAS SCOTT 20 RESEARCH DALLAS SMITH 20 RESEARCH DALLAS FORD 20 RESEARCH DALLAS JONES 20 RESEARCH DALLAS WARD 30 SALES CHICAGO JAMES 30 SALES CHICAGO TURNER 30 SALES CHICAGO ALLEN 30 SALES CHICAGO MARTIN 30 SALES CHICAGO BLAKE 30 SALES CHICAGO 14 rows selected.

Full Join
SQL> SELECT 2 ename,dept.deptno,dname,loc 3 FROM EMP FULL JOIN dept 4 ON dept.deptno=EMP.deptno; ENAME DEPTNO DNAME LOC ---------- ---------- -------------- ------------MILLER 10 ACCOUNTING NEW YORK CLARK 10 ACCOUNTING NEW YORK KING 10 ACCOUNTING NEW YORK ADAMS 20 RESEARCH DALLAS SCOTT 20 RESEARCH DALLAS SMITH 20 RESEARCH DALLAS FORD 20 RESEARCH DALLAS JONES 20 RESEARCH DALLAS WARD 30 SALES CHICAGO JAMES 30 SALES CHICAGO TURNER 30 SALES CHICAGO ALLEN 30 SALES CHICAGO MARTIN 30 SALES CHICAGO BLAKE 30 SALES CHICAGO 40 OPERATIONS BOSTON

202

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

15 rows selected.

SQL> SELECT 2 ename,dept.deptno,dname,loc 3 FROM EMP FULL JOIN dept 4 ON EMP.deptno=dept.deptno; ENAME DEPTNO DNAME LOC ---------- ---------- -------------- ------------MILLER 10 ACCOUNTING NEW YORK CLARK 10 ACCOUNTING NEW YORK KING 10 ACCOUNTING NEW YORK ADAMS 20 RESEARCH DALLAS SCOTT 20 RESEARCH DALLAS SMITH 20 RESEARCH DALLAS FORD 20 RESEARCH DALLAS JONES 20 RESEARCH DALLAS WARD 30 SALES CHICAGO JAMES 30 SALES CHICAGO TURNER 30 SALES CHICAGO ALLEN 30 SALES CHICAGO MARTIN 30 SALES CHICAGO BLAKE 30 SALES CHICAGO 40 OPERATIONS BOSTON 15 rows selected.

Some Complications
SQL> SELECT 2 e.ename Employees, 3 m.ename Manager 4 FROM EMP e LEFT OUTER JOIN EMP m 5 ON(e.mgr=m.EMPno) 6 ORDER BY 2; EMPLOYEE MANAGER ---------- ---------WARD BLAKE JAMES BLAKE ALLEN BLAKE TURNER BLAKE MARTIN BLAKE MILLER CLARK SMITH FORD SCOTT JONES FORD JONES JONES KING CLARK KING BLAKE KING ADAMS SCOTT KING

203

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

14 rows selected. SQL> Ed Wrote file afiedt.buf 1 SELECT 2 e.ename,m.ename,sal,grade,d.deptno,dname 3 FROM EMP e INNER JOIN dept d 4 ON e.deptno=d.deptno 5 INNER JOIN EMP m 6 ON e.EMPno=m.mgr 7 INNER JOIN salgrade s 8* ON e.sal BETWEEN losal AND hisal SQL> / ENAME ENAME SAL GRADE DEPTNO DNAME ---------- ---------- ---------- ---------- ---------- -------------KING BLAKE 2850 5 10 ACCOUNTING KING CLARK 2450 5 10 ACCOUNTING KING JONES 2975 5 10 ACCOUNTING BLAKE MARTIN 1250 4 30 SALES BLAKE ALLEN 1600 4 30 SALES BLAKE TURNER 1500 4 30 SALES BLAKE JAMES 950 4 30 SALES BLAKE WARD 1250 4 30 SALES JONES FORD 3000 4 20 RESEARCH FORD SMITH 800 4 20 RESEARCH JONES SCOTT 3000 4 20 RESEARCH SCOTT ADAMS 1100 4 20 RESEARCH CLARK MILLER 1300 4 10 ACCOUNTING 13 rows selected.

204

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Let Us Move into Pipelining the Results of the Queries

205

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Sub Queries OR Nested Select OR Sub Select OR Inner Select A sub query answer multiple-part questions. A sub query in the where clause of a select statement is called as nested sub query. A sub query in the where clause of statement is called as inline view. A sub query can be part of a column, in the select list. A sub query can contain another sub query. Oracle imposes no limit on the number of sub query levels in the from clause of the toplevel query. 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 name or table alias. Purpose of A 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 view in a create view or create materialized view statement. To define one or more values to be assigned to existing rows in an update statement. To provide values for conditions in a where clause, having clause, start with clause of select, update, and delete statements. To define a table to be created on by a containing query. Sub Query Principle Solve a problem by combining the 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. Sub Query Usage They are practically very useful when we need to select rows from a table with a condition that depends on the data in the table itself. Syntax SQL>select selectList From TableName Where ColumnName Operator ( Select selectList From TableName ); The expressional operators in sub queries can be categorized into Single row operators -> =, <>, <, >, >=, <= Multiple row operators -> IN, ANY, ALL

Types of Sub Queries Single Row Sub Query: These queries return only one row from the inner select statement. 206 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Multiple Row Sub Query: These queries return more than one row from the inner select statement. Multiple Column Sub Query: These queries return more than one column from the inner select statement. Guidelines To Follow. A sub query must be enclosed in parenthesis. A sub query must appear on the right side of the comparison operator only. Sub queries should not contain an order by clause. Only one order by clause can be implemented for the total select statement. Two classes of comparison operators can be used in sub queries they are. Single row operators. Multiple row operators Let Us Start With Single Row Sub Queries
SQL> SELECT ename,sal,job 2 FROM EMP 3 WHERE Sal>(SELECT Sal 4 FROM EMP 5 WHERE Empno=7566 6 ); ENAME SAL JOB ---------- ---------- --------KING 5000 PRESIDENT FORD 3000 ANALYST SCOTT 3000 ANALYST 3 rows selected. SQL> SELECT ename,sal,job 2 FROM EMP 3 WHERE job=(SELECT job 4 FROM EMP 5 WHERE ename=UPPER('smith') 6 ) 7 ORDER 8 BY Sal; ENAME SAL JOB ---------- ---------- --------SMITH 800 CLERK JAMES 950 CLERK ADAMS 1100 CLERK MILLER 1300 CLERK 4 rows selected. SQL> SELECT EMPno,ename,hiredate,sal

207

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 3 4 5 6 7

FROM EMP WHERE hiredate>(SELECT hiredate FROM EMP WHERE ename='TURNER' ) ORDER BY Sal;

EMPNO ENAME HIREDATE SAL ---------- ---------- --------- ---------7900 JAMES 03-DEC-81 950 7876 ADAMS 12-JAN-83 1100 7654 MARTIN 28-SEP-81 1250 7934 MILLER 23-JAN-82 1300 7902 FORD 03-DEC-81 3000 7788 SCOTT 09-DEC-82 3000 7839 KING 17-NOV-81 5000 7 rows selected. SQL> SELECT EMPno,ename,sal,job 2 FROM EMP 3 WHERE deptno=(SELECT deptno 4 FROM dept 5 WHERE dname='SALES' 6 ); EMPNO ENAME SAL JOB ---------- ---------- ---------- --------7698 BLAKE 2850 MANAGER 7654 MARTIN 1250 SALESMAN 7499 ALLEN 1600 SALESMAN 7844 TURNER 1500 SALESMAN 7900 JAMES 950 CLERK 7521 WARD 1250 SALESMAN 6 rows selected. SQL> SELECT Empno, ename,sal,comm,sal+nvl(comm,0) 2 FROM EMP 3 WHERE deptno=(SELECT deptno 4 FROM dept 5 WHERE loc='DALLAS' 6 ); EMPNO ENAME SAL COMM SAL+NVL(COMM,0) ---------- ---------- ---------- ---------- --------------7566 JONES 2975 2975 7902 FORD 3000 3000 7369 SMITH 800 800 7788 SCOTT 3000 3000 7876 ADAMS 1100 1100 5 rows selected.

208

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Applying Group Functions in Sub Queries The data from the main query can be displayed by using a group function in a sub query. As a group function returns a single row, the query passes through the success state. The inner sub query should not have a group by clause in this scenario.
SQL> SELECT ename,job,sal 2 FROM EMP 3 WHERE Sal=(SELECT MAX(Sal) 4 FROM EMP 5 ); ENAME JOB SAL ---------- --------- ---------KING PRESIDENT 5000 1 row selected. SQL> SQL> SELECT ename,job,sal 2 FROM EMP 3 WHERE Sal=(SELECT MIN(Sal) 4 FROM EMP 5 ); ENAME JOB SAL ---------- --------- ---------SMITH CLERK 800 1 row selected. SQL> SELECT ename,job,sal 2 FROM EMP 3 WHERE Sal>(SELECT AVG(Sal) 4 FROM EMP 5 ); ENAME JOB SAL ---------- --------- ---------KING PRESIDENT 5000 BLAKE MANAGER 2850 CLARK MANAGER 2450 JONES MANAGER 2975 FORD ANALYST 3000 SCOTT ANALYST 3000 6 rows selected. SQL> SELECT ename,job,sal

209

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 3 4 5

FROM EMP WHERE Sal<(SELECT STDDEV(Sal) FROM EMP );

ENAME JOB SAL ---------- --------- ---------JAMES CLERK 950 SMITH CLERK 800 ADAMS CLERK 1100 3 rows selected.

Applying Having Clause With Sub Queries A sub query can be also applied in having clause. The oracle server executes the sub query, and the results are returned into the having clause of the main query. The inner query need not use any group functions in this scenario. The outer queries having clause contains group function.
SQL> SELECT deptno,MIN(Sal) 2 FROM EMP 3 GROUP BY deptno 4 HAVING MIN(Sal)>(SELECT MIN(Sal) 5 FROM EMP 6 WHERE deptno=20 7 ); DEPTNO MIN(SAL) ---------- ---------10 1300 30 950 2 rows selected. SQL> SELECT job,AVG(Sal) 2 FROM EMP 3 GROUP BY job 4 HAVING AVG(Sal)=(SELECT MIN(AVG(Sal)) 5 FROM EMP 6 GROUP BY job 7 ); JOB AVG(SAL) --------- ---------CLERK 1037.5 1 row selected. SQL> SELECT job,AVG(Sal) 2 FROM EMP 3 GROUP BY job 4 HAVING AVG(Sal)<(SELECT MAX(AVG(Sal))

210

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

5 FROM EMP 6 GROUP BY job 7 ); JOB AVG(SAL) --------- ---------ANALYST 3000 CLERK 1037.5 MANAGER 2758.33333 SALESMAN 1400 4 rows selected. SQL> SELECT job,AVG(Sal),TO_CHAR(AVG(Sal),'L99,999.99') 2 FROM EMP 3 GROUP BY job 4 HAVING AVG(Sal)<(SELECT MAX(AVG(Sal))FROM EMP 5 GROUP BY deptno 6 ); JOB AVG(SAL) TO_CHAR(AVG(SAL),'L9 --------- ---------- -------------------CLERK 1037.5 $1,037.50 MANAGER 2758.33333 $2,758.33 SALESMAN 1400 $1,400.00 3 rows selected.

Sub Queries Returning More Than One Row The sub queries that return more than one row are called as multiple row sub queries. In this case a multiple row operator should be used. The multiple row operators expect one or more values as arguments. The multiple row operators are. IN -> Equal to any member in the list. ANY -> Compares value to each value returned by sub query. ALL -> Compares value to every value returned by the sub query.
SQL> SELECT ename,sal,deptno,job 2 FROM EMP 3 WHERE Sal IN(SELECT MIN(Sal) 4 FROM EMP 5 GROUP BY deptno); ENAME SAL DEPTNO ---------- ---------- ---------JAMES 950 30 SMITH 800 20 MILLER 1300 10 3 rows selected. SQL> SELECT ename,sal,deptno,job

211

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 3 4 5

FROM EMP WHERE Sal IN(SELECT MAX(Sal) FROM EMP GROUP BY deptno);

ENAME SAL DEPTNO ---------- ---------- ---------KING 5000 10 BLAKE 2850 30 FORD 3000 20 SCOTT 3000 20 4 rows selected. SQL> SELECT ename,sal,deptno,job 2 FROM EMP 3 WHERE Sal IN(SELECT MAX(Sal) 4 FROM EMP 5 GROUP BY job 6 ); ENAME SAL DEPTNO JOB ---------- ---------- ---------- --------KING 5000 10 PRESIDENT JONES 2975 20 MANAGER ALLEN 1600 30 SALESMAN FORD 3000 20 ANALYST SCOTT 3000 20 ANALYST MILLER 1300 10 CLERK 6 rows selected.

ANY Operator
SQL> SELECT EMPno,ename,job 2 FROM EMP 3 WHERE Sal<ANY(SELECT Sal 4 FROM EMP 5 WHERE job='CLERK' 6 ); EMPNO ENAME JOB ---------- ---------- --------7369 SMITH CLERK 7900 JAMES CLERK 7876 ADAMS CLERK 7654 MARTIN SALESMAN 7521 WARD SALESMAN 5 rows selected. SQL> SELECT EMPno,ename,job,sal 2 FROM EMP 3 WHERE Sal<ANY(SELECT Sal

212

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

4 5 6 7

FROM EMP WHERE deptno=20 AND job<>'CLERK' ); SAL 800 950 1100 1250 1250 1300 1500 1600 2450 2850 2975

EMPNO ENAME JOB ---------- ---------- --------- ---------7369 SMITH CLERK 7900 JAMES CLERK 7876 ADAMS CLERK 7654 MARTIN SALESMAN 7521 WARD SALESMAN 7934 MILLER CLERK 7844 TURNER SALESMAN 7499 ALLEN SALESMAN 7782 CLARK MANAGER 7698 BLAKE MANAGER 7566 JONES MANAGER 11 rows selected.

NOTE: <ANY means less than the maximum value in the list.
SQL> SELECT EMPno,ename,job 2 FROM EMP 3 WHERE Sal>ANY(SELECT Sal 4 FROM EMP 5 WHERE job='CLERK' 6 ); EMPNO ENAME JOB ---------- ---------- --------7839 KING PRESIDENT 7902 FORD ANALYST 7788 SCOTT ANALYST 7566 JONES MANAGER 7698 BLAKE MANAGER 7782 CLARK MANAGER 7499 ALLEN SALESMAN 7844 TURNER SALESMAN 7934 MILLER CLERK 7654 MARTIN SALESMAN 7521 WARD SALESMAN 7876 ADAMS CLERK 7900 JAMES CLERK 13 rows selected.

NOTE: >ANY means more than the maximum values in the list.
SQL> SELECT EMPno,ename,job 2 FROM EMP 3 WHERE Sal=ANY(SELECT Sal 4 FROM EMP

213

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

5 WHERE job='CLERK' 6 ); EMPNO ENAME JOB ---------- ---------- --------7900 JAMES CLERK 7369 SMITH CLERK 7876 ADAMS CLERK 7934 MILLER CLERK 4 rows selected.

NOTE: =ANY it is equivalent to IN operator. All Operator


SQL> SELECT EMPno,ename,job,sal 2 FROM EMP 3 WHERE Sal>ALL(SELECT AVG(Sal) 4 FROM EMP 5 GROUP BY deptno 6 ); EMPNO ENAME JOB ---------- ---------- --------- ---------7839 KING PRESIDENT 7566 JONES MANAGER 7902 FORD ANALYST 7788 SCOTT ANALYST 4 rows selected. SAL 5000 2975 3000 3000

NOTE: >ALL -> It means more than the maximum in the list.
SQL> SELECT EMPno,ename,job,sal 2 FROM EMP 3 WHERE Sal<ALL(SELECT AVG(Sal) 4 FROM EMP 5 GROUP BY deptno 6 ); EMPNO ENAME JOB ---------- ---------- --------- ---------7654 MARTIN SALESMAN 7844 TURNER SALESMAN 7900 JAMES CLERK 7521 WARD SALESMAN 7369 SMITH CLERK 7876 ADAMS CLERK 7934 MILLER CLERK 7 rows selected. SAL 1250 1500 950 1250 800 1100 1300

214

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

NOTE: <ALL -> It means less than the minimum in the list. Sub Queries Returning Multiple Columns. In sub queries multiple columns can be compared in the where clause, by writing a compound where clause using logical operators. Multiple column sub queries enable us to combine the duplicate where condition into a single where clause.

Syntax SQL>select Column1, column2, .. From TableName 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. In 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 is also called cross product, we can match the multiple where clause with multiple conditions. In not pair wise comparison, the candidate row must match the multiple conditions in the where clause but the values are compared individually. Pairwise Comparison OR Compound Where Clause Based Sub Query
SQL> SELECT ordid,prodid,qty 2 FROM item 3 WHERE(prodid,qty) IN(SELECT prodid,qty 4 FROM item 5 WHERE ordid=605 6 ) AND 7 ordid<>05; ORDID PRODID QTY ---------- ---------- ---------605 100861 100 617 100861 100 605 100870 500 617 100870 500 605 100890 5 605 101860 50 605 101863 100 605 102130 10 616 102130 10

215

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

9 rows selected.

Non Pairwise Comparison OR Component Where Clause Based Sub Query


SQL> SELECT ordid,prodid,qty 2 FROM item 3 WHERE prodid IN(SELECT prodid 4 FROM item 5 WHERE ordid=605 6 ) 7 AND 8 qty IN(SELECT qty 9 FROM item 10 WHERE ordid=605 11 ) 12 AND 13 ordid<>605; ORDID PRODID QTY ---------- ---------- ---------616 100861 10 621 100861 10 618 100861 50 617 100861 100 618 100870 10 616 100870 50 609 100870 5 617 100870 500 615 100870 100 621 100870 100 617 100890 500 617 101860 100 616 102130 10 620 102130 500 619 102130 100 617 102130 100 16 rows selected.

Handling NULL Values in Sub Quries: If one of the values returned by the inner query is NULL value, then the entire query returns no rows. All conditions that compare a null value result in a null. Whenever a null could be part of a sub query, it is better not be use not In operator as it is equivalent to !=ALL operator.
SQL> SELECT e.ename 2 FROM EMP e 3 WHERE e.EMPno IN(SELECT m.mgr 4 FROM EMP m 5 );

216

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ENAME ---------KING BLAKE JONES FORD SCOTT CLARK 6 rows selected.

Applying Sub Query in From Clause A sub query in the from clause is equivalent to a view. The sub query in the from clause defines a data source for the particular select statement and only that select statement.
SQL> SELECT e.ename,e.sal,e.deptno,e1.salAvg 2 FROM EMP e,(SELECT deptno,AVG(Sal) salAvg 3 FROM EMP 4 GROUP BY deptno) e1 5 WHERE e.deptno=e1.deptno AND e.sal>e1.salavg; ENAME SAL DEPTNO SALAVG ---------- ---------- ---------- ---------KING 5000 10 2916.66667 SCOTT 3000 20 2175 FORD 3000 20 2175 JONES 2975 20 2175 ALLEN 1600 30 1566.66667 BLAKE 2850 30 1566.66667 6 rows selected. SQL> SELECT t1.deptno,dname,staff 2 FROM dept t1,(SELECT deptno,COUNT(*) AS staff 3 FROM EMP 4 GROUP BY deptno 5 ) t2 6 WHERE t1.deptno=t2.deptno AND 7 staff>=5; DEPTNO DNAME STAFF ---------- -------------- ---------20 RESEARCH 5 30 SALES 6 2 rows selected. SQL> SELECT deptno,SUM(Sal), 2 SUM(Sal)/tot_sal*100 "salary%" 3 FROM EMP,(SELECT SUM(Sal) tot_sal 4 FROM EMP 5 )

217

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

6 GROUP BY deptno,tot_sal; DEPTNO SUM(SAL) salary% ---------- ---------- ---------10 8750 30.1464255 20 10875 37.4677003 30 9400 32.3858742 3 rows selected. SQL> Ed Wrote file afiedt.buf 1 SELECT e.EMPcount,d.deptcount 2 FROM (SELECT COUNT(*) EMPcount 3 FROM EMP 4 ) e, 5 (SELECT COUNT(*) deptcount 6 FROM dept 7* ) d SQL> / EMPCOUNT DEPTCOUNT ---------- ---------14 4 1 row selected. SQL> Ed Wrote file afiedt.buf 1 SELECT e.EMPcount,d.deptcount,s.gradecnt, 2 e.EMPcount+d.deptcount+s.gradecnt TotalRecCnt 3 FROM (SELECT COUNT(*) EMPcount 4 FROM EMP 5 ) e, 6 (SELECT COUNT(*) deptcount 7 FROM dept 8 ) d, 9 (SELECT COUNT(*) gradecnt 10 FROM salgrade 11* ) s SQL> / EMPCOUNT DEPTCOUNT GRADECNT TOTALRECCNT ---------- ---------- ---------- ----------14 4 5 23 1 row selected. SQL> SELECT a.deptno "Department Number", 2 (a.numEMP/b.totalcount)*100 "%Employees", 3 (a.salsum/b.totalsal)*100 "%salary" 4 FROM (SELECT deptno, 5 COUNT(*) numEMP,

218

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

6 SUM(Sal) salsum 7 FROM EMP 8 GROUP BY deptno 9 ) a, 10 (SELECT COUNT(*) totalcount, 11 SUM(Sal) totalsal 12 FROM EMP 13 )b; Department Number %Employees %salary ----------------- ---------- ---------10 21.4285714 30.1464255 20 35.7142857 37.4677003 30 42.8571429 32.3858742 3 rows selected.

Sub Select Statements These are select statements declared as part of the select list.
SQL> Ed Wrote file afiedt.buf 1 SELECT ename,sal, 2 (SELECT AVG(Sal) 3 FROM EMP 4 ) 5 "organization average" 6* FROM EMP SQL> / ENAME SAL organization average ---------- ---------- -------------------KING 5000 2073.21429 BLAKE 2850 2073.21429 CLARK 2450 2073.21429 JONES 2975 2073.21429 MARTIN 1250 2073.21429 ALLEN 1600 2073.21429 TURNER 1500 2073.21429 JAMES 950 2073.21429 WARD 1250 2073.21429 FORD 3000 2073.21429 SMITH 800 2073.21429 SCOTT 3000 2073.21429 ADAMS 1100 2073.21429 MILLER 1300 2073.21429 14 rows selected. SQL> SELECT ename,sal, 2 (SELECT MAX(Sal)

219

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 4 5 6 7 8 9

FROM EMP ) "organization maximum" ,(SELECT MIN(Sal) FROM EMP ) "organization minmum" FROM EMP;

ENAME SAL organization maximum organization minmum ---------- ---------- -------------------- ------------------KING 5000 5000 800 BLAKE 2850 5000 800 CLARK 2450 5000 800 JONES 2975 5000 800 MARTIN 1250 5000 800 ALLEN 1600 5000 800 TURNER 1500 5000 800 JAMES 950 5000 800 WARD 1250 5000 800 FORD 3000 5000 800 SMITH 800 5000 800 SCOTT 3000 5000 800 ADAMS 1100 5000 800 MILLER 1300 5000 800 14 rows selected.

Correlated Sub Queries It is another way of performing queries upon the data with a simulation of joins. In this the information from the outer select statement participates as a condition in the inner select statement. Syntax SQL>select selectList From Table1 f_alias1 Where expr.operator (select selectList From table2 f_alias2 Where f_alias1.column operator f_alis2.column ); Steps Performed First the outer query is executed. Passes the qualified column value to the inner queries where clause. Then the inner query or candidate query is executed, and the result is passed to the outer queries where clause. Depending on the supplied value the condition is qualified for the specific record. Successful presented else suppressed from display.
SQL> SELECT EMPno,ename,e.deptno,sal,mgr 2 FROM EMP e

220

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 4 5 6

WHERE e.sal>ANY(SELECT m.sal FROM EMP m WHERE m.EMPno=e.mgr ); MGR

EMPNO ENAME DEPTNO SAL ---------- ---------- ---------- ---------- ---------7788 SCOTT 20 3000 7566 7902 FORD 20 3000 7566 2 rows selected. SQL> Ed Wrote file afiedt.buf 1 SELECT deptno,dname 2 FROM dept d 3 WHERE EXISTS (SELECT * 4 FROM EMP e 5 WHERE d.deptno=e.deptno 6* ) SQL> / DEPTNO DNAME ---------- -------------10 ACCOUNTING 30 SALES 20 RESEARCH 3 rows selected. SQL> SELECT deptno,dname 2 FROM dept d 3 WHERE NOT EXISTS (SELECT * 4 FROM EMP e 5 WHERE d.deptno=e.deptno 6 ); DEPTNO DNAME ---------- -------------40 OPERATIONS 1 row selected. SQL> SELECT e.ename 2 FROM EMP e 3 WHERE EXISTS (SELECT * 4 FROM EMP e1 5 WHERE e1.EMPno=e.mgr 6 ); ENAME ---------BLAKE CLARK JONES MARTIN

221

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ALLEN TURNER JAMES WARD FORD SMITH SCOTT ADAMS MILLER 13 rows selected. SQL> SELECT e.ename 2 FROM EMP e 3 WHERE NOT EXISTS (SELECT * 4 FROM EMP e1 5 WHERE e1.EMPno=e.mgr 6 ); ENAME ---------KING 1 row selected. SQL> SELECT e.ename 2 FROM EMP e 3 WHERE EXISTS (SELECT * 4 FROM EMP e1 5 WHERE e1.mgr=e.EMPno 6 ); ENAME ---------KING BLAKE JONES FORD SCOTT CLARK 6 rows selected. SQL> SELECT e.ename 2 FROM EMP e 3 WHERE NOT EXISTS (SELECT * 4 FROM EMP e1 5 WHERE e1.mgr=e.EMPno 6 ); ENAME ---------TURNER WARD

222

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

MARTIN ALLEN MILLER SMITH ADAMS JAMES 8 rows selected.

223

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Hierarchical OR Recursive Queries

Hierarchical queries are queries that are executed upon tables that contain hierarchical data. To execute the hierarchical queries, we need the following clauses.

Start With It specifies the root rows of the hierarchy. Connect by It is used to specify the relationship between parent rows and child rows of the hierarchy. Where It is used to restrict the rows returned by the query without affecting other rows of the hierarchy. Steps Followed By Oracle Oracle selects the root row(s) of the hierarchy, which satisfy the condition of the start with clause. Then oracle selects the child rows of each root row. Each child row must satisfy the condition of the connect by clause, with respect to one of the root rows. Oracle selects successive generations of child rows by identifying the relation in the connect by clause. Oracle selects children by evaluating the connect by condition with respect to the current parent row selected. 224 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

If the query contains a where clause, oracle removes all rows from the hierarchy that do not satisfy the condition of the where clause.

General Representation

Root Node

Child

1 8 1

Leaf Nodes

Restrictions They cannot be used to perform joins. They cannot select data from a view, whose query performs a join. If order by clause is used, then the rows are returned as per the specification in the order by clause. To define hierarchical queries properly we must use the following clauses. Start with clause. Connect by clause. Start With Clause It identifies the row(s) to be used as the root(s) of a hierarchical query. If specifies a condition that the roots must specify. If start with is omitted, oracle uses all rows in the table as root rows. A start with condition can contain a sub query. Connect by Clause This clause specifies the relationship between parent and child rows, in a hierarchical query. This clause contains a condition that defines a relationship. This condition, some part of the condition must use the prior operator, which refers to the parent row. 225 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

The format of prior operators is Prior expr comparison operator expr. Expr comparison operator prior expr. The clause can contain other conditions to further filter the rows selected by the query. If cannot contain in a sub query.

General Structure of Hierarchical Tree Root / Level1

Child / parent

Child / Parent

Level 2

Child / Leaf

Child / Parent

Child / Parent

Level 3

Child / Leaf Child / Leaf Hierarchical Representation of EMP Table

Level 4

King (7839, NULL)

Jones Clark (7566, 7839)

Blake (7698, 7839) (7782, 7839)

Scott (7788, 7566) 7782)

Ford (7902, 7566)

Allen (7499, 7698) Ward (7521, 7698) Martin (7654, 7698) Miller (7934,

Adams 226

Smith Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

(7876, 7788)

(7369, 7902)

Turner (7844, 7698) James (7900, 7698)

SQL> SELECT ename,EMPno,mgr,job 2 FROM EMP 3 CONNECT BY PRIOR Empno=mgr; ENAME EMPNO MGR JOB ---------- ---------- ---------- --------FORD 7902 7566 ANALYST SMITH 7369 7902 CLERK SCOTT 7788 7566 ANALYST ADAMS 7876 7788 CLERK MARTIN 7654 7698 SALESMAN ALLEN 7499 7698 SALESMAN JAMES 7900 7698 CLERK WARD 7521 7698 SALESMAN TURNER 7844 7698 SALESMAN MILLER 7934 7782 CLERK ADAMS 7876 7788 CLERK BLAKE 7698 7839 MANAGER MARTIN 7654 7698 SALESMAN ALLEN 7499 7698 SALESMAN JAMES 7900 7698 CLERK WARD 7521 7698 SALESMAN TURNER 7844 7698 SALESMAN CLARK 7782 7839 MANAGER MILLER 7934 7782 CLERK JONES 7566 7839 MANAGER FORD 7902 7566 ANALYST SMITH 7369 7902 CLERK SCOTT 7788 7566 ANALYST ADAMS 7876 7788 CLERK SMITH 7369 7902 CLERK KING 7839 PRESIDENT BLAKE 7698 7839 MANAGER MARTIN 7654 7698 SALESMAN ALLEN 7499 7698 SALESMAN JAMES 7900 7698 CLERK WARD 7521 7698 SALESMAN TURNER 7844 7698 SALESMAN CLARK 7782 7839 MANAGER MILLER 7934 7782 CLERK JONES 7566 7839 MANAGER FORD 7902 7566 ANALYST SMITH 7369 7902 CLERK SCOTT 7788 7566 ANALYST ADAMS 7876 7788 CLERK 39 rows selected. SQL> SELECT ename,EMPno,mgr,job 2 FROM EMP

227

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 START WITH job='PRESIDENT' 4 CONNECT BY PRIOR Empno=mgr; ENAME EMPNO MGR JOB ---------- ---------- ---------- --------KING 7839 PRESIDENT BLAKE 7698 7839 MANAGER MARTIN 7654 7698 SALESMAN ALLEN 7499 7698 SALESMAN TURNER 7844 7698 SALESMAN JAMES 7900 7698 CLERK WARD 7521 7698 SALESMAN CLARK 7782 7839 MANAGER MILLER 7934 7782 CLERK JONES 7566 7839 MANAGER FORD 7902 7566 ANALYST SMITH 7369 7902 CLERK SCOTT 7788 7566 ANALYST ADAMS 7876 7788 CLERK 14 rows selected. SQL> SELECT ename,EMPno,mgr,job 2 FROM EMP 3 START WITH ename='KING' 4 CONNECT BY PRIOR Empno=mgr; ENAME EMPNO MGR JOB ---------- ---------- ---------- --------KING 7839 PRESIDENT BLAKE 7698 7839 MANAGER MARTIN 7654 7698 SALESMAN ALLEN 7499 7698 SALESMAN TURNER 7844 7698 SALESMAN JAMES 7900 7698 CLERK WARD 7521 7698 SALESMAN CLARK 7782 7839 MANAGER MILLER 7934 7782 CLERK JONES 7566 7839 MANAGER FORD 7902 7566 ANALYST SMITH 7369 7902 CLERK SCOTT 7788 7566 ANALYST ADAMS 7876 7788 CLERK 14 rows selected. SQL> SELECT ename,EMPno,mgr,job,sal 2 FROM EMP 3 START WITH Sal=5000 4 CONNECT BY PRIOR Empno=mgr; ENAME EMPNO MGR JOB ---------- ---------- ---------- --------- ---------KING 7839 PRESIDENT SAL 5000

228

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

BLAKE MARTIN ALLEN TURNER JAMES WARD CLARK MILLER JONES FORD SMITH SCOTT ADAMS

7698 7654 7499 7844 7900 7521 7782 7934 7566 7902 7369 7788 7876

7839 MANAGER 7698 SALESMAN 7698 SALESMAN 7698 SALESMAN 7698 CLERK 7698 SALESMAN 7839 MANAGER 7782 CLERK 7839 MANAGER 7566 ANALYST 7902 CLERK 7566 ANALYST 7788 CLERK

2850 1250 1600 1500 950 1250 2450 1300 2975 3000 800 3000 1100

14 rows selected. SQL> SELECT ename,EMPno,mgr,job,sal 2 FROM EMP 3 START WITH Sal=(SELECT MAX(Sal) 4 FROM EMP 5 ) 6 CONNECT BY PRIOR Empno=mgr; ENAME EMPNO MGR JOB SAL ---------- ---------- ---------- --------- ---------KING 7839 PRESIDENT 5000 BLAKE 7698 7839 MANAGER 2850 MARTIN 7654 7698 SALESMAN 1250 ALLEN 7499 7698 SALESMAN 1600 TURNER 7844 7698 SALESMAN 1500 JAMES 7900 7698 CLERK 950 WARD 7521 7698 SALESMAN 1250 CLARK 7782 7839 MANAGER 2450 MILLER 7934 7782 CLERK 1300 JONES 7566 7839 MANAGER 2975 FORD 7902 7566 ANALYST 3000 SMITH 7369 7902 CLERK 800 SCOTT 7788 7566 ANALYST 3000 ADAMS 7876 7788 CLERK 1100 14 rows selected. SQL> ED Wrote file afiedt.buf 1 2 3 4 5 6 7 8 9 SELECT ename,EMPno,mgr,job,sal FROM EMP START WITH Sal=(SELECT MAX(Sal) FROM EMP WHERE deptno=(SELECT deptno FROM dept WHERE dname='ACCOUNTING' ) )

229

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

10* CONNECT BY PRIOR Empno=mgr SQL> / ENAME EMPNO MGR JOB SAL ---------- ---------- ---------- --------- ---------KING 7839 PRESIDENT 5000 BLAKE 7698 7839 MANAGER 2850 MARTIN 7654 7698 SALESMAN 1250 ALLEN 7499 7698 SALESMAN 1600 TURNER 7844 7698 SALESMAN 1500 JAMES 7900 7698 CLERK 950 WARD 7521 7698 SALESMAN 1250 CLARK 7782 7839 MANAGER 2450 MILLER 7934 7782 CLERK 1300 JONES 7566 7839 MANAGER 2975 FORD 7902 7566 ANALYST 3000 SMITH 7369 7902 CLERK 800 SCOTT 7788 7566 ANALYST 3000 ADAMS 7876 7788 CLERK 1100 14 rows selected. SQL> SELECT ename,EMPno,mgr,job,sal 2 FROM EMP 3 START WITH ename='KING' 4 CONNECT BY PRIOR Empno=mgr 5 AND job='MANAGER'; ENAME EMPNO MGR JOB SAL ---------- ---------- ---------- --------- ---------KING 7839 PRESIDENT 5000 BLAKE 7698 7839 MANAGER 2850 CLARK 7782 7839 MANAGER 2450 JONES 7566 7839 MANAGER 2975 4 rows selected.

New Features in Hierarchical Queries Oracle 10g 1. New Operator . CONNECT_BY_ROOT 2. New Pseudo Columns .CONNECT_BY_ISCYCLE .CONNECT_BY_ISLEAF 3. New function .SYS_CONNECT_BY_PATH (oracle9i) 230 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

4. New Keywords .NOCYCLE .SIBLINGS (oracle9i) Connect By Root Operator Connect_by_root is a unary operator that is valid only in hierarchical queries. We should qualify a column with this operator, then oracle returns the column value using data from the root row. It extends the functionality of the connect by [prior] condition of hierarchical queries. Restriction We cannot specify this operator in the start with condition or the connect by condition.
SQL> Ed Wrote file afiedt.buf 1 SELECT ename Name, 2 CONNECT_BY_ROOT(ename) Boss 3 FROM EMP 4 START WITH Empno=7839 5* CONNECT BY PRIOR Empno=mgr SQL> / NAME BOSS ---------- ---------KING KING BLAKE KING MARTIN KING ALLEN KING TURNER KING JAMES KING WARD KING CLARK KING MILLER KING JONES KING FORD KING SMITH KING SCOTT KING ADAMS KING 14 rows selected.

SYS Connect By Path Function The function returns the path of a column value from root to node, with column values separated by char for each row returned by connect by condition. Can work on any datatype char, varchar2, nchar, or nvarchar2.
SQL> SELECT ename, 2 SYS_CONNECT_BY_PATH(ename,'/') "Path" 3 FROM EMP

231

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

4 START WITH ename='KING' 5 CONNECT BY PRIOR Empno=mgr; ENAME ---------Path ---------------------------------------------------------------KING /KING BLAKE /KING/BLAKE MARTIN /KING/BLAKE/MARTIN ALLEN /KING/BLAKE/ALLEN TURNER /KING/BLAKE/TURNER JAMES /KING/BLAKE/JAMES WARD /KING/BLAKE/WARD CLARK /KING/CLARK MILLER /KING/CLARK/MILLER JONES /KING/JONES FORD /KING/JONES/FORD SMITH /KING/JONES/FORD/SMITH SCOTT /KING/JONES/SCOTT ADAMS /KING/JONES/SCOTT/ADAMS

14 rows selected. NOCYCLE Keyword 232 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Cycles are not allowed in a true tree structure. But some hierarchical data may contain cycles. In a hierarchical structure, if a descendant is also an ancestor, it is called a cycle. To allow the start with.connect by.prior construct to work properly even if cycles are present in the data nocycle is used. The nocycle parameter in the connect by condition causes oracle to return the rows in spite of recursive loop.

14 rows selected. SQL> SELECT ename, 2 SYS_CONNECT_BY_PATH(Sal,'/') "Path" 3 FROM EMP 4 START WITH ename='KING' 5 CONNECT BY PRIOR Empno=mgr; ENAME ---------Path ----------------------------------------------------------KING /5000 BLAKE /5000/2850 MARTIN /5000/2850/1250 ALLEN /5000/2850/1600 TURNER /5000/2850/1500 JAMES /5000/2850/950 WARD /5000/2850/1250 CLARK /5000/2450 MILLER /5000/2450/1300 JONES /5000/2975 FORD /5000/2975/3000

233

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SMITH /5000/2975/3000/800 SCOTT /5000/2975/3000 ADAMS /5000/2975/3000/1100 14 rows selected.

SIBLINGS Keyword The keyword is valid only when we specify the hierarchical query using connect by clause. Order siblings by clause preserves any ordering specified in the hierarchical query clause. The order by clause finally gets applied on the query. Order siblings by clause is generally used when we want to order rows of siblings of the same parent.
SQL> SELECT ename,EMPno,mgr 2 FROM EMP 3 START WITH Empno=7839 4 CONNECT BY PRIOR Empno=mgr; ENAME EMPNO MGR ---------- ---------- ---------KING 7839 BLAKE 7698 7839 MARTIN 7654 7698 ALLEN 7499 7698 TURNER 7844 7698 JAMES 7900 7698 WARD 7521 7698 CLARK 7782 7839 MILLER 7934 7782 JONES 7566 7839 FORD 7902 7566 SMITH 7369 7902 SCOTT 7788 7566 ADAMS 7876 7788 14 rows selected. SQL> Ed Wrote file afiedt.buf 1 SELECT ename,EMPno,mgr 2 FROM EMP 3 START WITH Empno=7839 4 CONNECT BY PRIOR Empno=mgr 5* ORDER BY ename

234

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> / ENAME EMPNO MGR ---------- ---------- ---------ADAMS 7876 7788 ALLEN 7499 7698 BLAKE 7698 7839 CLARK 7782 7839 FORD 7902 7566 JAMES 7900 7698 JONES 7566 7839 KING 7839 MARTIN 7654 7698 MILLER 7934 7782 SCOTT 7788 7566 SMITH 7369 7902 TURNER 7844 7698 WARD 7521 7698 14 rows selected. SQL> SELECT ename,EMPno,mgr 2 FROM EMP 3 START WITH Empno=7839 4 CONNECT BY PRIOR Empno=mgr 5 ORDER SIBLINGS BY ename; ENAME EMPNO MGR ---------- ---------- ---------KING 7839 BLAKE 7698 7839 ALLEN 7499 7698 JAMES 7900 7698 MARTIN 7654 7698 TURNER 7844 7698 WARD 7521 7698 CLARK 7782 7839 MILLER 7934 7782 JONES 7566 7839 FORD 7902 7566 SMITH 7369 7902 SCOTT 7788 7566 ADAMS 7876 7788 14 rows selected.

235

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Taking the Advantage of Pseudo Columns in Oracle

Pseudo Column Pseudo columns behave like a table column, but is not actually stored in a table. Upon pseudo columns only select statements can be implemented, but insert, update or delete cannot be implemented. The available pseudo columns are.. Currval Nextval Level Rowed 236 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Rownum Currval and Nextval Pseudo Columns These pseudo columns are applied upon the sequence schema object. Currval returns the current value of a sequence. Nextval increments the sequence and returns the next value. The currval and nextval can be used only in. The select list of a select statement. The values clause of an insert statement. The set clause of an update statement. Restrictions The currval and nextval cannot be used in A sub query. A views query or snapshots query. A select with the distinct option. A select with a group by or order by clause. A select statement with union, intersect, minus set operators. The where clause of a select. The default option in create table or alter table statement. The condition of a check constraint. Syntax SEQUNCENAME.CURRVAL -> Returns the current value of the sequence. SWUENCENAME.NEXTVAL -> Increments the sequence value by the declared specification. Sequence Schema Object A sequence is a schema object that can generate unique sequential values. The sequence values are often used for primary keys and unique keys. To refer to the current or next value of a sequence in the schema of another user, the following privileges should be available. Select object privilege Select any sequence. For sequences in other schema the qualifying syntax is Schemaname.sequencename.currval Schemaname.sequencename.nextval To refer to the value of a sequence on a remote database, the sequence should be qualified with a complete or partial name of the database link. Schemaname.sequencename.currval@dblink Schemaname.sequencename.nextval@dblink In a single select statement, all referenced sequences, long columns, updated tables, and locked tables, must be located on the same database. When a sequence is created, we can define its initial value and the increment between it s values. The first reference to the nextval returns the sequences initial value. 237 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Before the currval can be used for a sequence in a session, first the sequence should be incremented with nextval. A sequence can be incremented only once in a single sql statement. A sequence can be accessed by many users concurrently with no waiting, no locking. Currval and nextval should be qualified with the name of the sequence.

Creating Sequence Purpose An object from which multiple users may generate unique integers. Can be used to generate primary key values automatically. Syntax CREATE SEQUENCE SequenceName INCREMENT BY Integer START WITH Integer MAXVAL Integer / NOMAXVALUE MINVAL Integer / NOMINVLUE CYCLE / NOCYCLE CACHE Integer / NOCACHE ORDER / NOORDER; Sequence can be either incremented sequence or decremented sequence Increment By Clause Specifies the interval between the sequence numbers. Value can be positive or negative, but cannot be 0. If the value is positive it is incremented sequence else it is decremented sequence. If omitted defaults to increment by 1. Minvalue Clause Specifies the sequences minimum value. Nominvalue Clause Specifies a minimum value of 1 for an ascending sequence or (10)26 for descending sequence. Maxvalue Clause Specifies the maximum value that can be generated. Nomaxvalue Clause Specifies a maximum value of 1027 for ascending sequence or -1 for descending sequence.

Cycle Clause Specifies the sequence will continue to generate values after reaching either maximum or minimum value. 238 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Nocycle Clause Specifies the sequence cannot generate more values after the targeted limit. Cache Clause Specifies the pre-allocation of sequence numbers, the minimum is 2. Nocache Clause Specifies the values of a sequence are not pre-allocated. Order Clause Guarantees the sequence numbers to be generated in the order of request. No Order Clause Does not guarantee the sequence number with order. Note If the above parameters are not specified by default. Start with will be 1. Increment by will be positive 1. Sequence is nocycle. The cache value will be 20. Sequence is order sequence. Illustrations
SQL> CREATE TABLE sample 2 ( 3 sampid NUMBER(4) 4 CONSTRAINT sampid_PK PRIMARY KEY, 5 sampname VARCHAR2(25), 6 sampdate DATE 7 ); Table created.

Creation of Incremental Sequence


SQL> CREATE SEQUENCE sampleseq 2 INCREMENT BY 1 3 START WITH 0 4 MINVALUE 0 5 MAXVALUE 5 6 NOCACHE 7 NOCYCLE; Sequence created.

Activating and Attaching the Sequence to a Table 239 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> INSERT INTO 2 sample(sampid,sampname,sampdate) 3 VALUES(sampleseq.NEXTVAL,'sample','31-aug-05'); 1 row created.

Creating a Sequence with Cycle


SQL> ED Wrote file afiedt.buf 1 CREATE SEQUENCE sampleseq1 2 INCREMENT BY 1 3 START WITH 0 4 MINVALUE 0 MAXVALUE 5 5 NOCACHE 6* CYCLE SQL> / Sequence created.

Creation of Decremental Sequence


SQL> Ed Wrote file afiedt.buf 1 CREATE SEQUENCE sampleseq2 2 INCREMENT BY -1 3 START WITH 5 4 MINVALUE 0 5 MAXVALUE 5 6 NOCACHE 7* NOCYCLE SQL> / Sequence created.

Modifying a Sequence The after command can be used to change the present status of a sequence. The alter sequence command can be used to change.. Increment value. Maximum value. Minimum value. Cycle option Cache option Syntax SQL> alter sequence sequenceName [increment by n] [{maxvalue n / nomaxvalue}] [{minvalue n / nominvalue}] [{cycle / nocycle}] 240 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

[{cache n / nocache}]; Illustration


SQL> ED Wrote file afiedt.buf 1 ALTER SEQUENCE sampleseq 2 MAXVALUE 10 3 CACHE 4* NOCYCLE SQL> / NOCYCLE * ERROR at line 4: ORA-01722: invalid number

Guidelines for Altering a Sequence The alter privilege should be available. Only the future sequence numbers are affected by the alter sequence statement. The start with option cannot be changed using alter sequence. To change the start with option, drip the sequence and then recreate the sequence. Some validation performed, i.e.., a New maxvalue cannot be imposed that is less than the current sequence number. Viewing the Current Value of a Sequence
SQL> SELECT sampleseq.CURRVAL 2 FROM DUAL; CURRVAL ---------0 1 row selected.

Dropping an Existing Sequence A sequence can be dropped at any time. Once removed, the sequence can no longer be referenced.
SQL> DROP SEQUENCE sampleseq1; Sequence dropped.

Confirming Sequences All sequences that have been created are documented in the data dictionary. The data dictionary in which the information of sequences are stored is user_objects. The settings of the sequence can be confirmed by selecting on user_sequences catlog.
SQL> SELECT SEQUENCE_NAME, 2 MIN_VALUE,MAX_VALUE,

241

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 INCREMENT_BY,LAST_NUMBER 4 FROM USER_SEQUENCES; SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY LAST_NUMBER ------------------------------ ---------- ---------- ------------ ----------SAMPLESEQ 0 5 1 1 SAMPLESEQ2 0 5 -1 5 2 rows selected.

Level Pseudo Column This pseudo column return 1 for root node, 2 for a child of a root and so on. Child -> Any non root node. Root -> Highest node within an inverted tree. Parent -> Any node / Row that has children. Leaf -> Any node without children. To establish the hierarchical relationship with level we need. START WITH Clause. CONNECT BY Clause.
SQL> SELECT ename,job,mgr,LEVEL 2 FROM EMP; FROM EMP * ERROR at line 2: ORA-01788: CONNECT BY clause required in this query block

SQL> SELECT LPAD('',2*(LEVEL-1)) Org_level,ename,EMPno,mgr,job 2 FROM EMP 3 START WITH job='PRESIDENT' 4 CONNECT BY PRIOR Empno=mgr; ORG_LEVEL --------------------------------------------------------------------------------------------------ENAME EMPNO MGR JOB

---------- ---------- ---------- --------KING 7839 PRESIDENT

242

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

BLAKE MARTIN ALLEN TURNER JAMES WARD CLARK MILLER JONES FORD SMITH SCOTT ADAMS

7698 7654 7499 7844 7900 7521 7782 7934 7566 7902 7369 7788 7876

7839 MANAGER 7698 SALESMAN 7698 SALESMAN 7698 SALESMAN 7698 CLERK 7698 SALESMAN 7839 MANAGER 7782 CLERK 7839 MANAGER 7566 ANALYST 7902 CLERK 7566 ANALYST 7788 CLERK

14 rows selected. SQL> SELECT 2 LPAD('',2*(LEVEL-1))||ename Org_char, 3 EMPno,mgr,job 4 FROM EMP 5 START WITH job='PRESIDENT' 6 CONNECT BY PRIOR Empno=mgr; ORG_CHAR --------------------------------------------------------------------------------------------------EMPNO MGR JOB

---------- ---------- --------KING 7839 BLAKE PRESIDENT

243

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7698 MARTIN 7654 ALLEN 7499 TURNER 7844 JAMES 7900 WARD 7521 CLARK 7782 MILLER 7934 JONES 7566

7839 MANAGER

7698 SALESMAN

7698 SALESMAN

7698 SALESMAN

7698 CLERK

7698 SALESMAN

7839 MANAGER

7782 CLERK

7839 MANAGER

FORD 7902 SMITH 7369 SCOTT 7788 ADAMS 7876 7788 CLERK 7566 ANALYST 7902 CLERK 7566 ANALYST

14 rows selected.

244

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT 2 LPAD('',2*(LEVEL-1))||ename Org_chart, 3 EMPno,mgr,job 4 ,Sal 5 FROM EMP 6 WHERE job!='ANALYST' 7 START WITH job='PRESIDENT' 8 CONNECT BY PRIOR Empno=mgr; ORG_CHART --------------------------------------------------------------------------------------------------EMPNO MGR JOB SAL

---------- ---------- --------- ---------KING 7839 BLAKE 7698 MARTIN 7654 ALLEN 7499 TURNER 7844 JAMES 7900 WARD 7521 CLARK 7698 SALESMAN 1250 7698 CLERK 950 7698 SALESMAN 1500 7698 SALESMAN 1600 7698 SALESMAN 1250 7839 MANAGER 2850 PRESIDENT 5000

245

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

7782 MILLER 7934 JONES 7566 SMITH 7369 ADAMS 7876

7839 MANAGER

2450

7782 CLERK

1300

7839 MANAGER

2975

7902 CLERK

800

7788 CLERK

1100

12 rows selected.

SQL> SELECT 2 LPAD('',2*(LEVEL-1))||ename Org_chart, 3 EMPno,mgr,job,sal 4 FROM EMP 5 START WITH job='PRESIDENT' 6 CONNECT BY PRIOR Empno=mgr AND LEVEL<=2; ORG_CHART --------------------------------------------------------------------------------------------------EMPNO MGR JOB SAL

---------- ---------- --------- ---------KING 7839 BLAKE 7698 CLARK 7782 7839 MANAGER 2450 7839 MANAGER 2850 PRESIDENT 5000

246

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

JONES 7566 7839 MANAGER 2975

4 rows selected.

Selection Nth Highest Value from Table Syntax Sql > select level, max(ColName) From TableName Where level=&levelno Connect by prior ColName > ColName Group by level; Illustration
SQL> ED Wrote file afiedt.buf 1 SELECT LEVEL, MAX(Sal) 2 FROM EMP 3 WHERE LEVEL=&LEVELNO 4 CONNECT BY PRIOR Sal>Sal 5* GROUP BY LEVEL SQL> / Enter value for levelno: 2 Old 3: WHERE LEVEL=&LEVELNO New 3: WHERE LEVEL=2 LEVEL MAX(SAL) ---------- ---------2 3000 1 row selected. SQL> / Enter value for levelno: 3 Old 3: WHERE LEVEL=&LEVELNO New 3: WHERE LEVEL=3 LEVEL MAX(SAL) ---------- ---------3 2975 1 row selected. SQL> / Enter value for levelno: 1 Old 3: WHERE LEVEL=&LEVELNO New 3: WHERE LEVEL=1

247

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

LEVEL MAX(SAL) ---------- ---------1 5000 1 row selected. SQL> / Enter value for levelno: 4 Old 3: WHERE LEVEL=&LEVELNO New 3: WHERE LEVEL=4 LEVEL MAX(SAL) ---------- ---------4 2850 1 row selected. SQL> / Enter value for levelno: 5 Old 3: WHERE LEVEL=&LEVELNO New 3: WHERE LEVEL=5 LEVEL MAX(SAL) ---------- ---------5 2450 1 row selected. SQL> / Enter value for levelno: 6 Old 3: WHERE LEVEL=&LEVELNO New 3: WHERE LEVEL=6 LEVEL MAX(SAL) ---------- ---------6 1600 1 row selected.

Selecting Nth Lowest Value From Table Syntax SQL> select level, min(ColName) From TableName Where level=&levelno Connect by prior colname<colname Group by level; Illustration
SQL> Ed Wrote file afiedt.buf 1 SELECT LEVEL, MIN(Sal)

248

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 FROM EMP 3 WHERE LEVEL=&LEVELNO 4 CONNECT BY PRIOR Sal<Sal 5* GROUP BY LEVEL SQL> / Enter value for levelno: 5 Old 3: WHERE LEVEL=&LEVELNO New 3: WHERE LEVEL=5 LEVEL MIN(SAL) ---------- ---------5 1300 1 row selected. SQL> / Enter value for levelno: 3 Old 3: WHERE LEVEL=&LEVELNO New 3: WHERE LEVEL=3 LEVEL MIN(SAL) ---------- ---------3 1100 1 row selected. SQL> / Enter value for levelno: 4 Old 3: WHERE LEVEL=&LEVELNO New 3: WHERE LEVEL=4 LEVEL MIN(SAL) ---------- ---------4 1250 1 row selected. SQL> / Enter value for levelno: 2 Old 3: WHERE LEVEL=&LEVELNO New 3: WHERE LEVEL=2 LEVEL MIN(SAL) ---------- ---------2 950 1 row selected. SQL> / Enter value for levelno: 1 Old 3: WHERE LEVEL=&LEVELNO New 3: WHERE LEVEL=1 LEVEL MIN(SAL)

249

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

---------- ---------1 800 1 row selected.

ROWNUM Pseudo Column For each row returned by a query, the rownum pseudo column returns a number indicating the order in which oracle selects the rows from a set of joined rows or non joined rows. The first row selected has a rownum of 1, the second has 2, and so on. The rownum can be used to limit the number of rows returned by the query. When order by clause follows a rownum, the rows will be re-ordered by order by clause. If order by clause is embedded in a sub query and rownum condition is placed in the toplevel query, then the rownum condition can be forced to get applied after the ordering of the rows. Conditions testing for rownum values greater than a positive integer are always false.
SQL> SELECT LPAD('',ROWNUM,'*') 2 FROM EMP; LPAD('',ROWNUM,'*') ------------------------------------------------------

14 rows selected. SQL> SELECT ROWNUM,ename,sal 2 FROM EMP; ROWNUM ENAME SAL ---------- ---------- ---------1 KING 5000 2 BLAKE 2850 3 CLARK 2450 4 JONES 2975 5 MARTIN 1250 6 ALLEN 1600 7 TURNER 1500 8 JAMES 950 9 WARD 1250 10 FORD 3000 11 SMITH 800 12 SCOTT 3000 13 ADAMS 1100 14 MILLER 1300

250

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

14 rows selected.

Querying for Top N Records We can ask for Nth largest or smallest values of a column. Never use rownum and order by clause together as oracle first fetches the rows according to rownum and then sorts the found rows. From oracle 8i, order by clause can be used in inline views.
SQL> SELECT ROWNUM,ename,sal 2 FROM EMP 3 WHERE ROWNUM<6 4 ORDER BY Sal DESC; - - - Wrong Way ROWNUM ENAME SAL ---------- ---------- ---------1 KING 5000 4 JONES 2975 2 BLAKE 2850 3 CLARK 2450 5 MARTIN 1250 5 rows selected. SQL> SELECT * 2 FROM (SELECT * 3 FROM EMP 4 ORDER BY Sal DESC 5 ) 6 WHERE ROWNUM<6; - - - Proper Way EMPNO ENAME JOB MGR HIREDATE ---------- ---------- ------------------ --------7839 KING PRESIDENT 17-NOV-81 7902 FORD ANALYST 7566 03-DEC-81 7788 SCOTT ANALYST 7566 09-DEC-82 7566 JONES MANAGER 7839 02-APR-81 7698 BLAKE MANAGER 7839 01-MAY-81 5 rows selected. SAL ---------5000 3000 3000 2975 2850 COMM DEPTNO ---------- ---------10 20 20 20 30

ROWID Pseudo Column This pseudo column returns a rows address for each row stored in the database. ROWID values contain information necessary to locate a the physics area of the database row. The row belongs to which data block in the data file. The row belongs to which row in the data block (first row is 0) The row belongs to which data file (first file is 1) The rows in different tables that are stored together in the same cluster can have the same ROWID. 251 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

The data type of the values belonging to the ROWID are of ROWID data type.

Uses of ROWID Values ROWID is the fastest means of accessing a single row from database. ROWID can show how a tables rows are physically stored. ROWIDs are unique identifiers for a row in a table. A ROWID never change during the life time of its row. ROWIDs should not be assigned as primary keys as there is a chance of ROWID to change when the database is exported or imported. When row is deleted, oracle may reassign its ROWID to a New row that is inserted. The ROWID can never be inserted, updated and deleted manually. The ROWID pseudo column can be used in select and where clauses.
SQL> SELECT ROWID,ename,job 2 FROM EMP 3 WHERE Empno=20; no rows selected SQL> SELECT ename,sal,job 2 FROM EMP 3 WHERE ROWID<'AACQQAACAAAAAEHAAA'; ENAME SAL JOB ---------- ---------- --------KING 5000 PRESIDENT BLAKE 2850 MANAGER CLARK 2450 MANAGER JONES 2975 MANAGER MARTIN 1250 SALESMAN ALLEN 1600 SALESMAN TURNER 1500 SALESMAN JAMES 950 CLERK WARD 1250 SALESMAN FORD 3000 ANALYST SMITH 800 CLERK SCOTT 3000 ANALYST ADAMS 1100 CLERK MILLER 1300 CLERK 14 rows selected. SQL> SELECT ename,sal,job 2 FROM EMP 3 WHERE ROWID='AACQQAACAAAAAEHAAA'; FROM EMP *

252

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ERROR at line 2: ORA-01410: invalid ROWID SQL> SELECT b.sal,SUM(a.sal) "Cum Sal" 2 FROM EMP e,EMP b 3 WHERE a. ROWID<=b.ROWID 4 GROUP BY b.ROWID,b.sal; SAL Cum Sal ---------- ---------5000 5000 2850 7850 2450 10300 2975 13275 1250 14525 1600 16125 1500 17625 950 18575 1250 19825 3000 22825 800 23625 3000 26625 1100 27725 1300 29025 14 rows selected. SQL> Ed Wrote file afiedt.buf 1 SELECT b.ename,b.job,b.sal,SUM(a.sal) "Cum Sal" 2 FROM EMP a,EMP b 3 WHERE a. ROWID<=b.ROWID 4* GROUP BY b.ROWID,b.sal,b.ename,b.job SQL> / ENAME JOB SAL Cum Sal ---------- --------- ---------- ---------KING PRESIDENT 5000 5000 BLAKE MANAGER 2850 7850 CLARK MANAGER 2450 10300 JONES MANAGER 2975 13275 MARTIN SALESMAN 1250 14525 ALLEN SALESMAN 1600 16125 TURNER SALESMAN 1500 17625 JAMES CLERK 950 18575 WARD SALESMAN 1250 19825 FORD ANALYST 3000 22825 SMITH CLERK 800 23625 SCOTT ANALYST 3000 26625 ADAMS CLERK 1100 27725 MILLER CLERK 1300 29025

253

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

14 rows selected.

New Pseudo Columns(Oracle 10g) CONNECT_BY_ISCYCLE CONNECT_BY_ISLEAF CONNECT BY ISCYCLE Pseudo Column The CONNECT_BY_ISCYCLE Pseudo column returns 1 if the current row has a child which is also its ancestor otherwise it returns 0. We can specify CONNECT_BY_ISCYCLE only if we have specified the NOCYCLE parameter of the connect by clause. NOCYCLE Enables oracle to return the results of a query that would otherwise fail because of a connect by loop in the data.
SQL> SELECT ename, 2 CONNECT_BY_ISCYCLE "Cycle", 3 LEVEL, 4 SYS_CONNECT_BY_PATH(Sal,'/') SalPath 5 FROM EMP 6 START WITH ename='KING' 7 CONNECT BY NOCYCLE 8 PRIOR Empno=mgr; ENAME Cycle LEVEL ---------- ---------- ---------SALPATH -----------------------------------------------------------KING 0 1 /5000 BLAKE /5000/2850 0 2 3 3 3 3 3

MARTIN 0 /5000/2850/1250 ALLEN 0 /5000/2850/1600 TURNER 0 /5000/2850/1500 JAMES 0 /5000/2850/950 WARD 0 /5000/2850/1250

254

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

CLARK /5000/2450

2 3 2 3 4 3 4

MILLER 0 /5000/2450/1300 JONES /5000/2975 0

FORD 0 /5000/2975/3000 SMITH 0 /5000/2975/3000/800 SCOTT 0 /5000/2975/3000 ADAMS 0 /5000/2975/3000/1100 14 rows selected.

CONNECT_BY_ISLEAF Pseudo Column The CONNECT_BY_ISLEAF Pseudo column returns 1, if the current row is a leaf of the tree defined by the connect by condition, else it returns 0. This information indicates whether a given row can be further expanded to show more of the hierarchy.
SQL> Ed Wrote file afiedt.buf 1 SELECT ename "Employees", 2 CONNECT_BY_ISLEAF "IsLeaf", 3 SYS_CONNECT_BY_PATH(ename,'/') Path 4 FROM EMP 5 START WITH Empno=7839 6* CONNECT BY PRIOR Empno=mgr

SQL> / Employees IsLeaf ---------- ---------PATH ----------------------------------------------------------KING 0 /KING BLAKE /KING/BLAKE 0

255

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

MARTIN 1 /KING/BLAKE/MARTIN ALLEN 1 /KING/BLAKE/ALLEN TURNER 1 /KING/BLAKE/TURNER JAMES 1 /KING/BLAKE/JAMES WARD 1 /KING/BLAKE/WARD CLARK /KING/CLARK 0

MILLER 1 /KING/CLARK/MILLER JONES /KING/JONES 0

FORD 0 /KING/JONES/FORD SMITH 1 /KING/JONES/FORD/SMITH SCOTT 0 /KING/JONES/SCOTT ADAMS 1 /KING/JONES/SCOTT/ADAMS 14 rows selected.

256

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Working with Set Operators


257 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Set Operators These operators are used to combine information of similar data type from one or more than one table. Data type of the corresponding column in all the select statements should be same. The different types of set operators are Union operator. Union all operator. Intersect operator. Minus operator. Set operators can combine two or more queries into one result. The result of each select statement can be treated as a set, and sql set operations can be applied on those sets to arrive at a final result. Sql statements containing set operators are referred to as compound queries, and each select statement in a compound query is referred to as a component query. Set operations are often called vertical joins, as the result combines data from two or more selects based on columns instead of rows. The Generic Syntax <component query> {union | union all | minus | intersect } <component query>; Union Combines the results of two select statements into one result set, and then eliminates any duplicate rows that result set. Union All Combines the results of two select statements into one result set including the duplicates. Intersect Returns only those rows that are returned by each of two select statements. Minus Takes the result set of one select statement, and removes those rows that are also returned by a second select statement. Point of Concentration The queries are all executed independently but their output is merged. 258 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Only final query ends with a semicolon. Rules and Restrictions The result sets of both the queries must have the same number of columns. The data type of each column in the second result set must match the data type of its corresponding column in the first result set. The two select statements may not contain an order by clause, the final result of the entire set operation can be ordered. The columns used for ordering must be defined through the column numbers.

Illustrations
SQL> SELECT EMPno,ename 2 FROM EMP 3 WHERE deptno=10 4 UNION 5 SELECT EMPno,ename 6 FROM EMP 7 WHERE deptno=30 8 ORDER BY 1; EMPNO ENAME ---------- ---------7499 ALLEN 7521 WARD 7654 MARTIN 7698 BLAKE 7782 CLARK 7839 KING 7844 TURNER 7900 JAMES 7934 MILLER 9 rows selected. SQL> SELECT EMPno,ename,job 2 FROM EMP 3 WHERE deptno=(SELECT deptno 4 FROM dept 5 WHERE dname='SALES') 6 UNION 7 SELECT EMPno,ename,job 8 FROM EMP 9 WHERE deptno=(SELECT deptno 10 FROM dept 11 WHERE dname='ACCOUNTING') 12 ORDER BY 1;

259

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

EMPNO ENAME JOB ---------- ---------- --------7499 ALLEN SALESMAN 7521 WARD SALESMAN 7654 MARTIN SALESMAN 7698 BLAKE MANAGER 7782 CLARK MANAGER 7839 KING PRESIDENT 7844 TURNER SALESMAN 7900 JAMES CLERK 7934 MILLER CLERK 9 rows selected. SQL> SELECT EMPno,ename 2 FROM EMP 3 WHERE deptno=10 4 UNION ALL 5 SELECT EMPno,ename 6 FROM EMP 7 WHERE deptno=30 8 ORDER BY 1; EMPNO ENAME ---------- ---------7499 ALLEN 7521 WARD 7654 MARTIN 7698 BLAKE 7782 CLARK 7839 KING 7844 TURNER 7900 JAMES 7934 MILLER 9 rows selected. SQL> SELECT EMPno,ename 2 FROM EMP 3 WHERE deptno=10 4 INTERSECT 5 SELECT EMPno,ename 6 FROM EMP 7 WHERE deptno=30 8 ORDER BY 1; no rows selected SQL> SELECT EMPno,ename 2 FROM EMP 3 WHERE deptno=10 4 MINUS 5 SELECT EMPno,ename

260

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

6 FROM EMP 7 WHERE deptno=30 8 ORDER BY 1; EMPNO ENAME ---------- ---------7782 CLARK 7839 KING 7934 MILLER 3 rows selected. SQL> SELECT job 2 FROM EMP 3 WHERE deptno=20 4 UNION 5 SELECT job 6 FROM 7 EMP 8 WHERE deptno=30; JOB --------ANALYST CLERK MANAGER SALESMAN 4 rows selected. SQL> SELECT job 2 FROM EMP 3 WHERE deptno=20 4 UNION ALL 5 SELECT job 6 FROM 7 EMP 8 WHERE deptno=30; JOB --------MANAGER ANALYST CLERK ANALYST CLERK MANAGER SALESMAN SALESMAN SALESMAN CLERK SALESMAN 11 rows selected.

261

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT job 2 FROM EMP 3 WHERE deptno=20 4 INTERSECT 5 SELECT job 6 FROM EMP 7 WHERE deptno=30; JOB --------CLERK MANAGER 2 rows selected. SQL> SELECT job 2 FROM EMP 3 WHERE deptno=20 4 MINUS 5 SELECT job 6 FROM EMP 7 WHERE deptno=10; JOB --------ANALYST 1 row selected. SQL> SELECT ROWNUM,ename 2 FROM EMP 3 WHERE ROWNUM<7 4 MINUS 5 SELECT ROWNUM,ename 6 FROM EMP 7 WHERE ROWNUM<6; ROWNUM ENAME ---------- ---------6 ALLEN 1 row selected.

262

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Working with Views in Oracle


263 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

View

It is a logical table based on one or more tables or views. A view in practicality contains no data by itself. The tables upon with a view is based are called as base tables. Views can be created as object views or relational views. The object views support Lobs Object Types Refs Nested Tables Varrys Object view is a view of a user defined type, where each row contains objects, and each object identifier.

Prerequisites Should have create view or create any view system privilege. To create a subview, we need under any view system privilege or under, object privilege on the superview. The owner of the schema should have select, insert, update or delete rows from all tables or view is based. The above privileges must be granted through privileges directly, rather than a role. Syntax SQL>create [or replace] [{force / noforce}] view viewname [(aliasname[,alisname.])] As subquery [with{check option / read only}] [constraint constraintName]; 264 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Or Replace Specifies the view has to be replaced if already existing. Force Specifies the view has to be created even if the base tables rows not exist. NOFORCE Specifies the view should not be created if the base tables does not exist, which is default. Alias Name Specifies the name of an alias for an expression in the subquery. With Check Option Specifies that only rows that would be retrieved by the subquery can only be inserted, updated or deleted. Constraint Constraint_name specifies the name of the constraint as with check option or read only constraint. With Read Only Specifies that row must only be read from the base tables. Restrictions If a view has inserted of trigger, then all sub views created on it must have instead of triggers, even if the views are inherently updatable. An alias cannot be specified when creating an object view. Types of Views Simple views Complex views Simple Views Which contains a subquery that retrieves data from only one base table? Complex views Contains a subquery that can perform any of these actions. Retrieving from multiple base tables. Groups rows using a group by or distinct clause. Contains a function call. Simple Views
SQL> Ed Wrote file afiedt.buf 1 CREATE VIEW Employees 2 AS 3 SELECT 4 Empno "id number", 5 ename Name, 6 Sal "Basic Salary", 7 job Designation 8* FROM EMP SQL> / View created.

265

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Selecting Data from A View


SQL> SELECT name, designation 2 FROM Employees; NAME DESIGNATI ---------- --------KING PRESIDENT BLAKE MANAGER CLARK MANAGER JONES MANAGER MARTIN SALESMAN ALLEN SALESMAN TURNER SALESMAN JAMES CLERK WARD SALESMAN FORD ANALYST SMITH CLERK SCOTT ANALYST ADAMS CLERK MILLER CLERK 14 rows selected.

SQL> Ed Wrote file afiedt.buf 1 SELECT "id number",name,"Basic Salary"*12 2 FROM Employees 3* WHERE "Basic Salary">2500 SQL> / id number NAME "BASICSALARY"*12 ---------- ---------- ---------------7839 KING 60000 7698 BLAKE 34200 7566 JONES 35700 7902 FORD 36000 7788 SCOTT 36000 5 rows selected. SQL> Ed Wrote file afiedt.buf 1 2 3 4 5 SELECT "id number", name, TO_CHAR("Basic Salary",'99,99,999.99') Monthly, "Basic Salary"*12 Annual

266

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

6 FROM Employees 7* WHERE "Basic Salary">2500 SQL> / id number NAME MONTHLY ---------- ---------- ------------- ---------7839 KING 5,000.00 7698 BLAKE 2,850.00 7566 JONES 2,975.00 7902 FORD 3,000.00 7788 SCOTT 3,000.00 5 rows selected. ANNUAL 60000 34200 35700 36000 36000

Complex Views
SQL> CREATE VIEW EMPInfo 2 AS 3 SELECT 4 e.EMPno EMPloyeeid, 5 e.ename name, 6 d.deptno departmentid, 7 d.dname departmentname 8 FROM EMP e,dept d 9 WHERE d.deptno=e.deptno 10 ORDER BY d.deptno; View created. SQL> CREATE VIEW EMPgrades 2 AS 3 SELECT e.ename name, 4 e.sal basic,s.grade grade 5 FROM EMP e,salgrade s 6 WHERE e.sal BETWEEN s.losal AND s.hisal 7 ORDER BY s.grade; View created. SQL> CREATE OR REPLACE VIEW EMPmanagers 2 AS 3 SELECT ROWNUM SerialNo, 4 INITCAP(e.ename)||' Works Undr '|| 5 m.ename "Employees and managers" 6 FROM EMP e,EMP m 7 WHERE e.mgr=m.EMPno; View created. SQL> CREATE OR REPLACE VIEW EMPaccounts 2 AS 3 SELECT 4 ename, 5 deptno,

267

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

6 Sal Monthly, 7 Sal*12 Annual 8 FROM EMP 9 WHERE deptno=(SELECT deptno 10 FROM dept 11 WHERE dname='ACCOUNTING' 12 ) 13 ORDER BY Annual; View created. SQL> CREATE OR REPLACE VIEW cumsum 2 AS 3 SELECT b.sal,SUM(a.sal) Cum_Sal 4 FROM EMP a,EMP b 5 WHERE a. ROWID<=b.ROWID 6 GROUP BY b.ROWID,b.sal; View created. SQL> ED Wrote file afiedt.buf 1 CREATE OR REPLACE VIEW orgdesignations 2 AS 3 SELECT job 4 FROM EMP 5 WHERE deptno=10 6 UNION 7 SELECT job 8 FROM EMP 9* WHERE deptno IN(20,30) SQL> / View created.

Data Access Using Views The steps or operations performed by the oracle server, when data is accessed using a view are Retrieves the view definition from the data dictionary table USER_VIEWS. Checks the access privileges for the views base table. Converts the view query into an equivalent operation on the underlying base table or tables. Views 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.
SQL> SELECT VIEW_NAME,TEXT 2 FROM USER_VIEWS; VIEW_NAME TEXT ------------------------------ --------------------------------------------EMPINFO SELECT e.EMPno EMPloyeeid, e.ename name,

268

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

d.deptno departmentid, d.dname departm EMPLOYEES SELECT Empno "id number", ename Name, Sal "Basic Salary", job Designation FROM SELECT e.ename name, e.sal basic,s.grade grade FROM EMP e,salgrade s WHERE e.sal SELECT ROWNUM SerialNo, INITCAP(e.ename)||' Works Undr '|| m.ename "Employees and SELECT ename, deptno, Sal Monthly, Sal*12 Annual FROM EMP WHERE deptno=(SELECT d SELECT b.sal,SUM(a.sal) Cum_Sal FROM EMP a,EMP b WHERE a. ROWID<=b.ROWID GROUP BY

EMPGRADES

EMPMANAGERS

EMPACCOUNTS

CUMSUM

ORGDESIGNATIONS SELECT job FROM EMP WHERE deptno=10 UNION SELECT job FROM EMP WHERE deptno IN(20 7 rows selected.

Modifying A View Or replace option is used to modify an existing view with a New definition. A view can be altered without dropping, recreating, and regranting object privileges. The assigned column aliases in the create view clause, are listed in the same order as the columns in the sub query. Creating Views with Columns Declarations When a view is being created, we can specify the names of the columns that it can project, along with the views definition. The view in this case totally hides the original names from the base table. 269 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> Ed Wrote file afiedt.buf 1 CREATE VIEW 2 deptsalsummary( 3 departmentname, 4 minimumsalary, 5 maxsalary, 6 averagesalary, 7 salarysum 8 ) 9 AS 10 SELECT 11 d.dname, 12 MIN(e.sal), 13 MAX(e.sal), 14 AVG(e.sal), 15 SUM(e.sal) 16 FROM EMP e,dept d 17 WHERE e.deptno=d.deptno 18* GROUP BY d.dname SQL> / View created.

Using Views to Create on the Fly Tables


SQL> CREATE VIEW insertdept10 2 AS 3 SELECT* 4 FROM EMP 5 WHERE deptno=10; View created.

Creating a Table with Data Using a View


SQL> CREATE TABLE dept10 2 AS 3 SELECT* 4 FROM insertdept10; Table created. SQL> CREATE VIEW EMPgradeins 2 AS 3 SELECT ename,job,sal,and grade 4 FROM EMP e,salgrade s 5 WHERE e.sal BETWEEN s.losal AND s.hisal; View created. SQL> Ed

270

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Wrote file afiedt.buf 1 CREATE TABLE EMPgrades1 2 ( 3 Employees, 4 designation, 5 basicsalary, 6 grade 7 ) 8 AS 9 SELECT* 10* FROM EMPgradeins SQL> / Table created.

Dropping A View 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 privilege to remove the views from data dictionary. Syntax SQL>drop view viewname; Example
SQL> DROP VIEW EMPgradeins; View dropped.

Inline Views An inline view is a sub query with an alias (called as correlation name ), that can be used within a sql statement. An inline view is similar to using a named subquery in the from clause of the main query. An inline view is not a schema object. An inline view in the from clause of a select statement defines a data source for the select statement.
SQL> SELECT e1.ename,e1.sal,e1.deptno,e2.maxsal 2 FROM EMP e1,(SELECT deptno,MAX(Sal) Maxsal 3 FROM EMP 4 GROUP BY deptno 5 ) e2 6 WHERE 7 e1.deptno=e2.deptno AND 8 e1.sal<e2.Maxsal; ENAME SAL DEPTNO MAXSAL ---------- ---------- ---------- ---------MILLER 1300 10 5000

271

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

CLARK ADAMS SMITH JONES WARD JAMES TURNER ALLEN MARTIN

2450 1100 800 2975 1250 950 1500 1600 1250

10 20 20 20 30 30 30 30 30

5000 3000 3000 3000 2850 2850 2850 2850 2850

10 rows selected.

Performing DML Operations On A View: DML operators can be perfumed upon a table through View. Rules To Follow A row can be removed from a view unless it contains. Group function. A group by clause. The ROWNUM PSEUDO COLUMN. The distinct key word. The columns defined by expressions. Data can be added through a view, unless it contains any of the above rules and there does not exist not null columns, and without default value. SQL> CREATE VIEW 2 insertdept(deptid, 3 deptname, 4 place 5 ) 6 AS 7 SELECT 8 deptno, 9 dname, 10 loc 11 FROM dept; View created. Inserting Data Into Dept Table Using the Insertdept View
SQL> INSERT INTO 2 insertdept(deptid,deptname,place) 3 VALUES(50,'ADMINISTRATION','DELHI'); 1 row created.

Updating Data in Dept Table Using the Insertdept View


SQL> UPDATE insertdept 2 SET PLACE='MUMBAI' 3 WHERE deptid=50;

272

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row updated.

Deleting Data from Dept Table Using the Insertdept View


SQL> DELETE 2 FROM insertdept 3 WHERE deptid=50; 1 row deleted.

Many times these transactions look consistent but it is not true, hence care should be taken when implementing them.

Using with Check Option Clause To ensure that DML on the view stays within the domain of the view we use the with check option clause. Views make it possible to perform referential integrity checks. Using views can enforce constraints at database level. Using views we protect the data integrity, but the use is very limited. The with check option clause specifies that inserts, & updates performed through the view are not allowed to create rows, that the view cannot select. Views allow integrity constraints and data validation checks to be enforced on data being inserted or updated.
SQL> CREATE OR REPLACE VIEW edept30 2 AS 3 SELECT* 4 FROM EMP 5 WHERE deptno=30 6 WITH CHECK OPTION CONSTRAINT edept30chkview; View created. SQL> CREATE OR REPLACE VIEW emanage 2 AS 3 SELECT* 4 FROM EMP 5 WHERE job='MANAGER' 6 WITH CHECK OPTION CONSTRAINT emanagerview; View created.

Applying with Read Only Option By adding the with read only option we can ensure that no DML operations are executed through view. An attempt to perform a DML operation results in oracle server error.
SQL> Ed Wrote file afiedt.buf 1 CREATE OR REPLACE VIEW 2 edptread( 3 EMPid,

273

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

4 name, 5 designation 6 ) 7 AS 8 SELECT EMPno,ename,job 9 FROM EMP 10 WHERE deptno=20 11* WITH READ ONLY SQL> / View created.

Understanding Constraint State As part of constraint definition, we can specify how and when oracle should enforce the constraint. Constraint state We can use the CONSTRAINT_STATE with both INLINE and OUT-OF-LINE specification. We can specify the clauses of CONSTRAINT_STATE in any order, but we can specify each clause only once. Constraint Clauses Deferrable and Not Deferrable Clauses The deferrable and not deferrable parameters indicate whether or not, in subsequent transactions, constraint checking can be deferred until the end of the transaction. The constraint state can be changed using the set constraint(s) statement. If we omit this clause while creating the table, then the default is not deferrable. We specify not deferrable to indicate that in subsequent transactions we can use the set constraint(s) clause to defer checking of the constraint until after the transaction is committed. The deferrable setting in effect lets us disable the constraint temporarily while making changes to the database that might violate the constraint until all the changes are complete. Restriction on [NOT] Deferrable We cannot specify either of the above clauses for a view constraint. INITIALLY Clause The INITIAL clause establishes the default checking behavior for constraints that are deferrable. The INITIAL setting can be overridden by a set constraint(s) statement in a subsequent transaction. Specify initially immediate to indicate that oracle should check the constraint at the end of each subsequent sql statement. If we do not specify INITIALLY at all, then the default is INITIALLY IMMEDIATE. Specify INITIALLY DEFFRRED to indicate that oracle should check this constraint at the end of subsequent transactions. Validate or Novalidate The behavior of validate and novalidate always depends on whether the constraint is enabled or disabled. Enable Clause 274 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Specify enable if we want the constraint to be applied to the data in the table. Enable validate specifies that all Old and New data also complies with the constraint. Enable NOVALIDATE ensure that all New DML operations on the constrained data comply with the constraint. Restriction on the Enable Clause We cannot enable a foreign that references a disabled unique or primary key. Disable Clause Specify disable to disable the integrity constraint. Disabled integrity constraints appear in the data dictionary along with enabled constraints. If we do not specify this clause when creating a constraint, oracle automatically enables the constraint. Disable validate disables the constraint and drops the index on the constraint, but keeps the constraint valid. This features is most useful in data warehousing situations, because it lets us load large amounts of data while also saving space by not having an index. Disable NOVALIDATE signifies that oracle makes no effort to maintain the constraint. If we specify neither validate nor NOVALIDATE, then the default id NOVALIDATE. RELY Clause Rely and NORELY are valid only when we are modifying an existing constraint. These parameters specify whether a constraint in NOVALIDATE mode is to be taken into account for query rewrite. Specify rely to activate an existing constraint in NOVALIDATE mode for query rewrite in an unenforced query rewrite integrity mode. The constraint is in NOVALIDATE mode, so oracle does not enforce it. The default is NORELY. Restriction on the RELY Clause We cannot set a NONDEFERRABLE NOT NULL constraint to RELY. Deferrable Constraints Illustration Table with Default Enable State
SQL> ED Wrote file afiedt.buf 1 CREATE TABLE mymaster 2 ( 3 mastid NUMBER(2) 4 CONSTRAINT mastidPK PRIMARY KEY, 5 mastname VARCHAR2(10) 6 CONSTRAINT mastnamechk 7 CHECK(mastname=UPPER(mastname)), 8 mastdate DATE 9 CONSTRAINT mastdateNN NOT NULL 10* ) SQL> / Table created.

275

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> Ed Wrote file afiedt.buf 1 CREATE TABLE mymasterdetail 2 ( 3 detilid NUMBER(2), 4 mastid NUMBER(2), 5 detailname VARCHAR2(10) 6 CONSTRAINT detailnamechk 7 CHECK(detailname=UPPER(detailname)), 8 detaildate DATE 9 CONSTRAINT detalidateNN NOT NULL, 10 CONSTRAINT detaliidpk PRIMARY KEY(detilid), 11 CONSTRAINT mastidfk FOREIGN KEY(mastid) 12 REFERENCES mymaster(mastid) 13* ) SQL> / Table created.

View Constraint In practically oracle does not enforce view constraints, but operations on views are subject to the integrity constraints defined on the underlying base tables. Constraints on views can be enforced through constraints on base tables. Restrictions on View constraints The view constraints are subset of table constraints. Only unique, primary key and foreign keys constraints can be specified on view. The check constraint is imposed using with check option. As view constraints are not enforced directly, we cannot specify initially deferred or deferrable clauses. View constraints are supported only in disable not novalidate mode. The rely and no rely key words will instruct the oracle server when the view constraint should be enforced. As view is a logical table the constraints on view are not highly considered in practice. The view constraints are adopted for maintenance easiness.
SQL> CREATE VIEW EMPsalary 2 ( 3 EMPid, 4 ename, 5 email UNIQUE RELY DISABLE NOVALIDATE, 6 CONSTRAINT ID_PK PRIMARY KEY(EMPid) 7 RELY DISABLE NOVALIDATE 8 ) 9 AS 10 SELECT 11 Empno, 12 ename, 13 email 14 FROM EMP; Email ERROR at line 13: ORA-00904: "EMAIL": invalid identifier

276

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

277

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Let Us Increase the Speed and Performance of the Database Using Indexes

Working with Index Index It is a schema object which contains an entry for each value that appears in the indexed column(s) of the table or cluster. Index provides direct, fast access to rows. Types of indexes Normal Indexes They are default indexes. They are created with B-tree principle. 278 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Bitmap Indexes They store ROWIDs associated with a key value as a bitmap. Partitioned Indexes They contain partitions containing an entry for each value that appears in the indexed columns of the table. Function Based Indexes They are based on expressions. Enable query to evaluate value returned by an expression. Domain Indexes They are indexes which are instances of an application specific index of type index type. Pre Requisites The table or cluster to be indexed must be in the own schema. Index object privilege should be available on the table to be indexed. Create any index system privilege must be available. Unlimited table space system privilege or space quota on table spaces must be available. For domain indexes, execute object privilege on the index type should be available. For function based indexes, the function used for indexing must be marked as deterministic. Restrictions If index is locally partitioned then the table must be partitioned. If the table is index organized, then a secondary index is created. If the table is temporary table, then index is also temporary with the same scope, as that of the table. Syntax SQL>create {[unique] / [bitmap]} Index indexname On TableName ( columnname [,columnname.]) Tablespace tabespacename; Simple Index or Normal Index A simple index or normal index is created upon a table by considering only one column. These indexes are generally created using the algorithm of B-tree index. We can create index on columns containing null or repeated data if unique key would is not used. These are default indexes in oracle.

SQL> CREATE INDEX EMPenameidx 2 ON EMP(ename); Index created. SQL> CREATE INDEX deptdnameidx

279

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 ON dept(dname); Index created.

Creating Composite Indexes Composite index is an index or multiple columns of a table. Composite index can be created upon a table to the maximum collection of 32 columns. SQL> CREATE INDEX dept_name_loc 2 ON dept(dname,loc); Index created. SQL> CREATE INDEX EMP_name_job_idx 2 ON EMP(ename,job); Index created. Creating Unique Indexes Specify unique to indicate that the value of the column or columns upon which the index is based must be unique. Restrictions We cannot specify both unique and bitmap indexes at a time. Unique key word cannot be specified for a domain index.
SQL> CREATE UNIQUE INDEX stunameIDxUNQ 2 ON stu(name); Index created. SQL> CREATE UNIQUE INDEX stuphonIDxUNQ 2 ON stu(phon); Index created.

BITMAP Indexes Specify BITMAP to indicate that index has to be created with a BITMAP for each distinct key in the table. BITMAP indexes store the ROWIDs associated with a key values as a BITMAP. Each BIT in the BITMAP corresponds to a possible RWOID. These indexes are used to tune queries that use non selective columns in their limiting conditions. BITMAP indexes should be used only when the data is infrequently updated. BITMAP indexes add to the cost of all data manipulation transactions against the tables they index. The oracle optimizer can dynamically convert BITMAP index entries to ROWIDs during the query processing. Restrictions 280 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

BITMAP cannot be specified when creating a global partitioned index. BITMAP second index cannot be created on an index organized table unless the index organized table has a mapping table associated with it. We cannot specify both unique and BITMAP indexes at a time. BITMAP cannot be specified for a domain index. BITMAP indexes should not be used for tables involved in OLTP. BITMAP indexes the load factor on the internal mechanisms of oracle to maintain them. Restricted with usage to tables involved in batch transactions.

SQL> CREATE BITMAP INDEX EMPbitmapdeptno 2 ON EMP(deptno); Index created.

Bitmap Index Structure Dept no 10 20 30 Start ROWID AAANsYAAEAAABSGAAA AAANsYAAEAAABSGAAA AAANsYAAEAAABSGAAA End ROWID AAANsYAAEAAABSGAAN AAANsYAAEAAABSGAAN AAANsYAAEAAABSGAAN Bit Pattern 10100000000001 00010000011110 01001111100000

Each row in the table being indexed adds only one bit to the size of the BITMAP pattern column for the BITMAP index. Each distinct value adds another row to the BITMAP index.

Creating Function Based Indexes These are indexes based on expressions in select statements. The index expressions are built from table columns, containing sql functions or user defined functions. Function based indexes defined with the upper (column name) or lower ( column name) allow case insensitive searches. We should have create index and query rewrite privileges. We should have execute object privilege on the functions used in the function based indexes. Function based indexes are designed to improve query performance when the function is used in where clause. To ensure that oracle uses the index rather than performing a full table scan, we should be sure that the value of the function is not null in the subsequent queries. Oracle treats indexes with columns marked DESC as function based indexes. The function based indexes are used only when the query statement is executed through the specified function.
SQL> CREATE INDEX EMPfuncannsalIDX 2 ON EMP(Sal*12); Index created.

281

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Index Creation is of Two Types Automatic. Manual. Specifications of an Index Index is a schema object. Index is used by the oracle server to speed up retrieval of rows by using a pointer. Index reduces the disk I / O by using rapid path access method to locate the data quickly. Indexs are independent of the table it indexes, both logically and physically. Index is used and maintained automatically by the oracle server. Indexs can be created or dropped at any time and have no effect on the base tables or other indexes. When a table is dropped, the corresponding indexes are also dropped automatically. On one table more than one index can be created, but this does not mean that more the indexes, lead to more faster performance. Each DML operation that is committed on a table with index, means that the index must be updated. Dropping an Index Syntax SQL>drop index index_name; When to Create an Index The column is used frequently in the where clause or in a join condition. The column contains a wide range of values. The column contains a large number of null values. Two or more columns are frequently used together in a where clause or join condition. The table is large and most queries are expected to retrieve less than 2 to 4 % of the rows. When not to Create an Index The table is too small. The columns are not often used as condition in the query. Most queries are expected to retrieve more than 2 to 4 % of the rows. The table is updated frequently. Querying for Indexes The indexes can be confirmed from the USER_INDEXES data dictionary. The column that are involved in an index by querying USER_IND_COLUMNS. SQL>SELECT UC.TABLE_NAME TabName, UC.COLUMN_NAME ColName, UI.INDEX_NAME IDXName FROM USER_IND_COLUMNS UC, USER_INDEXES UI WHERE UC.INDEX_NAME=UI.INDEX_NAME;

282

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Fundamentals of Data Base Security

283

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Database Security The security upon database is applied by defined and describing separate schema objects and GRANTING required privileges upon them. In oracle the privileges can be granted as well as revoked. Grant Command Syntax SQL> GRANT <PrivilageName1>,<PrivilageName2>. ON <ObjectName>; Grant command is used when we want the database to be shared with others users. The other users are granted with certain type of rights. Grant command can be issued not only on table object, but also on views, synonyms, indexes, sequences Etc.
SQL> GRANT SELECT 2 ON EMP 3 TO ENDUSERS; TO ENDUSERS * ERROR at line 3: ORA-01917: user or role 'ENDUSERS' does not exist SQL> GRANT INSERT,SELECT,DELETE 2 ON EMP 3 TO OPERATORS; TO OPERATORS * ERROR at line 3: ORA-01917: user or role 'OPERATORS' does not exist SQL> GRANT INSERT(EMPno,ename,job) 2 ON EMP 3 TO endusers; TO endusers * ERROR at line 3: ORA-01917: user or role 'ENDUSERS' does not exist

Revoke Command Syntax SQL>REVOKE<PrivilegeName1>,<PrivilegeName2>, ON<ObjectName>; Revoke is used when we want one database to stop sharing the information with other users. Revoke privileges is assigned not only on table object, but also on VIEWS, SYNONYMS, INDEXES Etc.

SQL> REVOKE INSERT,DELETE

284

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 ON EMP 3 FROM operators; FROM operators * ERROR at line 3: ORA-01917: user or role 'OPERATORS' does not exist

Types of Privileges System Privileges They allow a user to perform certain actions within the database. Object Privileges An object privilege allows a user to perform certain actions on database objects. Checking the Object Privileges Granted The schema object that stores the information about the privileges granted is USER_TAB_PRIVS_MADE The columns of USER_TAB_PRIVS_MADE Grantee TABLE_NAME Grantor Privilege GRANTABLE Hierarchy
SQL> SELECT 2 GRANTEE,TABLE_NAME "Table",GRANTOR,PRIVILEGE 3 FROM USER_TAB_PRIVS_MADE; GRANTEE Table GRANTOR PRIVILEGE ------------------------------ ------------------------------ ------------------------------ ------SEKHAR BONUS SCOTT ALTER SEKHAR BONUS SCOTT DELETE SEKHAR BONUS SCOTT INDEX SEKHAR BONUS SCOTT INSERT SEKHAR BONUS SCOTT SELECT SEKHAR BONUS SCOTT UPDATE SEKHAR BONUS SCOTT REFERENCES SEKHAR BONUS SCOTT ON COMMIT REFRESH SEKHAR BONUS SCOTT QUERY REWRITE SEKHAR BONUS SCOTT DEBUG SEKHAR BONUS SCOTT FLASHBACK SEKHAR SALGRADE SCOTT ALTER SEKHAR SALGRADE SCOTT DELETE SEKHAR SALGRADE SCOTT INDEX SEKHAR SALGRADE SCOTT INSERT SEKHAR SALGRADE SCOTT SELECT SEKHAR SALGRADE SCOTT UPDATE SEKHAR SALGRADE SCOTT REFERENCES SEKHAR SALGRADE SCOTT ON COMMIT REFRESH SEKHAR SALGRADE SCOTT QUERY REWRITE SEKHAR SALGRADE SCOTT DEBUG SEKHAR SALGRADE SCOTT FLASHBACK

285

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

22 rows selected.

Making Use of Object Privileges Once a particular user has been granted an object privilege, the specific user can perform the tasks as granted by the privilege. Steps to be Performed Connect to the required user using the user name and password. Execute the required sql statement using the object hierarchy.
SQL> SELECT * 2 FROM SCOTT.EMP; EMPNO ENAME JOB MGR HIREDATE SAL ---------- ---------- --------- ---------- --------- ---------- ---------- ---------7839 KING PRESIDENT 17-NOV-81 5000 7698 BLAKE MANAGER 7839 01-MAY-81 2850 7782 CLARK MANAGER 7839 09-JUN-81 2450 7566 JONES MANAGER 7839 02-APR-81 2975 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 7844 TURNER SALESMAN 7698 08-SEP-81 1500 7900 JAMES CLERK 7698 03-DEC-81 950 7521 WARD SALESMAN 7698 22-FEB-81 1250 7902 FORD ANALYST 7566 03-DEC-81 3000 7369 SMITH CLERK 7902 17-DEC-80 800 7788 SCOTT ANALYST 7566 09-DEC-82 3000 7876 ADAMS CLERK 7788 12-JAN-83 1100 7934 MILLER CLERK 7782 23-JAN-82 1300 14 rows selected. COMM 10 30 10 20 1400 30 300 30 0 30 30 500 30 20 20 20 20 10 DEPTNO

Working with Roles A role is a group of privileges that can be assigned to a user or another role. Advantages Rather than assigning privileges one at a time directly to a 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 one role to another role. A role can be assigned with a password. Roles Creation To create a role we should have the create role system privilege. The steps in implanting the roles Role creation Granting privileges to roles Granting roles to users or objects Syntax 286 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL>CREATE ROLE<RoleName> [IDENTIFIED BY<Password>];


SQL> CREATE ROLE sales_manger 2 IDENTIFIED BY salesaudit; IDENTIFIED BY salesaudit * ERROR at line 2: ORA-01031: insufficient privileges

Granting Privileges to Role The roles are granted privileges using the grant statement. A role can be granted both system as well as object privileges at a time.
SQL> GRANT SELECT, INSERT, UPDATE, DELETE 2 ON EMP 3 TO sales_manager; TO sales_manager * ERROR at line 3: ORA-01917: user or role 'SALES_MANAGER' does not exist

Granting a Role to a User


SQL> GRANT sales_manager 2 TO 3 SCOTT; GRANT sales_manager * ERROR at line 1: ORA-01919: role 'SALES_MANAGER' does not exist

Granting Multiple Roles to Another Role SQL> GRANT ROLE1, ROLE2, . TO <TARGET_ROLE_NAME>; Checking Roles Granted to a Role The schema object USER_ROLE_PRIVS specifies the roles granted to a user. The columns of USER_ROLE_PRIVS USERNAME GRANTED_ROLE ADMIN_OPTION DEFAULT_ROLE OS_GRANTED
SQL> SELECT USERNAME,GRANTED_ROLE 2 FROM USER_ROLE_PRIVS; USERNAME GRANTED_ROLE ------------------------------ -----------------------------SCOTT CONNECT SCOTT RESOURCE

287

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 rows selected.

System Privileges Granted to a Role The schema object ROLE_SYS_PRIVS specifies the system privileges granted to a role. The columns of ROLE_SYS_PRIVS. Role Privilege ADMIN_OPTION
SQL> SELECT ROLE,PRIVILEGE 2 FROM ROLE_SYS_PRIVS; ROLE PRIVILEGE ------------------------------ --------------------------CONNECT CREATE VIEW CONNECT CREATE TABLE CONNECT ALTER SESSION CONNECT CREATE CLUSTER CONNECT CREATE SESSION CONNECT CREATE SYNONYM CONNECT CREATE SEQUENCE CONNECT CREATE DATABASE LINK RESOURCE CREATE TYPE RESOURCE CREATE TABLE RESOURCE CREATE CLUSTER RESOURCE CREATE TRIGGER RESOURCE CREATE OPERATOR RESOURCE CREATE SEQUENCE RESOURCE CREATE INDEXTYPE RESOURCE CREATE PROCEDURE 16 rows selected.

Object Privileges Granted to a Role The schema object ROLE_TAB_PRIVS specification the object privileges granted to a role. The columns of ROLE_TAB_PRIVS Role .COLUMN_NAME Owner .Privilege TABLE_NAME .GRANTABLE
SQL> SELECT ROLE,PRIVILEGE 2 FROM ROLE_TAB_PRIVS; no rows selected

Revoking a Role
SQL> REVOKE sales_manager 2 FROM SCOTT;

288

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

REVOKE sales_manager * ERROR at line 1: ORA-01919: role 'SALES_MANAGER' does not exist

Revoking All Privileges from a Role


SQL> REVOKE ALL 2 ON EMP 3 FROM sales_manager; FROM sales_manager * ERROR at line 3: ORA-01917: user or role 'SALES_MANAGER' does not exist

Dropping a Role Syntax SQL> DROP ROLE <RoleName>;


SQL> DROP ROLE sales_manager; DROP ROLE sales_manager * ERROR at line 1: ORA-01919: role 'SALES_MANAGER' does not exist

Working with Synonyms A synonym is schema object, which acts as an alternate name for an existing schema object. By using a synonym, we can avoid the entry of the schema name, when referencing upon objects the belong to other schema. The create synonym privilege is necessary to execute the creation of a synonym. Syntax SQL> CREATE [PUBLIC] SYNONYM <SynonymName> FOR <SchemaName>.<ObjectName>; Illustration
SQL> CREATE SYNONYM EMPinfor 2 FOR SCOTT.EMP; Synonym created.

Synonym Types The synonyms are practically of two types Private synonym Public synonym We should have create public synonym privilege, which can be accessed by all users in the data base.
SQL> CREATE PUBLIC SYNONYM EMPinfo

289

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 FOR SCOTT.EMP; CREATE PUBLIC SYNONYM EMPinfo * ERROR at line 1: ORA-01031: insufficient privileges

Dropping a Synonym Syntax SQL> DROP [PUBLIC] SYNONYM <SynonymName>; Illustration


SQL> DROP SYNONYM EMPinfor; Synonym dropped. SQL> DROP PUBLIC SYNONYM EMPinfo; DROP PUBLIC SYNONYM EMPinfo * ERROR at line 1: ORA-01432: public synonym to be dropped does not exist

290

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

OLAP Features in Oracle

291

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Some features for query processing in oracle include the use of online analytical processing (OLAP) upon the data base. OLAP features are useful for data warehousing and data mart applications. The OLAP operations are performance enhancements. TOP_N QUERIES. GROUP BY. CUBE. ROLLUP. Rollup Option It is a group by operation and is used to produce subtotals at any level of the aggregation. The generated subtotal Rolled UP to produce grant total. The totaling is based on a one dimensional data hierarchy of grouped information. Syntax GROUP BY ROLLUP ( Column1, Column2, ..) Illustrations
SQL> SELECT deptno,SUM(Sal) 2 FROM EMP 3 GROUP BY ROLLUP(deptno); DEPTNO SUM(SAL) ---------- ---------10 8750 20 10875 30 9400 29025 4 rows selected. SQL> SELECT job, SUM(Sal) 2 FROM EMP 3 GROUP BY ROLLUP(job); JOB SUM(SAL) -----------------ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 29025

292

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

6 rows selected. SQL> SELECT job,AVG(Sal) 2 FROM EMP 3 GROUP BY ROLLUP(job); JOB AVG(SAL) --------- ---------ANALYST 3000 CLERK 1037.5 MANAGER 2758.33333 PRESIDENT 5000 SALESMAN 1400 2073.21429 6 rows selected.

Passing Multiple Columns to Rollup When multiple columns are passed to rollup, the rollup, groups the rows into blocks with the same column values.
SQL> SELECT deptno,job,SUM(Sal) Salary 2 FROM EMP 3 GROUP BY ROLLUP(deptno, job); DEPTNO JOB SALARY ---------- -----------------10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 10 8750 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 20 10875 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 30 9400 29025 13 rows selected. SQL> SELECT job,deptno,SUM(Sal) Salary 2 FROM EMP 3 GROUP BY ROLLUP(job,deptno); JOB DEPTNO SALARY --------- ---------- ---------CLERK 10 1300 CLERK 20 1900 CLERK 30 950

293

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

CLERK ANALYST ANALYST MANAGER MANAGER MANAGER MANAGER SALESMAN SALESMAN PRESIDENT PRESIDENT

20

4150 6000 6000 10 2450 20 2975 30 2850 8275 30 5600 5600 10 5000 5000 29025

15 rows selected. SQL> SELECT job,deptno,AVG(Sal) Average 2 FROM EMP 3 GROUP BY ROLLUP(job,deptno); JOB DEPTNO AVERAGE --------- ---------- ---------CLERK 10 1300 CLERK 20 950 CLERK 30 950 CLERK 1037.5 ANALYST 20 3000 ANALYST 3000 MANAGER 10 2450 MANAGER 20 2975 MANAGER 30 2850 MANAGER 2758.33333 SALESMAN 30 1400 SALESMAN 1400 PRESIDENT 10 5000 PRESIDENT 5000 2073.21429 15 rows selected.

Null vales in the output of rollup operations typically mean that the row contains subtotal or grant total information. Use NVL () function for proper meaning. CUBE Option It is an extension similar to rollup. Cube allows to take a specified set of grouping columns and create sub totals for all possible combinations of them. The result of cube is a summary that shows subtotals for every combination of columns or expressions in the group by clause. The implementation of cube is also called as N-Dimensional cross tabulation.
SQL> SELECT deptno,job,SUM(Sal) Salary 2 FROM EMP

294

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 GROUP BY CUBE(deptno, job); DEPTNO JOB ---------- --------SALARY ---------29025 CLERK 4150 ANALYST 6000 MANAGER 8275 SALESMAN 5600 PRESIDENT 5000 10 8750 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 10875 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 30 9400 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600

18 rows selected. SQL> SELECT job,deptno,SUM(Sal) Salary 2 FROM EMP 3 GROUP BY CUBE(job,deptno); JOB --------DEPTNO SALARY ---------- ---------29025 10 8750 20 10875 30 9400 CLERK 4150 CLERK 10 1300 CLERK 20 1900 CLERK 30 950 ANALYST 6000 ANALYST 20 6000 MANAGER 8275 MANAGER 10 2450 MANAGER 20 2975 MANAGER 30 2850 SALESMAN 5600 SALESMAN 30 5600 PRESIDENT 5000 PRESIDENT 10 5000 18 rows selected.

Applying GROUPING () Function The GROUPING () function accepts a column and returns 0 or 1. 295 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

GROUPIN () function returns 1 when the column value is null, and returns 0 when the column value is not null. GROUPIN () function is used only upon queries that use rollup or cube. GROUPIN () function is useful when we want to display a value when a null would otherwise be returned in OLAP queries.

SQL> SELECT GROUPING(deptno),deptno,SUM(Sal) 2 FROM EMP 3 GROUP BY ROLLUP(deptno); GROUPING(DEPTNO) ---------------0 0 0 1 4 rows selected. SQL> SELECT GROUPING(job),job, SUM(Sal) 2 FROM EMP 3 GROUP BY ROLLUP(job); GROUPING(JOB) JOB SUM(SAL) --------------------- ---------0 ANALYST 6000 0 CLERK 4150 0 MANAGER 8275 0 PRESIDENT 5000 0 SALESMAN 5600 1 29025 6 rows selected. DEPTNO SUM(SAL) ------------------10 8750 20 10875 30 9400 29025

DECODE Function It is a single row function. The function works on the same principle as the IF_THEN_ELSE. We can pass a variable number of values into the call of the DECODE () function. The first item is always the name of the column that need to be decoded. Once all value-substitute pairs have been defined, we can optionally specify a default value. Syntax SQL> SELECT DECODE (ColumnName, Value 1, Substitute 1, Value 2, Substitute 2, . ReturnDefault ) From TableName; The function has no restriction on the input and output data type. It is the most power full function in oracle. 296 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

The function can work for only an analysis that considers an equality operator in the logical comparison.

SQL> Ed Wrote file afiedt.buf 1 SELECT ename,job,sal, 2 DECODE(deptno, 3 10,'ACCOUNTING', 4 20,'RESEARCH', 5 30,'SALES', 6 40,'OPERATIONS', 7 'OTHER') Departments 8 FROM EMP 9* ORDER BY Departments SQL> / ENAME JOB SAL DEPARTMENT ---------- --------- ---------- ---------KING PRESIDENT 5000 ACCOUNTING CLARK MANAGER 2450 ACCOUNTING MILLER CLERK 1300 ACCOUNTING JONES MANAGER 2975 RESEARCH SCOTT ANALYST 3000 RESEARCH ADAMS CLERK 1100 RESEARCH SMITH CLERK 800 RESEARCH FORD ANALYST 3000 RESEARCH BLAKE MANAGER 2850 SALES MARTIN SALESMAN 1250 SALES ALLEN SALESMAN 1600 SALES TURNER SALESMAN 1500 SALES JAMES CLERK 950 SALES WARD SALESMAN 1250 SALES 14 rows selected.

GROUPING () with DECODE () The decode () function can be used to convert 1 and 0 returned through GROUPING () into a meaningful output.
SQL> SELECT 2 DECODE(GROUPING(deptno), 3 1,'All Departments', 4 deptno) Departments, 5 SUM(Sal) 6 FROM EMP 7 GROUP BY ROLLUP(deptno); DEPARTMENTS SUM(SAL) ---------------------------------------- ---------10 8750 20 10875 30 9400

297

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

All Departments 4 rows selected. SQL> SELECT 2 DECODE(GROUPING(job), 3 1,'All Designation', 4 job) Designations, SUM(Sal) 5 FROM EMP 6 GROUP BY ROLLUP(job); DESIGNATIONS SUM(SAL) --------------- ---------ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 All Designation 29025 6 rows selected.

29025

DECODE () and GROUPING () to Converting Multiple Column Values


SQL> SELECT 2 DECODE(GROUPING(deptno), 3 1,'All Departments', 4 deptno) Departments, 5 DECODE(GROUPING(job), 6 1,'All Designation', 7 job) Designations, SUM(Sal) 8 FROM EMP 9 GROUP BY ROLLUP(deptno, job); DEPARTMENTS DESIGNATIONS SUM(SAL) ---------------------------------------- --------------- ---------10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 10 All Designation 8750 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 20 All Designation 10875 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 30 All Designation 9400 All Departments All Designation 29025 13 rows selected.

GROUPING () with DECODE () and CUBE


SQL> SELECT

298

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 3 4 5 6 7 8 9

DECODE(GROUPING(deptno), 1,'All Departments', deptno) Departments, DECODE(GROUPING(job), 1,'All Designation', job) Designations, SUM(Sal) FROM EMP GROUP BY CUBE(deptno, job);

DEPARTMENTS DESIGNATIONS SUM(SAL) ---------------------------------------- --------------- ---------All Departments All Designation 29025 All Departments CLERK 4150 All Departments ANALYST 6000 All Departments MANAGER 8275 All Departments SALESMAN 5600 All Departments PRESIDENT 5000 10 All Designation 8750 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 All Designation 10875 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 30 All Designation 9400 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 18 rows selected.

Applying GROUPING SETS Clause The GROUPING SETS clause is used to get the sub total rows.
SQL> SELECT deptno,job,SUM(Sal) 2 FROM EMP 3 GROUP BY 4 GROUPING SETS(deptno, job); DEPTNO JOB SUM(SAL) ---------- --------- ---------10 8750 20 10875 30 9400 ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 8 rows selected.

299

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Working with CASE Expressions The case expression can be used to perform IF_THEN_ELSE logic in sql. Case is similar to decode but it is ANSI compliant. It can be used even for executing conditions on range based comparison. Case expressions are of two types Simple case expressions. Searched case expressions. Simple Case Expressions These expressions are used to determine the returned value. They work with equality comparison only, almost all similar to decode. It has a selector which associates to the compared value either from the column or constant. The value in the selector is used for comparison with the expressions used in the when clause. Syntax SQL> CASE Search_Expr WHEN Expr 1 THEN Result 1 WHEN Expr 2 THEN Result 2 ELSE Default_Result END Illustration
SQL> SELECT ename,deptno, 2 CASE deptno 3 WHEN 10 THEN 'ACCOUNTS' 4 WHEN 20 THEN 'RESEARCH' 5 WHEN 30 THEN 'SALES' 6 WHEN 40 THEN 'OPERATIONS' 7 ELSE 'Not Found' 8 END 9 FROM EMP; ENAME DEPTNO CASEDEPTNO ---------- ---------- ---------KING 10 ACCOUNTS BLAKE 30 SALES CLARK 10 ACCOUNTS JONES 20 RESEARCH MARTIN 30 SALES ALLEN 30 SALES TURNER 30 SALES JAMES 30 SALES WARD 30 SALES FORD 20 RESEARCH SMITH 20 RESEARCH SCOTT 20 RESEARCH ADAMS 20 RESEARCH MILLER 10 ACCOUNTS

300

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

14 rows selected.

Searched Case Expressions 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 n ELSE DefaultResult END Illustration
SQL> SELECT ename,deptno, 2 CASE 3 WHEN deptno=10 THEN 'ACCOUNTING' 4 WHEN deptno=20 THEN 'RESEARCH' 5 WHEN deptno=30 THEN 'SALES' 6 WHEN deptno=40 THEN 'OPERATIONS' 7 ELSE 'Not Specified' 8 END 9 FROM EMP; ENAME DEPTNO CASEWHENDEPTNO ---------- ---------- -------------KING 10 ACCOUNTING BLAKE 30 SALES CLARK 10 ACCOUNTING JONES 20 RESEARCH MARTIN 30 SALES ALLEN 30 SALES TURNER 30 SALES JAMES 30 SALES WARD 30 SALES FORD 20 RESEARCH SMITH 20 RESEARCH SCOTT 20 RESEARCH ADAMS 20 RESEARCH MILLER 10 ACCOUNTING 14 rows selected. SQL> ED Wrote file afiedt.buf 1 2 3 4 SELECT ename,sal, CASE WHEN Sal>=800 AND Sal<=2000 THEN 'Lowest Pay' WHEN Sal>=2001 AND Sal<=4000 THEN 'Moderate Pay'

301

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

5 ELSE 'High Pay' 6 END 7* FROM EMP SQL> / ENAME SAL CASEWHENSAL> ---------- ---------- -----------KING 5000 High Pay BLAKE 2850 Moderate Pay CLARK 2450 Moderate Pay JONES 2975 Moderate Pay MARTIN 1250 Lowest Pay ALLEN 1600 Lowest Pay TURNER 1500 Lowest Pay JAMES 950 Lowest Pay WARD 1250 Lowest Pay FORD 3000 Moderate Pay SMITH 800 Lowest Pay SCOTT 3000 Moderate Pay ADAMS 1100 Lowest Pay MILLER 1300 Lowest Pay 14 rows selected.

Materialized Views Materialized views are used in data warehouses and data marts. They are used to increase the speed of queries on very large scale databases. Queries making use of materialized views are.. Aggregations on a single table. Joins between tables. Aggregations and joins together. Materialized views can be used to replicate data. Prior to materialized views, the concept of snapshot was implemented. Query Rewrite Materialized views improve query performance by pre calculating expensive join and aggregation operations on the database prior to executive time and stores the results 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. After above process is completed then the query optimizer transparently rewrites the request to use the materialized view. Queries are then directed to the materialized view and not to the underlying detail tables or views. Rewriting queries to use materialized views rather than detail relations, results in a significant performance gain. Prerequisites for Materialized Views 302 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Privileges
SQL> CONN / AS SYSDBA Connected. SQL> GRANT 2 QUERY REWRITE 3 TO SCOTT; Grant succeeded. SQL> GRANT CREATE MATERIALIZED VIEW 2 TO SCOTT; Grant succeeded. SQL> ALTER SESSION 2 SET QUERY_REWRITE_ENABLED = TRUE; Session altered.

Set the InitSid.ORA File OPTIMIZER_MODE=CHOOSE JOB_QUEUE_INTERVAL=3600 JOB_QUEUE_PROCESSES=1 QUERY_REWRITE_ENABLED=TRUE QUERY_REWRITE_INTEGRITY=ENFORCED

Materialized View with Aggregation


SQL> CREATE MATERIALIZED VIEW emo_SUM 2 ENABLE QUERY REWRITE 3 AS 4 SELECT deptno,job,SUM(Sal) 5 FROM EMP 6 GROUP BY deptno, job; Materialized view created.

Creating Optimizer Statistics and Refreshing Materialized Views


SQL> EXECUTE DBMS_UTILITY.ANALYZE_SCHEMA ('SCOTT','ESTIMATE'); PL/SQL procedure successfully completed.

Testing Materialized View


SQL> EXECUTE DBMS_UTILITY.ANALYZE_SCHEMA ('SCOTT','ESTIMATE'); PL/SQL procedure successfully completed.

303

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SET AUTOTRACE ON EXPLAIN; SQL> SELECT deptno,SUM(Sal) 2 FROM EMP 3 GROUP BY deptno, job; DEPTNO SUM(SAL) ---------- ---------10 1300 10 2450 10 5000 20 1900 20 6000 20 2975 30 950 30 2850 30 5600 9 rows selected. Execution Plan ---------------------------------------------------------0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=2 Card=9 Bytes=45) 1 0 MAT_VIEW REWRITE ACCESS (FULL) OF 'EMO_SUM' (MAT_VIEW REWR ITE) (Cost=2 Card=9 Bytes=45)

Putting the Things with Rollup


SQL> Ed Wrote file afiedt.buf 1 CREATE MATERIALIZED VIEW emo_dept_agg 2 ENABLE QUERY REWRITE 3 AS 4 SELECT deptno,job,COUNT(*),SUM(Sal) 5 FROM EMP 6* GROUP BY ROLLUP(Deptno, job) SQL> / Materialized view created.

GROUPING ID () Function The function is used to filter rows using a having clause to exclude rows that do not contain a subtotal or grant total. The function accepts one or more columns and returns the decimal equivalent of the GROUPIN BIT VECTOR. The GROUPING BIT VICTOR is computed by combining the results of a call to the GROUPING () function for each column in order. 304 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Computing the GROUPING BIT VECTOR GROUPING () function returns 1 when the column value is null, else returns 0, based on this concept. GROUPING_ID () returns 0, when deptno and job not nulls. 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, if deptno is null and job is null.
SQL> Ed Wrote file afiedt.buf 1 SELECT deptno, job, 2 GROUPING(deptno) GDPT, 3 GROUPING(job) GJOB, 4 GROUPING_ID(deptno, job) GRPID, 5 SUM(Sal) 6 FROM EMP 7* GROUP BY ROLLUP(deptno, job) SQL> / DEPTNO JOB GDPT GJOB GRPID SUM(SAL) ---------- --------- ---------- ---------- ---------- ---------10 CLERK 0 0 0 1300 10 MANAGER 0 0 0 2450 10 PRESIDENT 0 0 0 5000 10 0 1 1 8750 20 CLERK 0 0 0 1900 20 ANALYST 0 0 0 6000 20 MANAGER 0 0 0 2975 20 0 1 1 10875 30 CLERK 0 0 0 950 30 MANAGER 0 0 0 2850 30 SALESMAN 0 0 0 5600 30 0 1 1 9400 1 1 3 29025 13 rows selected. Execution Plan ---------------------------------------------------------0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=3 Card=9 Bytes=108 ) 1 2 0 SORT (GROUP BY ROLLUP) (Cost=3 Card=9 Bytes=108) 1 MAT_VIEW REWRITE ACCESS (FULL) OF 'EMO_SUM' (MAT_VIEW RE WRITE) (Cost=2 Card=9 Bytes=108)

SQL> SELECT deptno, job, 2 GROUPING(deptno) GDPT, 3 GROUPING(job) GJOB, 4 GROUPING_ID(deptno, job) GRPID,

305

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

5 SUM(Sal) 6 FROM EMP 7 GROUP BY CUBE(deptno, job); DEPTNO JOB GDPT GJOB GRPID SUM(SAL) ---------- --------- ---------- ---------- ---------- ---------1 1 3 29025 CLERK 1 0 2 4150 ANALYST 1 0 2 6000 MANAGER 1 0 2 8275 SALESMAN 1 0 2 5600 PRESIDENT 1 0 2 5000 10 0 1 1 8750 10 CLERK 0 0 0 1300 10 MANAGER 0 0 0 2450 10 PRESIDENT 0 0 0 5000 20 0 1 1 10875 20 CLERK 0 0 0 1900 20 ANALYST 0 0 0 6000 20 MANAGER 0 0 0 2975 30 0 1 1 9400 30 CLERK 0 0 0 950 30 MANAGER 0 0 0 2850 30 SALESMAN 0 0 0 5600 18 rows selected. Execution Plan ---------------------------------------------------------0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=3 Card=9 Bytes=108 ) 1 2 3 4 0 SORT (GROUP BY) (Cost=3 Card=9 Bytes=108) 1 GENERATE (CUBE) (Cost=3 Card=9 Bytes=108) 2 SORT (GROUP BY) (Cost=3 Card=9 Bytes=108) 3 MAT_VIEW REWRITE ACCESS (FULL) OF 'EMO_SUM' (MAT_VIE W REWRITE) (Cost=2 Card=9 Bytes=108)

GROUPING ID () and HAVING Clause


SQL> SELECT deptno, job, 2 GROUPING_ID(deptno, job) GPRD 3 ,SUM(Sal) 4 FROM EMP 5 GROUP BY CUBE(deptno, job) 6 HAVING GROUPING_ID(deptno, job)>0; DEPTNO JOB GPRD SUM(SAL) ---------- --------- ---------- ---------3 29025 CLERK 2 4150 ANALYST 2 6000 MANAGER 2 8275

306

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SALESMAN PRESIDENT 10 1 20 1 30 1 9 rows selected.

2 5600 2 5000 8750 10875 9400

Execution Plan ---------------------------------------------------------0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=3 Card=1 Bytes=12) 1 0 FILTER 2 1 SORT (GROUP BY) (Cost=3 Card=1 Bytes=12) 3 2 GENERATE (CUBE) (Cost=3 Card=1 Bytes=12) 4 3 SORT (GROUP BY) (Cost=3 Card=1 Bytes=12) 5 4 MAT_VIEW REWRITE ACCESS (FULL) OF 'EMO_SUM' (MAT_V IEW REWRITE) (Cost=2 Card=9 Bytes=108)

Representing Column Multiple Times in a Group By Clause A column can be represented multiple times in a group by clause.
SQL> Ed Wrote file afiedt.buf 1 SELECT deptno,job,SUM(Sal) 2 FROM EMP 3* GROUP BY deptno,ROLLUP(deptno, job) SQL> / DEPTNO JOB SUM(SAL) ---------- --------- ---------10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 10 8750 20 10875 30 9400 10 8750 20 10875 30 9400 15 rows selected. Execution Plan ---------------------------------------------------------0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=9 Card=9 Bytes=288

307

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

) 1 2 3 4 5 6 0 TEMP TABLE TRANSFORMATION 1 MULTI-TABLE INSERT 2 DIRECT LOAD INTO OF 'SYS_TEMP_0FD9D6604_28B922' 2 DIRECT LOAD INTO OF 'SYS_TEMP_0FD9D6605_28B922' 4 SORT (GROUP BY ROLLUP) (Cost=3 Card=9 Bytes=108) 5 MAT_VIEW ACCESS (FULL) OF 'EMO_SUM' (MAT_VIEW) (Co st=2 Card=9 Bytes=108)

7 1 VIEW (Cost=6 Card=3 Bytes=96) 8 7 VIEW (Cost=6 Card=3 Bytes=96) 9 8 UNION-ALL 10 9 TABLE ACCESS (FULL) OF 'SYS_TEMP_0FD9D6605_28B922' (TABLE (TEMP)) (Cost=2 Card=1 Bytes=32) 11 12 9 TABLE ACCESS (FULL) OF 'SYS_TEMP_0FD9D6604_28B922' (TABLE (TEMP)) (Cost=2 Card=1 Bytes=32) 9 TABLE ACCESS (FULL) OF 'SYS_TEMP_0FD9D6604_28B922' (TABLE (TEMP)) (Cost=2 Card=1 Bytes=32)

SQL> SET AUTOTRACE OFF EXPLAIN; SQL> SELECT deptno,job,SUM(Sal) 2 FROM EMP 3 GROUP BY deptno,CUBE(deptno, job); DEPTNO JOB SUM(SAL) ---------- --------- ---------10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 10 8750 20 10875 30 9400 10 8750

308

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

20 30

10875 9400

24 rows selected.

Applying GROUP 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. If N duplicates exist for a particular grouping, GROUP_ID () returns numbers in the range 0 to N 1.
SQL> SELECT deptno,job,GROUP_ID(),SUM(Sal) 2 FROM EMP 3 GROUP BY deptno,ROLLUP(deptno, job); DEPTNO JOB GROUP_ID() SUM(SAL) ---------- --------- ---------- ---------10 CLERK 0 1300 10 MANAGER 0 2450 10 PRESIDENT 0 5000 20 CLERK 0 1900 20 ANALYST 0 6000 20 MANAGER 0 2975 30 CLERK 0 950 30 MANAGER 0 2850 30 SALESMAN 0 5600 10 0 8750 20 0 10875 30 0 9400 10 1 8750 20 1 10875 30 1 9400 15 rows selected. SQL> SELECT deptno,job,GROUP_ID(),SUM(Sal) 2 FROM EMP 3 GROUP BY deptno,CUBE(deptno, job); DEPTNO JOB GROUP_ID() SUM(SAL) ---------- --------- ---------- ---------10 CLERK 0 1300 10 MANAGER 0 2450 10 PRESIDENT 0 5000 20 CLERK 0 1900 20 ANALYST 0 6000 20 MANAGER 0 2975 30 CLERK 0 950 30 MANAGER 0 2850 30 SALESMAN 0 5600 10 CLERK 1 1300 10 MANAGER 1 2450 10 PRESIDENT 1 5000

309

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

20 CLERK 20 ANALYST 20 MANAGER 30 CLERK 30 MANAGER 30 SALESMAN 10 0 20 0 30 0 10 1 20 1 30 1 24 rows selected.

1900 6000 2975 1 950 1 2850 1 5600 8750 10875 9400 8750 10875 9400 1 1

SQL> SELECT deptno,job,GROUP_ID(),SUM(Sal) 2 FROM EMP 3 GROUP BY deptno,CUBE(deptno, job) 4 HAVING GROUP_ID ()=0; DEPTNO JOB GROUP_ID() SUM(SAL) ---------- --------- ---------- ---------10 CLERK 0 1300 10 MANAGER 0 2450 10 PRESIDENT 0 5000 20 CLERK 0 1900 20 ANALYST 0 6000 20 MANAGER 0 2975 30 CLERK 0 950 30 MANAGER 0 2850 30 SALESMAN 0 5600 10 0 8750 20 0 10875 30 0 9400 12 rows selected.

Enhancing the Power of OLAP Using Analytic Functions Analytic functions 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 differences from ordinary aggregate functions to analytic functions are, they return multiple rows for each group. The group of rows are called as window and is defined by the analytic clause. For each row, a sliding window of rows are defined. The window define the range of rows used to perform the calculation for the current row. 310 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Window sizes can be based upon either a physical number of rows or a logical interval such as time. Analytic functions are the last set of operations performed in a query, except for the final order by clause. All joins, where clause, group by, and having clauses are completed before the analytic functions are processed. Analytic functions can appear only in the select list or order by clause.

Syntax AnalyticFunction (Arg 1, Arg 2, Arg 3) Over (partition clause Order by clause Windowing clause) Analytic function takes 0 to 3 arguments. The partition by clause logically breaks a single result set into N groups. The analytic functions are applied for each group independently, and they are reset for each group. The order by clause specifies how data is stored within each group (partition). The output of analytic function is affected by order by clause. The windowing clause us a way to define a sliding (or) analytic function will operate, within a group. Analytic Functions Categories Ranking Functions They enable us to calculate ranks, percentiles and N-Tiles. Inverse Percentile Functions Enable to calculate the value corresponding to a percentile. Window Functions Enable to calculate cumulative and moving aggregates.

Reporting Functions Enable to calculate area like market shares. Lag and Lead Functions Enable to get a value in a row where that row is a certain number of rows away from the current row. First and Last Functions Enable to get the first and last values in an ordered group. Linear Regression Functions Enable to fit an ordinary-least-squares regression line to a set of number pairs. Hypothetical Rank and Distribution Functions 311 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Enable to calculate the rank and percentile that a New row would have if a value is inserted into a table.

Normal Ranking
SQL> SELECT ename,deptno,sal, 2 RANK() 3 OVER(ORDER BY Sal) EMPRank 4 FROM EMP 5 GROUP BY deptno,ename,sal ORDER BY EMPRank; ENAME DEPTNO SAL EMPRANK ---------- ---------- ---------- ---------SMITH 20 800 1 JAMES 30 950 2 ADAMS 20 1100 3 MARTIN 30 1250 4 WARD 30 1250 4 MILLER 10 1300 6 TURNER 30 1500 7 ALLEN 30 1600 8 CLARK 10 2450 9 BLAKE 30 2850 10 JONES 20 2975 11 FORD 20 3000 12 SCOTT 20 3000 12 KING 10 5000 14 14 rows selected. SQL> SELECT ename,deptno,sal, 2 DENSE_RANK() 3 OVER(ORDER BY Sal DESC) EMPRank 4 FROM EMP 5 GROUP BY deptno,ename,and sal 6 ORDER BY EMPRank; ENAME DEPTNO SAL EMPRANK ---------- ---------- ---------- ---------KING 10 5000 1 FORD 20 3000 2 SCOTT 20 3000 2 JONES 20 2975 3 BLAKE 30 2850 4 CLARK 10 2450 5 ALLEN 30 1600 6 TURNER 30 1500 7 MILLER 10 1300 8 MARTIN 30 1250 9 WARD 30 1250 9 ADAMS 20 1100 10 JAMES 30 950 11 SMITH 20 800 12

312

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

14 rows selected.

Ranking with Partition


SQL> ED Wrote file afiedt.buf 1 SELECT ename,deptno,sal, 2 RANK() 3 OVER(PARTITION BY deptno 4 ORDER BY Sal DESC) "Top Sal" 5 FROM EMP 6* ORDER BY deptno,sal DESC SQL> / ENAME DEPTNO SAL Top Sal ---------- ---------- ---------- ---------KING 10 5000 1 CLARK 10 2450 2 MILLER 10 1300 3 FORD 20 3000 1 SCOTT 20 3000 1 JONES 20 2975 3 ADAMS 20 1100 4 SMITH 20 800 5 BLAKE 30 2850 1 ALLEN 30 1600 2 TURNER 30 1500 3 MARTIN 30 1250 4 WARD 30 1250 4 JAMES 30 950 6 14 rows selected. SQL> SELECT ename,deptno,sal, 2 DENSE_RANK() 3 OVER(PARTITION BY deptno 4 ORDER BY Sal DESC) "Top Sal" 5 FROM EMP 6 ORDER BY deptno,sal DESC; ENAME DEPTNO SAL Top Sal ---------- ---------- ---------- ---------KING 10 5000 1 CLARK 10 2450 2 MILLER 10 1300 3 FORD 20 3000 1 SCOTT 20 3000 1 JONES 20 2975 2 ADAMS 20 1100 3 SMITH 20 800 4 BLAKE 30 2850 1 ALLEN 30 1600 2

313

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

TURNER MARTIN WARD JAMES

30 30 30 30

1500 1250 1250 950

3 4 4 5

14 rows selected.

Applying Windows The windowing clause gives a way to define a sliding or ANCHORED window of data, upon which the analytic function will operate, within a group. The default window is an ANCHORED window that simply starts at the first row of a group and continues to the current row. Window can be based on Ranges of data values. Rows offset from the current row. Existence 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 before the order by clause. Row Window
SQL> SELECT deptno,ename,sal,SUM(Sal) 2 OVER(PARTITION BY deptno 3 ORDER BY ename 4 ROWS 2 PRECEDING)"Sliding Total" 5 FROM EMP 6 ORDER BY deptno,ename; DEPTNO ENAME SAL Sliding Total ---------- ---------- ---------- ------------10 CLARK 2450 2450 10 KING 5000 7450 10 MILLER 1300 8750 20 ADAMS 1100 1100 20 FORD 3000 4100 20 JONES 2975 7075 20 SCOTT 3000 8975 20 SMITH 800 6775 30 ALLEN 1600 1600 30 BLAKE 2850 4450 30 JAMES 950 5400 30 MARTIN 1250 5050 30 TURNER 1500 3700 30 WARD 1250 4000 14 rows selected.

Range Window Range windows 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. 314 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT ename, 2 hiredate,hiredate-100, 3 COUNT(*) 4 OVER(ORDER BY hiredate ASC 5 RANGE 100 PRECEDING) hirecnt 6 FROM EMP 7 ORDER BY hiredate ASC; ENAME HIREDATE HIREDATE---------- --------- --------- ---------SMITH 17-DEC-80 08-SEP-80 ALLEN 20-FEB-81 12-NOV-80 WARD 22-FEB-81 14-NOV-80 JONES 02-APR-81 23-DEC-80 BLAKE 01-MAY-81 21-JAN-81 CLARK 09-JUN-81 01-MAR-81 TURNER 08-SEP-81 31-MAY-81 MARTIN 28-SEP-81 20-JUN-81 KING 17-NOV-81 09-AUG-81 JAMES 03-DEC-81 25-AUG-81 FORD 03-DEC-81 25-AUG-81 MILLER 23-JAN-82 15-OCT-81 SCOTT 09-DEC-82 31-AUG-82 ADAMS 12-JAN-83 04-OCT-82 14 rows selected. SQL> SELECT ename,hiredate,sal, 2 AVG(Sal) 3 OVER(ORDER BY hiredate ASC 4 RANGE 100 PRECEDING) avgsal 5 FROM EMP 6 ORDER BY hiredate ASC; ENAME HIREDATE SAL AVGSAL ---------- --------- ---------- ---------SMITH 17-DEC-80 800 800 ALLEN 20-FEB-81 1600 1200 WARD 22-FEB-81 1250 1216.66667 JONES 02-APR-81 2975 1941.66667 BLAKE 01-MAY-81 2850 2168.75 CLARK 09-JUN-81 2450 2758.33333 TURNER 08-SEP-81 1500 1975 MARTIN 28-SEP-81 1250 1375 KING 17-NOV-81 5000 2583.33333 JAMES 03-DEC-81 950 2340 FORD 03-DEC-81 3000 2340 MILLER 23-JAN-82 1300 2562.5 SCOTT 09-DEC-82 3000 3000 ADAMS 12-JAN-83 1100 2050 14 rows selected. HIRECNT 1 2 3 3 4 3 2 2 3 5 5 4 1 2

Accessing Rows Around Current Row Lag Function 315 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Lag provides access to more than one row of a table at the same time without the use of self join. Given a series of rows returned from a query and a position of the cursor, lag function provides access to a row at a given offset prior to that position. If offset is not provided than default offset is considered as 1. The optional default value is returned if the offset goes beyond the scope of the window. If default is not specified, than the default is considered as null. Syntax LAG(ValueExpr(, offset)(, DEFAULT)) OVER((Query-Partition-Clause) ORDER BY CLAUSE) Lead Function Lead provides access to more than one row of a table at the same time without the use of a self join. Given a series of rows returned from a query and a position of the cursor, lead function provides access to a row at a given physical offset beyond that position. Syntax LEAD(ValueExpr(, offset)(, DEFAULT)) OVER((Query-partition-clause) ORDER BY CLAUSE) Illustration
SQL> SELECT ename,hiredate,sal, 2 LAG(sal,1,0) 3 OVER(ORDER BY hiredate) PerSal 4 FROM EMP; ENAME HIREDATE SAL PERSAL ---------- --------- ---------- ---------SMITH 17-DEC-80 800 0 ALLEN 20-FEB-81 1600 800 WARD 22-FEB-81 1250 1600 JONES 02-APR-81 2975 1250 BLAKE 01-MAY-81 2850 2975 CLARK 09-JUN-81 2450 2850 TURNER 08-SEP-81 1500 2450 MARTIN 28-SEP-81 1250 1500 KING 17-NOV-81 5000 1250 JAMES 03-DEC-81 950 5000 FORD 03-DEC-81 3000 950 MILLER 23-JAN-82 1300 3000 SCOTT 09-DEC-82 3000 1300 ADAMS 12-JAN-83 1100 3000 14 rows selected. SQL> SELECT ename,hiredate,sal, 2 LAG(sal,1,0) 3 OVER(ORDER BY hiredate) NextSal

316

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

4 FROM EMP; ENAME HIREDATE SAL NEXTSAL ---------- --------- ---------- ---------SMITH 17-DEC-80 800 0 ALLEN 20-FEB-81 1600 800 WARD 22-FEB-81 1250 1600 JONES 02-APR-81 2975 1250 BLAKE 01-MAY-81 2850 2975 CLARK 09-JUN-81 2450 2850 TURNER 08-SEP-81 1500 2450 MARTIN 28-SEP-81 1250 1500 KING 17-NOV-81 5000 1250 JAMES 03-DEC-81 950 5000 FORD 03-DEC-81 3000 950 MILLER 23-JAN-82 1300 3000 SCOTT 09-DEC-82 3000 1300 ADAMS 12-JAN-83 1100 3000 14 rows selected.

First Value Function FIRST_VALUE returns the first value in an ordered set of values. If the first value in the set is null, then the function returns null unless ignore nulls is specified. Ignore nulls setting is useful for data densification. If specified then FIRST_VALUE returns the first non-null value in the set, else null is returned. Syntax FIRST_VLAUE(EXPR IGNORE NULLS) OVER(Analytic_Clause) Last Value Function LAST_VALUE returns the last value in an ordered set of values. If the last value in the set is null, then the function returns null unless ignore nulls is specified. Ignore nulls setting is useful for data densification. If specified then LAST_VALUE returns the first non-null value in the set, else null is returned. Syntax LAST_VALUE (EXPR IGNORE NULLS) OVER(Analytic_Clause)

Illustration
SQL> SELECT ename,deptno,sal, 2 FIRST_VALUE(ename) 3 OVER(PARTITION BY deptno 4 ORDER BY Sal DESC) Max_Sal_Name 5 FROM EMP 6 ORDER BY deptno,ename;

317

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ENAME DEPTNO SAL MAX_SAL_NA ---------- ---------- ---------- ---------CLARK 10 2450 KING KING 10 5000 KING MILLER 10 1300 KING ADAMS 20 1100 FORD FORD 20 3000 FORD JONES 20 2975 FORD SCOTT 20 3000 FORD SMITH 20 800 FORD ALLEN 30 1600 BLAKE BLAKE 30 2850 BLAKE JAMES 30 950 BLAKE MARTIN 30 1250 BLAKE TURNER 30 1500 BLAKE WARD 30 1250 BLAKE 14 rows selected. SQL> SELECT ename,deptno,sal, 2 FIRST_VALUE(ename) 3 OVER(ORDER BY Sal ASC) Max_Sal_Name 4 FROM (SELECT * 5 FROM EMP 6 WHERE deptno=30); ENAME DEPTNO SAL MAX_SAL_NA ---------- ---------- ---------- ---------JAMES 30 950 JAMES MARTIN 30 1250 JAMES WARD 30 1250 JAMES TURNER 30 1500 JAMES ALLEN 30 1600 JAMES BLAKE 30 2850 JAMES 6 rows selected.

Row_Number Function The ROW_NUMBER function assigns a unique number sequentially, starting from 1, as defined by order by to each row within the partition. Syntax ROW_NUMBER () OVER([Query_Partition_Clause] ORDER_BY_CLAUSE )
SQL> SELECT 2 ROW_NUMBER() 3 OVER(PARTITION BY deptno 4 ORDER BY Sal DESC NULLS LAST) RowNo, 5 ename,sal,deptno,job 6 FROM EMP;

318

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ROWNO ENAME SAL DEPTNO ---------- ---------- ---------- ---------1 KING 5000 10 2 CLARK 2450 10 3 MILLER 1300 10 1 FORD 3000 20 2 SCOTT 3000 20 3 JONES 2975 20 4 ADAMS 1100 20 5 SMITH 800 20 1 BLAKE 2850 30 2 ALLEN 1600 30 3 TURNER 1500 30 4 MARTIN 1250 30 5 WARD 1250 30 6 JAMES 950 30 14 rows selected.

CROSSTAB OR PIVOT Queries A CORSSTAB query can be used to get a result with rows and columns in a matrix form.
SQL> SELECT deptno, 2 MAX(DECODE(seqno,1,ename,NULL)) First, 3 MAX(DECODE(seqno, 4 2,ename,NULL)) Second, 5 MAX(DECODE(seqno,3,ename,NULL)) Third 6 FROM (SELECT deptno,ename, 7 ROW_NUMBER() 8 OVER(PARTITION BY deptno 9 ORDER BY Sal DESC NULLS LAST) SeqNo 10 FROM EMP) 11 WHERE SeqNo<=3 12 GROUP BY deptno; DEPTNO FIRST SECOND THIRD ---------- ---------- ---------- ---------10 KING CLARK MILLER 20 FORD SCOTT JONES 30 BLAKE ALLEN TURNER 3 rows selected.

Centered SUM and Centered AVERAGE


SQL> SELECT ename, SUM(Sal) SalAmt, 2 ROUND(SUM(SUM(Sal)) 3 OVER(ORDER BY deptno 4 ROWS BETWEEN 5 1 PRECEDING AND 1 FOLLOWING),2) CSum, 6 ROUND(AVG(SUM(Sal)) 7 OVER(ORDER BY deptno

319

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

8 ROWS BETWEEN 9 1 PRECEDING AND 1 FOLLOWING),2) CAvg 10 FROM EMP 11 GROUP BY deptno,ename 12 ORDER BY deptno; ENAME SALAMT CSUM CAVG ---------- ---------- ---------- ---------CLARK 2450 7450 3725 KING 5000 8750 2916.67 MILLER 1300 7400 2466.67 ADAMS 1100 5400 1800 FORD 3000 7075 2358.33 JONES 2975 8975 2991.67 SCOTT 3000 6775 2258.33 SMITH 800 5400 1800 ALLEN 1600 5250 1750 BLAKE 2850 5400 1800 JAMES 950 5050 1683.33 MARTIN 1250 3700 1233.33 TURNER 1500 4000 1333.33 WARD 1250 2750 1375 14 rows selected.

Extra Stuff for Practice on Analytic Functions Create the Following Tables in the Same Order
SQL> CREATE TABLE itemtypes 2 ( 3 itemtypeid INTEGER 4 CONSTRAINT itemtypePK PRIMARY KEY, 5 itemtname VARCHAR2(10) 6 CONSTRAINT itemtnameNN NOT NULL 7 ); Table created. SQL> ED Wrote file afiedt.buf 1 CREATE TABLE items 2 ( 3 itemid INTEGER 4 CONSTRAINT itemidPK PRIMARY KEY, 5 itemtypeid INTEGER 6 CONSTRAINT itemtypeidFK 7 REFERENCES itemtypes(itemtypeid), 8 itemname VARCHAR2(10) 9 CONSTRAINT itemnameNN NOT NULL, 10 description VARCHAR2(100), 11 price NUMBER(5,2) 12* ) SQL> /

320

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Table created. SQL> CREATE TABLE divisions 2 ( 3 divid CHAR(3) 4 CONSTRAINT jobidPK PRIMARY KEY, 5 jobname VARCHAR2(20) 6 CONSTRAINT jobnameNN NOT NULL 7 ); Table created. SQL> CREATE TABLE divisions 2 ( 3 divid CHAR(3) 4 CONSTRAINT dividPK PRIMARY KEY, 5 divname VARCHAR2(15) 6 CONSTRAINT divnameNN NOT NULL 7 ); Table created. SQL> CREATE TABLE jobmaster 2 ( 3 jobid CHAR(3) 4 CONSTRAINT jobidPK PRIMARY KEY, 5 jobname VARCHAR2(20) 6 CONSTRAINT jobnameNN NOT NULL 7 ); Table created. SQL> CREATE TABLE EMPstores 2 ( 3 EMPid INTEGER 4 CONSTRAINT EMPstoresPK PRIMARY KEY, 5 divid CHAR(3) 6 CONSTRAINT dividFK REFERENCES divisions(divid), 7 jobid CHAR(3) 8 CONSTRAINT jobidFK REFERENCES jobmaster(jobid), 9 firstname VARCHAR2(10) 10 CONSTRAINT fnameNN NOT NULL, 11 lastname VARCHAR2(10) 12 CONSTRAINT lnameNN NOT NULL, 13 Sal NUMBER(6,0) 14 ); Table created. SQL> CREATE TABLE allsales 2 ( 3 year INTEGER CONSTRAINT yearNN NOT NULL, 4 month INTEGER CONSTRAINT monthNN NOT NULL,

321

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

5 itemtypeid INTEGER CONSTRAINT itemtidas 6 REFERENCES itemtypes(itemtypeid), 7 EMPid INTEGER 8 CONSTRAINT EMPidas REFERENCES EMPstores(EMPid), 9 saleamt NUMBER(8,2), 10 CONSTRAINT allsalesPK 11 PRIMARY KEY(year,month,itemtypeid,EMPid) 12 ); Table created.

Insert Sample Data into Itemtypes Table


SQL> INSERT INTO itemtypes(itemtypeid,itemtname) 2 VALUES(1,'book'); 1 row created. SQL> INSERT INTO itemtypes(itemtypeid,itemtname) 2 VALUES(2,'video'); 1 row created. SQL> INSERT INTO itemtypes(itemtypeid,itemtname) 2 VALUES(3,'dvd'); 1 row created. SQL> INSERT INTO itemtypes(itemtypeid,itemtname) 2 VALUES(4,'cd'); 1 row created. SQL> INSERT INTO itemtypes(itemtypeid,itemtname) 2 VALUES(5,'magazine'); 1 row created. SQL> COMMIT; Commit complete.

Insert Sample Data into Products Table


SQL> INSERT INTO 2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4 (1, 1,'modern science, a desc of modern science', 19.95); 1 row created. SQL> INSERT INTO 2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4 (2,1,'chemistry','introduction to chemistry',30.00);

322

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> Ed Wrote file afiedt.buf 1 INSERT INTO 2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4* (3,2,'supernova','a star explodes',25.99) SQL> / 1 row created. SQL> INSERT INTO 2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4 (4,2,'Tank War','Action move about a future war',13.95); 1 row created. SQL> INSERT INTO 2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4 (5,2,'Z files','Series on mysterious activites',49.99); 1 row created. SQL> INSERT INTO 2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4 (6,2,'2412: The return','Aliens return',14.95); 1 row created. SQL> Ed Wrote file afiedt.buf 1 INSERT INTO 2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4* (7,3,'Space force 9','Adventures of heroes',13.49) SQL> / 1 row created. SQL> INSERT INTO 2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4 (8,3,'From another planet','Alien from another planet lands on Earth',12.99); 1 row created. SQL> INSERT INTO

323

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4 (9,4,'classic Music','The best classical music',10.99); 1 row created. SQL> INSERT INTO 2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4 (10,4,'Pop 3','The best popular music',10.99); 1 row created. SQL> INSERT INTO 2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4 (11,4,'Creative Yell','Debut album',14.99); 1 row created. SQL> INSERT INTO 2 items(itemid,itemtypeid,itemname,description,price) 3 VALUES 4 (12,null,'My front line','Their greatest hits',13.49); 1 row created. SQL> commit; Commit complete.

Insert Sample Data Into Divisions Table


SQL> Ed Wrote file afiedt.buf 1 INSERT INTO divisions(divid,divname) 2* VALUES('sal','sales') SQL> / 1 row created. SQL> INSERT INTO divisions(divid,divname) 2 VALUES('ope','operations'); 1 row created. SQL> INSERT INTO divisions(divid,divname) 2 VALUES('sup','support'); 1 row created. SQL> INSERT INTO divisions(divid,divname) 2 VALUES('bus','business');

324

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> commit; Commit complete.

Insert Sample Data Into Jobs Table


SQL> Ed Wrote file afiedt.buf 1 INSERT INTO jobmaster(jobid,jobname) 2* VALUES('wor','worker') SQL> / 1 row created. SQL> INSERT INTO jobmaster(jobid,jobname) 2 VALUES('mgr','manager'); 1 row created. SQL> INSERT INTO jobmaster(jobid,jobname) 2 VALUES('eng','engineer'); 1 row created. SQL> INSERT INTO jobmaster(jobid,jobname) 2 VALUES('tec','technologist'); 1 row created. SQL> INSERT INTO jobmaster(jobid,jobname) 2 VALUES('pre','president'); 1 row created. SQL> commit; Commit complete.

Insert Sample Data Into EMPstores Table


SQL> Ed Wrote file afiedt.buf 1 INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4* VALUES(1,'bus','pre','james','smith',800000) SQL> / 1 row created.

325

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(2,'sal','mgr','ron','johnson',350000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(3,'sal','wor','fred','hobbs',140000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(4,'sup','mgr','susan','jones',200000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(5,'sal','wor','rob','green',350000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(6,'sup','wor','jane','brown',200000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(7,'sup','mgr','john','grey',265000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(8,'sup','wor','jean','blue',110000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(9,'sup','wor','henry','heyson',125000);

326

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(10,'ope','mgr','kevin','black',225000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(11,'ope','mgr','keith','long',165000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(12,'ope','wor','frank','howard',125000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(13,'ope','wor','doreen','penn',145000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(14,'bus','mgr','mark','smith',155000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(15,'bus','mgr','jill','jones',175000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(16,'ope','eng','megan','craig',245000); 1 row created. SQL> INSERT INTO 2 EMPstores

327

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(17,'sup','tec','matthew','brant',115000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(18,'ope','mgr','tony','clerke',200000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(19,'bus','mgr','tanya','conway',200000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(20,'ope','mgr','terry','cliff',215000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(21,'sal','mgr','steve','green',275000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(22,'sal','mgr','roy','red',375000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(23,'sal','mgr','sandra','smith',335000); 1 row created. SQL> Ed Wrote file afiedt.buf 1 INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4* VALUES(24,'sal','mgr','gail','silver',225000)

328

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> / 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(25,'sal','mgr','gerald','gOld',245000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(26,'sal','mgr','eileen','lane',235000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(27,'sal','mgr','doreen','upton',235000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(28,'sal','mgr','jack','ewing',235000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(29,'sal','mgr','paul','owens',245000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(30,'sal','mgr','melanle','york',255000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(31,'sal','mgr','tracy','yellow',225000); 1 row created. SQL> INSERT INTO

329

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(32,'sal','mgr','sarah','white',235000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(33,'sal','mgr','terry','iron',225000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(34,'sal','mgr','christine','brown',247000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(35,'sal','mgr','john','brown',249000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(36,'sal','mgr','kelvin','trenton',255000); 1 row created. SQL> INSERT INTO 2 EMPstores 3 (EMPid,divid,jobid,firstname,lastname,sal) 4 VALUES(37,'bus','wor','damon','jones',280000); 1 row created. SQL> commit; Commit complete.

Insert Sample Data Into Allsales Table


SQL> Ed Wrote file afiedt.buf 1 INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3* VALUES(21,1,2003,1,10034.84) SQL> /

330

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,1,2003,2,15144.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,1,2003,3,20137.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,1,2003,4,25057.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,1,2003,5,17214.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,1,2003,6,15564.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,1,2003,7,12654.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,1,2003,8,17434.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,1,2003,9,19854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,1,2003,10,21754.19);

331

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,1,2003,11,13029.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,1,2003,12,10034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,2,2003,1,1034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,2,2003,2,1544.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,2,2003,3,2037.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,2,2003,4,2557.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,2,2003,5,1714.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,2,2003,6,1564.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,2,2003,7,1264.84);

332

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,2,2003,8,1734.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,2,2003,10,2754.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,2,2003,11,1329.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,2,2003,12,1034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,1,6034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,2,1944.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,3,2537.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,4,4557.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,5,3714.564);

333

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,6,3564.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,7,21264.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,8,21734.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,9,12854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,10,32754.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,11,15329.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,3,2003,12,14034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,4,2003,1,3034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,4,2003,2,2944.65);

334

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,4,2003,3,5537.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,4,2003,4,3557.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,4,2003,5,2714.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,4,2003,6,7564.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,4,2003,7,1264.84); 1 row created. SQL> Ed Wrote file afiedt.buf 1 INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3* VALUES(21,4,2003,8,21734.82) SQL> / 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,4,2003,9,14854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,4,2003,10,22754.19); 1 row created.

335

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,4,2003,11,11329.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,4,2003,12,11034.84); 1 row created. SQL> commit; Commit complete. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,1,11034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,2,16144.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,3,24137.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,4,29057.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,5,19214.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,6,16564.64); 1 row created. SQL> INSERT INTO

336

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,7,13654.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,8,17834.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,9,21854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,10,18754.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,11,16529.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,1,2003,12,9434.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,1,1234.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,2,1044.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,3,2537.83); 1 row created. SQL> INSERT INTO

337

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,4,2657.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,5,1314.56); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,6,1264.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,7,1964.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,8,1234.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,9,1954.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,10,2254.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,11,1229.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,2,2003,12,1134.84); 1 row created. SQL> INSERT INTO

338

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,1,6334.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,2,1544.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,3,2737.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,4,4657.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,5,3714.56); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,6,3864.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,7,2726.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,8,17734.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,9,10854.57); 1 row created. SQL> INSERT INTO

339

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,10,15754.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,11,10329.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,3,2003,12,12034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,1,3334.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,2,2344.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,3,5137.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,4,3157.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,5,2114.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,6,7064.64); 1 row created. SQL> INSERT INTO

340

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,7,1564.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,8,12734.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,9,10854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,10,20754.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,11,10329.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,4,2003,12,2034.84); 1 row created. SQL> commit; Commit complete. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,1,4034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,2,7144.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,3,12137.83);

341

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,4,16057.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,5,13214.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,6,3564.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,7,7654.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,8,5834.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,9,6754.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,10,12534.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,11,2529.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,1,2003,12,7434.84);

342

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> commit; Commit complete. SQL> Ed Wrote file afiedt.buf 1 INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3* VALUES(23,2,2003,1,1234.84) SQL> / 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,2,2003,2,2244.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,2,2003,3,2137.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,2,2003,4,2357.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,2,2003,5,1314.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,2,2003,6,1364.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,2,2003,7,1364.84); 1 row created. SQL> INSERT INTO

343

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,2,2003,8,1334.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,2,2003,9,1354.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,2,2003,10,2354.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,2,2003,11,1329.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,2,2003,12,1334.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,1,6334.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,2,1344.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,3,2337.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,4,4357.45); 1 row created. SQL> INSERT INTO

344

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,5,3314.56); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,6,3364.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,7,23264.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,8,13734.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,9,13854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,10,13754.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,11,13329.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,3,2003,12,13034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,1,3334.84); 1 row created. SQL> INSERT INTO

345

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,2,2344.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,3,5337.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,4,3357.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,5,2314.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,6,7364.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,7,1364.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,8,13734.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,9,13854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,10,23754.19); 1 row created. SQL> INSERT INTO

346

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,11,13329.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,4,2003,12,2334.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,1,7034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,2,17144.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,3,22137.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,4,24057.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,5,25214.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,6,14564.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,7,17654.84); 1 row created. SQL> INSERT INTO

347

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,8,15834.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,9,15854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,10,22754.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,11,14529.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,1,2003,12,10434.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,1,1934.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,2,2844.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,3,2837.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,4,2697.45); 1 row created. SQL> INSERT INTO

348

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,5,7314.56); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,6,1864.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,7,2364.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,8,4334.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,9,6654.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,10,2254.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,11,5429.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,2,2003,12,3334.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,1,2334.84); 1 row created. SQL> INSERT INTO

349

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,2,4544.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,3,6337.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,4,3357.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,5,2314.56); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,6,1364.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,7,5264.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,8,1734.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,9,1854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,10,1354.19); 1 row created. SQL> INSERT INTO

350

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,11,1332.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,3,2003,12,3034.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,4,2003,1,3364.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,4,2003,2,4344.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,4,2003,3,4337.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,4,2003,4,2357.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,4,2003,5,6314.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,4,2003,6,4364.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,4,2003,7,2364.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt)

351

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 VALUES(24,4,2003,8,3734.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,4,2003,9,3854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,4,2003,10,3754.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,4,2003,11,1329.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,4,2003,12,7334.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,1,2003,1,1234.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,1,2003,2,6144.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,1,2003,3,8137.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,1,2003,4,14057.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt)

352

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 VALUES(25,1,2003,5,12214.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,1,2003,6,4564.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,1,2003,7,5654.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,1,2003,8,8834.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,1,2003,9,10854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,1,2003,10,12754.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,1,2003,11,5329.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,1,2003,12,5434.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,2,2003,1,3434.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt)

353

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 VALUES(25,2,2003,2,1844.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,2,2003,3,2137.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,2,2003,4,1697.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,2,2003,5,4314.56); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,2,2003,6,3264.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,2,2003,7,5364.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,2,2003,8,3334.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,2,2003,9,2654.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,2,2003,10,454.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt)

354

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 VALUES(25,2,2003,11,2429.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,2,2003,12,1334.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,3,2003,1,1434.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,3,2003,2,3544.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,3,2003,3,1337.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,3,2003,4,1457.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,3,2003,5,1314.56); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,3,2003,6,4364.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,3,2003,7,1264.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt)

355

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 VALUES(25,3,2003,8,2734.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,3,2003,9,4354.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,3,2003,10,2354.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,3,2003,11,3432.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,3,2003,12,1534.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,4,2003,1,1164.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,4,2003,2,2144.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,4,2003,3,4337.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,4,2003,4,1357.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt)

356

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 VALUES(25,4,2003,5,2314.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,4,2003,6,2364.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,4,2003,7,3264.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,4,2003,8,2234.82); 1 row created. SQL> Ed Wrote file afiedt.buf 1 INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3* VALUES(25,4,2003,9,3454.57) SQL> / 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,4,2003,10,2754.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,4,2003,11,3429.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,4,2003,12,4334.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,1,5534.84);

357

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,2,8844.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,3,5137.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,4,12057.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,5,10214.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,6,2564.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,7,3654.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,8,9834.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,9,9854.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,10,16754.27);

358

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,11,5529.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,1,2003,12,3434.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,1,5434.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,2,3844.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,3,5137.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,4,3697.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,5,2314.56); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,6,5264.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,7,3364.84);

359

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,8,4334.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,9,4654.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,10,3454.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,11,4429.19); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,2,2003,12,4334.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,1,2434.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,2,2544.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,3,5337.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,4,5457.45);

360

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,5,4314.56); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,6,3364.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,7,3264.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,8,4734.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,9,2354.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,10,4354.34); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,11,2432.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,3,2003,12,4534.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,1,3164.23);

361

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,2,3144.65); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,3,6337.83); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,4,2357.45); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,5,4314.564); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,6,4364.64); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,7,2264.84); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,8,4234.82); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,9,2454.57); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,10,1554.19);

362

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,11,2429.73); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,4,2003,12,3334.85); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,1,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,2,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,3,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,4,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,5,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,6,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,7,null);

363

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,8,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,9,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,10,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,11,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(21,5,2003,12,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,1,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,2,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,3,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,4,null);

364

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,5,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,6,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,7,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,8,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,9,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,10,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,11,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(22,5,2003,12,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,1,null);

365

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,2,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,3,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,4,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,5,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,6,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,7,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,8,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,9,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,10,null);

366

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,11,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(23,5,2003,12,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,1,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,2,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,3,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,4,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,5,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,6,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,7,null);

367

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,8,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,9,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,10,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,11,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(24,5,2003,12,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,1,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,2,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,3,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,4,null);

368

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,5,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,6,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,7,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,8,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,9,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,10,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,11,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(25,5,2003,12,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,1,null);

369

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,2,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,3,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,4,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,5,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,6,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,7,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,8,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,9,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,10,null);

370

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,11,null); 1 row created. SQL> INSERT INTO 2 allsales(EMPid,itemtypeid,year,month,saleamt) 3 VALUES(26,5,2003,12,null); 1 row created. SQL> select*from itemtypes; ITEMTYPEID ITEMTNAME ---------- ---------1 book 2 video 3 DVD 4 cd 5 magazines 5 rows selected. SQL> select*from items; ITEMID ITEMTYPEID ITEMNAME ---------- ---------- -----------------------------DESCRIPTION ----------------------------------------------------------------------------------------------2 1 chemistry Introduction to chemistry 3 2 supernova A star explodes 1 1 modern science A desc of modern science 4 2 Tank War Action move about a future war 5 2 Z files Series on mysterious activates 6 2 2412: The return Aliens return 7 3 Space force 9 Adventures of heroes

371

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

8 3 from another planet Alien from another planet lands on Earth 9 4 classic Music The best classical music 10 4 Pop 3 The best popular music 11 4 Creative Yell Debut album 12 My front line Their greatest hits 12 rows selected. SQL> select*from DIVISIONS DIV DIVNAME --- --------------Sal sales Ope operations Sup support Bus business 4 rows selected. SQL> select*from JOBMASTER; JOB JOBNAME --- -------------------Wor worker Mgr manager Eng engineer Tec technologist Pre president 5 rows selected. SQL> select*from EMPSTORES; EMPID DIV JOB FIRSTNAME LASTNAME ---------- --- --- ---------- ---------- ---------1 bus pre James smith 800000 2 Sal mgr Ron Johnson 350000 3 Sal wor Fred Hobbs 140000 4 sup mgr Susan jones 200000 5 Sal wor rob green 350000 6 sup wor Jane brown 200000 7 sup mgr john grey 265000 8 sup wor jean blue 110000 9 sup wor henry heyson 125000 SAL ;

372

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

10 ope mgr Kevin black 225000 11 ope mgr Keith long 165000 12 ope wor frank Howard 125000 13 ope wor Doreen penn 145000 14 bus mgr mark smith 155000 15 bus mgr jill jones 175000 16 ope eng Megan Craig 245000 17 sup tec Matthew brant 115000 18 ope mgr tony clerke 200000 19 bus mgr Tanya Conway 200000 20 ope mgr terry cliff 215000 21 Sal mgr Steve green 275000 22 Sal mgr Roy red 375000 23 Sal mgr Sandra smith 335000 24 Sal mgr Gail silver 225000 25 Sal mgr Gerald gOld 245000 26 Sal mgr Eileen lane 235000 27 Sal mgr Doreen Upton 235000 28 Sal mgr jack Ewing 235000 29 Sal mgr Paul Owens 245000 30 Sal mgr melanle York 255000 31 Sal mgr Tracy yellow 225000 32 Sal mgr Sarah white 235000 33 Sal mgr terry iron 225000 34 Sal mgr Christine brown 247000 35 Sal mgr john brown 249000 36 Sal mgr kelvin Trenton 255000 37 bus wor Damon jones 280000 37 rows selected. SQL> select*from ALLSALES ; SALEAMT

YEAR MONTH ITEMTYPEID EMPID ---------- ---------- ---------- ---------- ---------2003 1 3 22 6334.84 2003 2 3 22 1544.65 2003 3 3 22 2737.83 2003 4 3 22 4657.45 2003 5 3 22 3714.56 2003 6 3 22 3864.64 2003 7 3 22 2726.84 2003 8 3 22 17734.82 2003 9 3 22 10854.57 2003 10 3 22 15754.19 2003 11 3 22 10329.73 2003 12 3 22 12034.84 2003 1 4 22 3334.84 2003 2 4 22 2344.65 2003 3 4 22 5137.83 2003 4 4 22 3157.45 2003 5 4 22 2114.56 2003 6 4 22 7064.64 2003 7 4 22 1564.84

373

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003

8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1

4 4 4 4 4 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 1

22 22 22 22 22 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 24

12734.82 10854.57 20754.19 10329.73 2034.84 4034.84 7144.65 12137.83 16057.45 13214.56 3564.64 7654.84 5834.82 6754.57 12534.19 2529.73 7434.84 1234.84 2244.65 2137.83 2357.45 1314.64 1364.64 1364.84 1334.82 1354.57 2354.19 1329.73 1334.84 6334.84 1344.65 2337.83 4357.45 3314.56 3364.64 23264.84 13734.82 13854.57 13754.19 13329.73 13034.84 3334.84 2344.65 5337.83 3357.45 2314.56 7364.64 1364.84 13734.82 13854.57 23754.19 13329.73 2334.84 7034.84

374

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003

2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7

1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 1 1 1 1 1 1 1

24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 25 25 25 25 25 25 25

17144.65 22137.83 24057.45 25214.56 14564.64 17654.84 15834.82 15854.57 22754.19 14529.73 10434.84 1934.84 2844.65 2837.83 2697.45 7314.56 1864.64 2364.84 4334.82 6654.57 2254.19 5429.73 3334.84 2334.84 4544.65 6337.83 3357.45 2314.56 1364.64 5264.84 1734.82 1854.57 1354.19 1332.73 3034.84 3364.84 4344.65 4337.83 2357.45 6314.64 4364.64 2364.84 3734.82 3854.57 3754.19 1329.84 7334.84 1234.84 6144.65 8137.83 14057.45 12214.56 4564.64 5654.84

375

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003

8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3

1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3

25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25

8834.82 10854.57 12754.19 5329.73 5434.84 3434.84 1844.65 2137.83 1697.45 4314.56 3264.64 5364.84 3334.82 2654.57 454.19 2429.73 1334.84 1434.84 3544.65 1337.83 SALEAMT

YEAR MONTH ITEMTYPEID EMPID ---------- ---------- ---------- ---------- ---------2003 4 3 25 1457.45 2003 5 3 25 1314.56 2003 6 3 25 4364.64 2003 7 3 25 1264.84 2003 8 3 25 2734.82 2003 9 3 25 4354.57 2003 10 3 25 2354.19 2003 11 3 25 3432.73 2003 12 3 25 1534.84 2003 1 4 25 1164.84 2003 2 4 25 2144.65 2003 3 4 25 4337.83 2003 4 4 25 1357.45 2003 5 4 25 2314.56 2003 6 4 25 2364.64 2003 7 4 25 3264.84 2003 8 4 25 2234.82 2003 9 4 25 3454.57 2003 10 4 25 2754.19 2003 11 4 25 3429.73 2003 12 4 25 4334.84 2003 1 1 26 5534.84 2003 2 1 26 8844.65 2003 3 1 26 5137.83 2003 4 1 26 12057.45 2003 5 1 26 10214.56 2003 6 1 26 2564.64 2003 7 1 26 3654.84 2003 8 1 26 9834.57 2003 9 1 26 9854.57 2003 10 1 26 16754.27

376

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003

11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4

1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5

26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 21 21 21 21 21 21 21 21 21 21 21 21 22 22 22 22

5529.73 3434.84 5434.84 3844.65 5137.83 3697.45 2314.56 5264.64 3364.84 4334.82 4654.57 3454.19 4429.19 4334.84 2434.84 2544.65 5337.83 5457.45 4314.56 3364.64 3264.84 4734.82 2354.57 4354.34 2432.73 4534.84 3164.23 3144.65 6337.83 2357.45 4314.56 4364.64 2264.84 4234.82 2454.57 1554.19 2429.73 3334.85

377

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003

5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10

5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5

22 22 22 22 22 22 22 22 23 23 23 23 23 23 23 23 23 23 23 23 24 24 24 24 24 24 24 24 24 24 24 24 25 25 25 25 25 25 25 25 25 25 25 25 26 26 26 26 26 26 26 26 26 26

378

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2003 2003 2003 2003 2003 2003 2003 2003

11 12 1 2 3 4 5 6

5 5 4 4 4 4 4 4

26 26 21 21 21 21 21 21

3034.84 2944.65 5537.83 3557.45 2714.56 7564.64 SALEAMT

YEAR MONTH ITEMTYPEID EMPID ---------- ---------- ---------- ---------- ---------2003 7 4 21 1264.84 2003 8 4 21 21734.82 2003 9 4 21 14854.57 2003 10 4 21 22754.19 2003 11 4 21 11329.73 2003 12 4 21 11034.84 2003 1 1 22 11034.84 2003 2 1 22 16144.65 2003 3 1 22 24137.83 2003 4 1 22 29057.45 2003 5 1 22 19214.56 2003 6 1 22 16564.64 2003 7 1 22 13654.84 2003 8 1 22 17834.82 2003 9 1 22 21854.57 2003 10 1 22 18754.19 2003 11 1 22 16529.73 2003 12 1 22 9434.83 2003 1 2 22 1234.84 2003 2 2 22 1044.65 2003 3 2 22 2537.83 2003 4 2 22 2657.45 2003 5 2 22 1314.56 2003 6 2 22 1264.64 2003 7 2 22 1964.84 2003 8 2 22 1234.82 2003 9 2 22 1954.57 2003 10 2 22 2254.19 2003 11 2 22 1229.73 2003 12 2 22 1134.84 2003 1 1 21 10034.84 2003 2 1 21 15144.65 2003 3 1 21 20137.83 2003 4 1 21 25057.45 2003 5 1 21 17214.56 2003 6 1 21 15564.64 2003 7 1 21 12654.84 2003 8 1 21 17434.82 2003 9 1 21 19854.57 2003 11 1 21 13029.73 2003 12 1 21 10034.84 2003 1 2 21 1034.84 2003 2 2 21 1544.65

379

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003 2003

3 4 5 6 7 8 9 10 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12

2 2 2 2 2 2 2 1 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3

21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21

2037.83 2557.45 1714.56 1564.64 1264.84 1734.82 1854.57 21754.19 2754.19 1329.73 1034.84 6034.84 1944.65 2537.83 4557.45 3714.56 3564.64 21264.84 21734.82 12854.57 32754.19 15329.73 14034.84

360 rows selected.

Illustrative examples on the above Database Ranking Functions The different tpyes of ranking functions are 1. Rnak() Function . It returns the rank of items in a group. . Rank () leaves a gap in the sequence of rankings in the event of a tie. 2. Dense Rank() Function . It returns the rank of items in a group. . DENSE_RANK () doesnt leave a gap in the sequence of ranking in the vent of tie.
SQL> SELECT itemtypeid, SUM (saleamt), 2 RANK () 3 OVER (ORDER BY SUM (saleamt) DESC) Rank, 4 DENSE_RANK () 5 OVER (ORDER BY SUM (saleamt) DESC) Dense_Rank 6 FROM allsales 7 WHERE year=2003 AND saleamt IS NOT NULL 8 GROUP BY itemtypeid 9 ORDER BY itemtypeid; ITEMTYPEID SUM (SALEAMT) RANK DENSE_RANK ---------- ------------ ---------- ---------1 906881.58 1 1 2 186381.3 4 4 3 453732.91 2 2

380

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

402751.35

4 rows selected.

Partition by Clause The clause is used to divide groups into subgroups.


SQL> SELECT itemtypeid, month, SUM (saleamt), 2 RANK () 3 OVER (PARTITION BY month 4 ORDER BY SUM (saleamt) DESC) Rank 5 FROM allsales 6 WHERE year=2003 AND saleamt IS NOT NULL 7 GROUP BY itemtypeid, month 8 ORDER BY itemtypeid, month; ITEMTYPEID MONTH SUM (SALEAMT) ---------- ---------- ------------ ---------1 1 38909.04 1 1 2 70567.9 1 1 3 91826.98 1 1 4 120344.7 1 1 5 97287.36 1 1 6 57387.84 1 1 7 60929.04 1 1 8 75608.67 1 1 9 85027.42 1 1 10 105305.22 1 1 11 57478.38 1 1 12 46209.03 2 2 1 14309.04 4 2 2 13367.9 4 2 3 16826.98 4 2 4 15664.7 4 2 5 18287.44 4 2 6 14587.84 4 2 7 15689.04 3 2 8 16308.92 4 2 9 19127.42 4 2 10 13525.14 4 2 11 16177.84 4 2 12 12509.04 4 3 1 24909.04 2 3 2 15467.9 3 3 3 20626.98 3 3 4 23844.7 2 3 5 18687.36 3 3 6 19887.84 3 3 7 57051.04 2 3 8 62408.92 2 3 9 46127.42 3 3 10 70325.29 3 3 11 46187.38 2 3 12 48209.04 1 RANK

381

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

4 4 4 4 4 4 4 4 4 4 4 4

1 2 3 4 5 6 7 8 9 10 11 12

17398.43 17267.9 31026.98 16144.7 20087.44 33087.84 12089.04 58408.92 49327.42 75325.14 42178.49 30409.05

3 2 2 3 2 2 4 3 2 2 3 3

48 rows selected.

Applying Rollup, Cube and GROUPING Sets


SQL> SELECT itemtypeid, EMPid, SUM (saleamt), 2 RANK () 3 OVER (ORDER BY SUM (saleamt) DESC) Rank 4 FROM allsales 5 WHERE year=2003 6 GROUP BY CUBE (itemtypeid, EMPid) 7 ORDER BY itemtypeid, EMPid; ITEMTYPEID EMPID SUM (SALEAMT) ---------- ---------- ------------ ---------1 21 197916.96 19 1 22 214216.95 17 1 23 98896.96 25 1 24 207216.96 18 1 25 95216.96 26 1 26 93416.79 27 1 906881.58 9 2 21 20426.96 40 2 22 19826.96 41 2 23 19727.04 42 2 24 43866.96 34 2 25 32266.96 38 2 26 50266.42 31 2 186381.3 21 3 21 140326.96 22 3 22 92288.96 29 3 23 112026.96 23 3 24 34829.96 36 3 25 29129.96 39 3 26 45130.11 33 3 453732.91 11 4 21 108326.96 24 4 22 81426.96 30 4 23 92426.96 28 4 24 47457.15 32 4 25 33156.96 37 RANK

382

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

4 4 5 5 5 5 5 5 5

26 21 22 23 24 25 26

39956.36 402751.35 1 1 1 1 1 1 1 466997.84 407759.83 323077.92 333371.03 189770.84 228769.68 1949747.14

35 13

21 22 23 24 25 26

10 12 15 14 20 16 8

42 rows selected. SQL> SELECT itemtypeid, EMPid, SUM (saleamt), 2 RANK () 3 OVER (ORDER BY SUM (saleamt) DESC) Rank 4 FROM allsales 5 WHERE year=2003 6 GROUP BY GROUPING SETS (itemtypeid, EMPid) 7 ORDER BY itemtypeid, EMPid; ITEMTYPEID EMPID SUM (SALEAMT) ---------- ---------- ------------ ---------1 906881.58 2 2 186381.3 11 3 453732.91 4 4 402751.35 6 5 1 21 466997.84 3 22 407759.83 5 23 323077.92 8 24 333371.03 7 25 189770.84 10 26 228769.68 9 11 rows selected. SQL> ED Wrote file afiedt.buf 1 SELECT itemtypeid, SUM (saleamt), 2 RANK () 3 OVER (ORDER BY SUM (saleamt) DESC) Rank 4 FROM allsales 5 WHERE year=2003 6 GROUP BY ROLLUP (itemtypeid) 7* ORDER BY itemtypeid SQL> / RANK

383

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ITEMTYPEID SUM (SALEAMT) ---------- ------------ ---------1 906881.58 3 2 186381.3 6 3 453732.91 4 4 402751.35 5 5 1 1949747.14 2 6 rows selected. SQL> ED Wrote file afiedt.buf

RANK

1 SELECT itemtypeid, SUM (saleamt), 2 RANK () 3 OVER (ORDER BY SUM (saleamt) DESC) Rank, 4 DENSE_RANK () 5 OVER (ORDER BY SUM (saleamt) DESC) Dense_Rank 6 FROM allsales 7 WHERE year=2003 8 GROUP BY itemtypeid 9* ORDER BY itemtypeid SQL> / ITEMTYPEID SUM (SALEAMT) RANK DENSE_RANK ---------- ------------ ---------- ---------1 906881.58 2 2 2 186381.3 5 5 3 453732.91 3 3 4 402751.35 4 4 5 1 1 5 rows selected.

Nulls First and Nulls Last Clause


SQL> Ed Wrote file afiedt.buf 1 SELECT itemtypeid, SUM (saleamt), 2 RANK () 3 OVER (ORDER BY SUM (saleamt) DESC NULLS LAST) Rank, 4 DENSE_RANK () 5 OVER (ORDER BY SUM (saleamt) DESC NULLS LAST) Dense_Rank 6 FROM allsales 7 WHERE year=2003 8 GROUP BY itemtypeid 9* ORDER BY itemtypeid SQL> / ITEMTYPEID SUM (SALEAMT) ---------- ------------ ---------- ---------RANK DENSE_RANK

384

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 2 3 4 5

906881.58 186381.3 453732.91 402751.35 5

1 4 2 3 5

1 4 2 3

5 rows selected.

CUME Dist () Function It returns the position of a specified value relative to a group of values. The function represents the cumulative distribution of the data. Percent Rank () Function It returns the percent rank of value relative to a group by values.
SQL> Ed Wrote file afiedt.buf 1 SELECT itemtypeid, SUM (saleamt), 2 CUME_DIST () 3 OVER (ORDER BY SUM (saleamt) DESC) Cumulative, 4 PERCENT_RANK () 5 OVER (ORDER BY SUM (saleamt) DESC) Percent 6 FROM allsales 7 WHERE year=2003 8 GROUP BY itemtypeid 9* ORDER BY itemtypeid SQL> / ITEMTYPEID SUM (SALEAMT) CUMULATIVE ---------- ------------ ---------- ---------1 906881.58 .4 .25 2 186381.3 1 1 3 453732.91 .6 .5 4 402751.35 .8 .75 5 .2 0 5 rows selected. PERCENT

NTILE () Function The NTILE (Buckets) is used to calculate n-tiles. Bucket specifies the number of buckets into which group of rows are placed.
SQL> ED Wrote file afiedt.buf 1 SELECT itemtypeid, SUM (saleamt), 2 NTILE (4) 3 OVER (ORDER BY SUM (saleamt) DESC) AS Ntile 4 FROM allsales 5 WHERE year=2003 AND saleamt IS NOT NULL 6 GROUP BY itemtypeid 7* ORDER BY itemtypeid SQL> /

385

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

ITEMTYPEID SUM (SALEAMT) ---------- ------------ ---------1 906881.58 1 2 186381.3 4 3 453732.91 2 4 402751.35 3 4 rows selected.

NTILE

Row Number () Function The function is used to return a number with each row in a group. The row number starts at 1.
SQL> Ed Wrote file afiedt.buf 1 SELECT itemtypeid, SUM (saleamt), 2 ROW_NUMBER () 3 OVER (ORDER BY SUM (saleamt) DESC) Row_Number 4 FROM allsales 5 WHERE year=2003 6 GROUP BY itemtypeid 7* ORDER BY itemtypeid SQL> / ITEMTYPEID SUM (SALEAMT) ROW_NUMBER ---------- ------------ ---------1 906881.58 2 2 186381.3 5 3 453732.91 3 4 402751.35 4 5 1 5 rows selected.

Inverse Percentage Function These functions are used to get the value corresponding to a percentile. The types of inverse percentile functions are Percentile Dist () It examines the cumulative distribution values in each group until it finds one that is greater than or equal to x. Percentile Cont () It examines the percent rank values in each group until it finds one that is greater than or equal to x.
SQL> Ed Wrote file afiedt.buf 1 SELECT 2 PERCENTILE_CONT (0.6) 3 WITHIN GROUP (ORDER BY SUM (saleamt) DESC) Percentile_Cont, 4 PERCENTILE_DIST (0.6) 5 WITHIN GROUP (ORDER BY SUM (saleamt) DESC) Percentile_Dist 6 FROM allsales 7 WHERE year=2003

386

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

8* GROUP BY itemtypeid SQL> / WITHIN GROUP (ORDER BY SUM (saleamt) DESC) Percentile_Dist * ERROR at line 5: ORA-00923: FROM keyword not found where expected

Window Function The window functions are used to calculate cumulative sums and moving averages within a specified range of rows. Calculating Cumulative Sum
SQL> Ed Wrote file afiedt.buf 1 SELECT month, SUM (saleamt) MonthlyAmt, 2 SUM (SUM (saleamt)) OVER 3 (ORDER BY month 4 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) CumulativeAmount 5 FROM allsales 6 GROUP BY month 7* ORDER BY month SQL> / MONTH MONTHLYAMT CUMULATIVEAMOUNT ---------- ---------- ---------------1 95525.55 95525.55 2 116671.6 212197.15 3 160307.92 372505.07 4 175998.8 548503.87 5 154349.6 702853.47 6 124951.36 827804.83 7 145758.16 973562.99 8 212735.43 1186298.42 9 199609.68 1385908.1 10 264480.79 1650388.89 11 162022.09 1812410.98 12 137336.16 1949747.14 12 rows selected.

Unbounded Proceeding Specifies that the window starts at the first row of the partition. Unbounded Following Specifies that the window starts at the last row of the partition. Current Row Specifies that the window begins at the current row or value.
SQL> Ed Wrote file afiedt.buf

387

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 SELECT month, SUM (saleamt) MonthlyAmt, 2 SUM (SUM (saleamt)) OVER 3 (ORDER BY month 4 ROWS UNBOUNDED PRECEDING) CumulativeAmount 5 FROM allsales 6 WHERE year=2003 AND month BETWEEN 6 AND 12 7 GROUP BY month 8* ORDER BY month SQL> / MONTH MONTHLYAMT CUMULATIVEAMOUNT ---------- ---------- ---------------6 124951.36 124951.36 7 145758.16 270709.52 8 212735.43 483444.95 9 199609.68 683054.63 10 264480.79 947535.42 11 162022.09 1109557.51 12 137336.16 1246893.67 7 rows selected.

Calculating Moving Averages


SQL> Ed Wrote file afiedt.buf 1 SELECT month, SUM (saleamt) MonthlyAmt, 2 AVG (SUM (saleamt)) OVER 3 (ORDER BY month 4 ROWS BETWEEN 3 AND 5 CURRENT ROW) MovingAverage 6 FROM allsales 7 WHERE year=2003 8 GROUP BY month 9* ORDER BY month SQL> / ROWS BETWEEN 3 AND * ERROR at line 4: ORA-00905: missing keyword

Calculating Centered Average


SQL> Ed Wrote file afiedt.buf 1 SELECT month, SUM (saleamt) MonthlyAmt, 2 AVG (SUM (saleamt)) 3 OVER (ORDER BY month 4 ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) MovAvg 5 FROM allsales 6 WHERE year=2003 7 GROUP BY month

388

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

8* ORDER BY month SQL> / MONTH MONTHLYAMT MOVAVG ---------- ---------- ---------1 95525.55 106098.575 2 116671.6 124168.357 3 160307.92 150992.773 4 175998.8 163552.107 5 154349.6 151766.587 6 124951.36 141686.373 7 145758.16 161148.317 8 212735.43 186034.423 9 199609.68 225608.633 10 264480.79 208704.187 11 162022.09 187946.347 12 137336.16 149679.125 12 rows selected.

Dis [lay First and Last Rows Using First Value () and Last Value ()
SQL> Ed Wrote file afiedt.buf 1 SELECT month, SUM (saleamt) MonthlyAmt, 2 FIRST_VALUE (SUM (saleamt)) 3 OVER (ORDER BY month 4 ROWS BETWEEN 5 1 PRECEDING AND 6 1 FOLLOWING) PRVMonthAmt, 7 LAST_VALUE (SUM (saleamt)) 8 OVER (ORDER BY month 9 ROWS BETWEEN 10 1 PRECEDING AND 11 1 FOLLOWING) NXTMonthAmt 12 FROM allsales 13 WHERE year=2003 14 GROUP BY month 15* ORDER BY month SQL> / MONTH MONTHLYAMT PRVMONTHAMT NXTMONTHAMT ---------- ---------- ----------- ----------1 95525.55 95525.55 116671.6 2 116671.6 95525.55 160307.92 3 160307.92 116671.6 175998.8 4 175998.8 160307.92 154349.6 5 154349.6 175998.8 124951.36 6 124951.36 154349.6 145758.16 7 145758.16 124951.36 212735.43 8 212735.43 145758.16 199609.68 9 199609.68 212735.43 264480.79 10 264480.79 199609.68 162022.09

389

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

11 162022.09 264480.79 137336.16 12 137336.16 162022.09 137336.16 12 rows selected.

Working with Reporting Functions The reporting function can be used to perform calculations across groups and partitions within groups.
SQL> Ed Wrote file afiedt.buf 1 SELECT month, itemtypeid, 2 SUM (SUM (saleamt)) 3 OVER (PARTITION BY month) ToT_Month_Amt, 4 SUM (SUM (saleamt)) 5 OVER (PARTITION BY itemtypeid) Tot_Pesd_Type_Amt 6 FROM allsales 7 WHERE year=2003 AND month<=3 8 GROUP BY month, itemtypeid 9* ORDER BY month, itemtypeid SQL> / MONTH ITEMTYPEID TOT_MONTH_AMT TOT_PESD_TYPE_AMT ---------- ---------- ------------- ----------------1 1 95525.55 201303.92 1 2 95525.55 44503.92 1 3 95525.55 61003.92 1 4 95525.55 65693.31 1 5 95525.55 2 1 116671.6 201303.92 2 2 116671.6 44503.92 2 3 116671.6 61003.92 2 4 116671.6 65693.31 2 5 116671.6 3 1 160307.92 201303.92 3 2 160307.92 44503.92 3 3 160307.92 61003.92 3 4 160307.92 65693.31 3 5 160307.92 15 rows selected.

Ratio to Report () Function The function is used to compute the ratio of a value to the sum of a set of values.
SQL> Ed Wrote file afiedt.buf

390

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 SELECT month, itemtypeid, SUM (saleamt) Itemtypeamt, 2 RATIO_TO_REPORT (SUM (saleamt)) 3 OVER (PARTITION BY month) ProtypeRatio 4 FROM allsales 5 WHERE year=2003 AND month<=3 6 GROUP BY month, itemtypeid 7* ORDER BY month, itemtypeid SQL> / MONTH ITEMTYPEID ITEMTYPEAMT PROTYPERATIO ---------- ---------- ----------- -----------1 1 38909.04 .40731553 1 2 14309.04 .149792804 1 3 24909.04 .260757881 1 4 17398.43 .182133785 1 5 2 1 70567.9 .604842138 2 2 13367.9 .114577155 2 3 15467.9 .132576394 2 4 17267.9 .148004313 2 5 3 1 91826.98 .57281624 3 2 16826.98 .104966617 3 3 20626.98 .128670998 3 4 31026.98 .193546145 3 5 15 rows selected.

Lag () and Lead () Function They function is used to compute the ratio of a value to the sum of a set of values.
SQL> Ed Wrote file afiedt.buf 1 SELECT month, 2 SUM (saleamt) MonthAmt, 3 LAG (SUM (saleamt), 1) 4 OVER (ORDER BY month) PrevMthAmt, 5 LEAD (SUM (saleamt), 1) 6 OVER (ORDER BY Month) NextMthAmt 7 FROM allsales 8 WHERE year=2003 AND month<=3 9 GROUP BY month 10* ORDER BY month SQL> / MONTH MONTHAMT PREVMTHAMT NEXTMTHAMT ---------- ---------- ---------- ---------1 95525.55 116671.6 2 116671.6 95525.55 160307.92 3 160307.92 116671.6 3 rows selected.

391

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> ED Wrote file afiedt.buf 1 SELECT month, 2 SUM (saleamt) MonthAmt, 3 AVG (SUM (saleamt)) 4 OVER (ORDER BY month) PrevMthAmt, 5 LEAD (SUM (saleamt), 1) 6 OVER (ORDER BY Month) NextMthAmt 7 FROM allsales 8 WHERE year=2003 AND month<=3 9 GROUP BY month 10* ORDER BY month SQL> / MONTH MONTHAMT PREVMTHAMT NEXTMTHAMT ---------- ---------- ---------- ---------1 95525.55 95525.55 116671.6 2 116671.6 106098.575 160307.92 3 160307.92 124168.357 3 rows selected. SQL> ED Wrote file afiedt.buf 1 SELECT month, 2 SUM (saleamt) MonthAmt, 3 LEAD (SUM (saleamt)) 4 OVER (ORDER BY month) PrevMthAmt, 5 LAG (SUM (saleamt), 1) 6 OVER (ORDER BY Month) NextMthAmt 7 FROM allsales 8 WHERE year=2003 AND month<=3 9 GROUP BY month 10* ORDER BY month SQL> / MONTH MONTHAMT PREVMTHAMT NEXTMTHAMT ---------- ---------- ---------- ---------1 95525.55 116671.6 2 116671.6 160307.92 95525.55 3 160307.92 116671.6 3 rows selected. SQL> SELECT MIN (month) 2 KEEP (DENSE_RANK FIRST ORDER BY SUM (saleamt)) LowestSalMonth 3 FROM allsales 4 WHERE year=2003 5 GROUP BY month 6 ORDER BY month; LOWESTSALMONTH

392

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

-------------1 1 row selected.

Data Updating and Deletion

393

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Updating the Data in a Table The update statement is used to change the existing values in a table or in the base table of view. It can be used to update the master table of materialized view. Prerequisites The table must be in the own schema. Update object privilege should be available. Syntax: SQL>UPDATE<Table_Name> SET<Specification> WHERE CLAUSE;
SQL> UPDATE EMP 2 SET comm=NULL 3 WHERE job='CLERK'; 4 rows updated. SQL> UPDATE EMP 2 SET 3 (job, deptno) = (SELECT job, deptno 4 FROM EMP 5 WHERE Empno=7499) 6 WHERE Empno=7698; 1 row updated. SQL> UPDATE EMP 2 SET deptno= (SELECT deptno 3 FROM EMP 4 WHERE Empno=7788 5) 6 WHERE job= (SELECT job 7 FROM EMP 8 WHERE Empno=7788); 2 rows updated.

394

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Applying Default Values It is used to update a value in a column with default value set in the constraints. Default key word is introduced from oracle 9i onwards.
SQL> UPDATE EMP 2 SET Sal=DEFAULT 3 WHERE ename='SMITH'; 1 row updated. SQL> UPDATE EMP 2 SET hiredate=DEFAULT 3 WHERE ename='TAYLOR'; 0 rows updated.

Returning Clause The returning clause is introduced from 10g. It is used to return a value from an aggregate function. The clause can be specified for tables and materialized views and for views with a single base table. Restrictions: Each expression must be a simple expression or a single set aggregate function. It cannot be specified for multi table insert. It cannot be used with parallel DML or with remote objects. It cannot be used to retrieve long types. It cannot be specified upon a view upon which an inserted of trigger is defined.
SQL> VARIABLE sumsal NUMBER SQL> UPDATE EMP 2 SET Sal=Sal*1.1 3 WHERE deptno=10 4 RETURNING SUM (Sal) INTO: sumsal; 3 rows updated.

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
SQL> CREATE TABLE mybonus 2(

395

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

3 Empno NUMBER, 4 bonuses NUMBER DEFAULT 100 5); Table created. SQL> INSERT INTO mybonus (Empno) 2 (SELECT e.EMPno 3 FROM EMP e 4 WHERE job='SALESMAN'); 5 rows created. SQL> MERGE INTO mybonus B 2 USING (SELECT EMPno, sal, deptno 3 FROM EMP 4 WHERE deptno=30) S 5 ON (B.EMPno=s.EMPno) 6 WHEN MATCHED THEN 7 UPDATE 8 SET B.bonus=B.bonus+S.sal*0.1 9 DELETE 10 WHERE (S.sal>4000) 11 WHEN NOT MATCHED THEN 12 INSERT (B.EMPno, B.bonus) 13 VALUES (S.EMPno, S.sal*0.1) 14 WHERE S.sal<=4000; 6 rows merged. SQL> Ed Wrote file afiedt.buf 1 CREATE TABLE examtimetable 2( 3 examname VARCHAR2 (30), 4 examtime VARCHAR2 (12), 5 CONSTRAINT examnamePK PRIMARY KEY (examname) 6*) SQL> / Table created. SQL> INSERT INTO examtimetable 2 VALUES ('physical sciences','9.00 AM'); 1 row created. SQL> Ed Wrote file afiedt.buf 1 MERGES INTO examtimetable e1 2 USING examtimetable e2 3 ON

396

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

4( 5 e2.examname=e1.examname AND 6 e1.examname='physical sciences' 7) 8 WHEN MATCHED THEN 9 UPDATE 10 SET e1.examtime='10:30 AM' 11 WHEN NOT MATCHED THEN 12 INSERT (e1.examname, e1.examtime) 13* VALUES ('physical sciences','10:30 AM') SQL> / 1 row merged. SQL> Ed Wrote file afiedt.buf 1 MERGES INTO examtimetable e1 2 USING examtimetable e2 3 ON 4( 5 e2.examname=e1.examname AND 6 e1.examname='chemical sciences' 7) 8 WHEN MATCHED THEN 9 UPDATE SET e1.examtime='12:30 PM' 10 WHEN NOT MATCHED THEN 11 INSERT (e1.examname, e1.examtime) 12* VALUES ('chemical sciences','12:30 PM') SQL> / 1 row merged.

Delete Statement It is used to remove rows from A UN partitioned or partitioned table. The UN partitioned or partitioned base table of a view. The UN partitioned or partitioned container table of writable materialized view. Prerequisites To delete rows from a table, the table must be in the users schema. To delete rows from a materialized view, delete object privilege is a must. Delete any table system privilege allows to delete rows from any table or partition table or from the base table of any view. Syntax SQL>DELETE [FROM] <Table_Name> [WHERE Condition]; Using Returning Clause
SQL> DELETE FROM EMP 2 WHERE Empno=7864;

397

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

0 rows deleted. SQL> DELETE FROM EMP 2 WHERE deptno=20; 5 rows deleted. SQL> DELETE FROM EMP 2 WHERE deptno= (SELECT deptno 3 FROM dept 4 WHERE dname='SALES'); 6 rows deleted. SQL> VARIABLE salary NUMBER; SQL> DELETE FROM EMP 2 WHERE job='SALESMAN' AND hiredate<SYSDATE 3 RETURNING SUM (Sal) INTO: salary; 0 rows deleted. SQL> PRINT: salary; SALARY ----------

Transaction Control Oracle server ensures data consistency based upon transactions. Transactions consist of DML statements that make up one consistent change to the data. Transactions Start and End Cases A transaction begins when the first executable sql statement is encountered. The transaction terminates when the following specifications occur. A commit or rollback is issued. A DDL statement issued. A DCL statement issued. The user exists the sql*plus Failure of machine or system crashes. A DDL statement or a DCL statement is automatically committed and hence implicitly ends a transaction. Explicit Transaction Control Statements The logic of transaction can be controlled by using. Commit It ends the current transaction by making all pending data changes permanent. Savepint <Name> It marks a savepoint within the current transaction. Rollback [To Savepoint Name] It ends the current transaction by discarding all pending data changes. State of Data before Commit or Rollback 398 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Every data change made during the transaction is temporary until the transaction is committed. Data manipulation operation 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 cannot view the results of the data manipulation operations made by the current user. The oracle server institutes read consistency to ensure that each user sees data as it existed at the time of last commit. 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. SQL>COMMIT; Sate 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 marker in the current transaction. Using savepoint the transaction can be discarded up to the marker by using the rollback statement. SQL>ROLLBACK TO <SAVEPOINTName>; If a second savepoint is created with the same name as an earlier savepoint, the earlier savepoint is deleted. Altering the Table Definition Syntax for Adding Column SQL>ALTER TABLE<Table_name> ADD ( ColumnName DataType [DEFAULT Exp], ColumnName DataType].. ); Syntax for Modifying Column SQL>ALTER TABLE<TableName> MODIFY ( ColumnName DataType [DEFAULT Exp], Column DataType].. ); Adding a Column to a Table The add clause is used to add columns for an existing table. 399 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> ALTER TABLE dept30 2 ADD 3( 4 job VARCHAR2 (9) 5); ALTER TABLE dept30 * ERROR at line 1: ORA-00942: table or view does not exist

Guidelines for Adding Column A column can be added or modified but cannot be dropped from a table. We cannot specify the location where the column can appear, it by default becomes the last column. If the table contains records, before the column is added, the new column contains null values. Modifying a Column A column data type, size and default value can be changed. A change to the default value affects only subsequent insertions to the table. Guidelines to Modify a Column We can increase the width or precision of a numeric column. We can decrease the width of a column if the column contains only null values and if the table has no rows. We can change the data type if the column contains nulls. We can convert a char column to the vacrchar2 data type or convert a varchar2 column to the char data type if the column contains null values or if the size is not changed. Dropping a Column A column can be dropped from a table by using the alter table statement. The drop column clause is used for this purpose and the feature is enabled from oracle 8i onwards. Guidelines to Drop a Column The column may or may not contain data. Only one column can be dropped at a time. The table must have at least one column remaining in it after it is altered. Once a column is dropped it cannot be recovered.
SQL> ALTER TABLE dept30 2 DROP column job; ALTER TABLE dept30 * ERROR at line 1: ORA-00942: table or view does not exist

Set Unused Option The set unused option marks one or more columns as unused such that they can be dropped when the demand on system resources is less (8i). The response time is faster than the drop clause. 400 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Unused columns are treated as if they were dropped, even though their column data remains in the tables rows. After a column has been marked unused, we cannot have access to that column. The names and types of columns marked unused will not be displayed during a describe. We can add to a table a new column with the same name as an unused column.

SQL> ALTER TABLE dept30 2 SET UNUSED (ename); ALTER TABLE dept30 * ERROR at line 1: ORA-00942: table or view does not exist

Drop Unused Column Option This option removes from the table all columns currently marked as unused. The option is used when we want to reclaim the extra disk space from unused columns in the table. If the table does not contain unused columns the statement returns with no errors.
SQL> ALTER TABLE dept30 2 DROP UNUSED COLUMNS; ALTER TABLE dept30 * ERROR at line 1: ORA-00942: table or view does not exist

Dropping a Table It removes the definition of the oracle table. The command not only drops the table but the entire database is lost along with the associated indexes. Syntax SQL>DROP TABLE<TableName> [CASCADE CONSTRAINTS];
SQL> DROP TABLE dept30 2 CASCADE CONSTRAINTS; DROP TABLE dept30 * ERROR at line 1: ORA-00942: table or view does not exist

Guidelines to Drop Table The data is totally deleted from the table. Any views and synonyms will remain but are kept in invalid state. Any pending transactions are committed.

401

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Only the creator or owner of the table or a user with drop any table privilege can remove a table from database. The drop table statement once executed is irreversible. Changing the Name of an Object The rename command can be used to change the name of a Table View Sequence Synonym To rename the object we must be the owner of the object. Syntax SQL>RENAME<OldName> TO <NewName>; Illustration
SQL> RENAME dept TO department; Table renamed.

Truncating a Table It is used to remove all rows from a table and to release the storage space used by the specific table. The truncate table will not facilitate for rollback. Syntax SQL>TRUNCATE TABLE<TableName>; Illustration
SQL> TRUNCATE TABLE department; TRUNCATE TABLE department * ERROR at line 1: ORA-02266: unique/primary keys in table referenced by enabled foreign keys

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 comment 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 Syntax SQL>COMMENT ON TABLE <TableName> / COLUMN <Tablename.Column> is Text; Illustration
SQL> COMMENT ON TABLE EMP 2 IS 3 The Table Storing Employees Information'; Comment created.

402

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> COMMENT ON COLUMN EMP.mgr 2 IS 3 This Column is Actually Storing the Registered Employees Number as Manager 4 Numbers, with a Self Relation'; Comment created.

Dropping a Comment A comment is dropped from the database by setting it to an Empty string.
SQL> COMMENT ON TABLE EMP 2 IS ''; Comment created.

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 a select statement on an already existing table. Syntax SQL>CREATE TABLE<TablenName> AS SELECT Columns FROM TableName; [WHERE Condition]; The create table as select command will not work if one of the selected columns use long data type. When the New table is described it reveals that it has INHERITED the column definition from the existing table Using this style we can include all columns using asterisk or a subset of columns from table. The New table can contain invented columns which are the product of function of the combination of other columns. The column definition will adjust to the size necessary to contain the data in the invented columns. Creating an Exact Copy
SQL> CREATE TABLE samdept 2 AS 3 SELECT* 4 FROM department; Table created.

Creating an Exact Copy with Different Column Names


SQL> CREATE TABLE sampdept1 2( 3 deptid,

403

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

4 deptname, 5 place 6) 7 AS 8 SELECT* 9 FROM department; Table created.

Creating a Copy with Required Columns


SQL> CREATE TABLE sampdept3 2 AS 3 SELECT deptno, dname 4 FROM department; Table created.

Creating a Copy with Required Columns


SQL> CREATE TABLE sampdept4 2( 3 deptid, 4 deptname 5) 6 AS 7 SELECT deptno, dname 8 FROM department; Table created.

Creating a Copy with Invented Columns


SQL> Ed Wrote file afiedt.buf 1 CREATE TABLE sampdept5 2( 3 deptid, 4 deptname, 5 deptbudget 6) 7 AS 8 SELECT d.deptno, d.dname, SUM (Sal) 9 FROM EMP e, department d 10 WHERE e.deptno=d.deptno 11* GROUP BY d.deptno, d.dname SQL> / Table created.

Creating a Copy without Data 404 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> ED Wrote file afiedt.buf 1 CREATE TABLE sampdept6 2 AS 3 SELECT* 4 FROM department 5* WHERE 1=2 SQL> / Table created.

Creating a Table without Generating REDO LOG Entries Redo log entries are chronological records of database actions used during database recoveries. The redo log entries generation can be avoided by using the no logging keyword. By circumventing with no logging key word the performance o the create table command will improve as less work is being done. As the New table creation is not being written to the redo log files, the table will not be able to re-create, following a database failure. The redo log files are used to recover the database.
SQL> CREATE TABLE sampdept7 2 NOLOGGING 3 AS 4 SELECT* 5 FROM department; Table created.

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. Illustration
SQL> CREATE TABLE sample1 2( 3 sampid NUMBER (4), 4 sampname VARCHAR2 (20), 5 sampdate DATE,

405

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

6 CONSTRAINT sampidsampnamePK 7 PRIMARY KEY (sampid, sampname) 8) 9 ORGANIZATION INDEX; Table created.

To minimize the amount of active management of the index organized table, we should create it only if the tables data is very static. An index organized table is most effective when the primary key constitutes a large part of the tables columns. Working 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 partitioning is useful for very large tables only. Important Goals behind Partitioning The performance of queries 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 Partitioned Table
SQL> CREATE TABLE sampletable 2( 3 sampleid NUMBER (4) 4 CONSTRAINT sampidPK PRIMARY KEY, 5 sampname VARCHAR2 (20), 6 sampdate DATE, 7 sampdesc LONG 8); Table created.

Creating Range Partition Table


SQL> ED Wrote file afiedt.buf 1 CREATE TABLE sampletablepart 2( 3 sampid NUMBER (4) PRIMARY KEY, 4 sampname VARCHAR2 (20), 5 sampdate DATE, 6 sampdesc VARCHAR2 (4000) 7) 8 PARTITION BY RANGE (sampid) 9( 10 PARTITION sampidpart1 11 VALUES LESS THAN (500), 12 PARTITION sampidpart2

406

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

13 VALUES LESS THAN (1000), 14 PARTITION sampidpart3 15 VALUES LESS THAN (MAXVALUE) 16*) SQL> / Table created.

The maximum value need not be specified for the last partition, the maxvalue keyword is specified. The maxvalue specifies 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 minmum value for the range is implicitly determined by oracle from the definition of the preceding partition. Hash Partitions upon a Table A hash partition 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. In hash partition consecutive values of the partition key are not generally stored in the same partition. Hash partitioning distributes a set of records over a greater set of partitions, decreasing the likelihood for I/O contention. To create a hash partition we use the partition by hash clause.
SQL> Ed Wrote file afiedt.buf 1 CREATE TABLE EMPtablehash 2( 3 Empno NUMBER (6) 4 CONSTRAINT EMPnoPK PRIMARY KEY, 5 ename VARCHAR2 (30), 6 job VARCHAR2 (30), 7 deptno NUMBER (2) 8 CHECK(deptno IN(10,20,30,40,50,60,70,80,90)), 9 Sal NUMBER (8, 2), 10 CONSTRAINT deptnofk_hash 11 FOREIGN KEY (deptno) 12 REFERENCES department (deptno) 13) 14 PARTITION BY HASH (deptno) 15* PARTITIONS 9 SQL> / Table created.

Format Choices Specify the number of partitions and the table space to use. Specify the named partitions. 407 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> Ed Wrote file afiedt.buf 1 CREATE TABLE EMPtablehash1 2( 3 Empno NUMBER (6) 4 CONSTRAINT EMPnopk PRIMARY KEY, 5................ 6) 7 PARTITON BY HASH (deptno) 8* PARTITION 2 STORE IN (dpetnopart1ts, deptnopart2ts) SQL> / ................ * ERROR at line 5: ORA-00904: invalid identifier

Working with List Partitioning In list partitioning we specify oracle all the possible values and designate the partition into which the corresponding rows should be inserted.
SQL> ED Wrote file afiedt.buf 1 CREATE TABLE EMPsamplelist 2( 3 EMP NUMBER (4) 4 CONSTRAINT EMPno1PK PRIMARY KEY, 5 ename VARCHAR2 (20), 6 Sal NUMBER (8, 2), 7 hiredate DATE, 8 deptno NUMBER (2), 9 job VARCHAR2 (15), 10 CONSTRAINT deptnoFK 11 FOREIGN KEY (deptno) REFERENCES department (deptno) 12) 13 PARTITION BY LIST (job) 14 ( 15 PARTITION jpart1 16 VALUES ('PRESIDENT','ANALYSIT'), 17 PARTITION jpart2 18 VALUES ('MANAGER','SALESMAN','CLERK') 19*) SQL> / Table created.

Generating Sub Partitions Sub partitions are partitions of partitions. Sub partitions can be used to combine the two types of partitions Range partitions 408 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Hash partitions In very large tables, the composite partition strategy is an effective way of separating the data into manageable and tunable divisions.

SQL> CREATE TABLE EMPsamplesubpart 2( 3 Empno NUMBER (6) PRIMARY KEY, 4 ename VARCHAR2 (30), 5 Sal NUMBER (8, 2), 6 deptno NUMBER (2), 7 job VARCHAR2 (15), 8 CONSTRAINT deptnoFK1 9 FOREIGN KEY (deptno) REFERENCES department (deptno)) 10 PARTITION BY RANGE (ename) 11 SUBPARTITION BY HASH (job) 12 SUBPARTITIONS 5 13 ( 14 PARTITION namep1 15 VALUES LESS THAN ('M'), 16 PARTITION namep2 17 VALUES LESS THAN (MAXVALUE) 18); Table created.

Splitting Table Partitions


SQL> ALTER TABLE sampletablepart 2 SPLIT PARTITION sampidpart3 AT (2000) 3 INTO 4( 5 PARTITION sampidpart3, 6 PARTITION sampidpart4 7); Table altered. SQL> Ed Wrote file afiedt.buf 1 ALTER TABLE EMPsamplelist 2 SPLIT PARTITION jpart2 3 VALUES ('SALESMAN') 4 INTO 5( 6 PARTITION jsalesman, 7 PARTITION ssalesman 8*) SQL> / Table altered.

Merging Table Partitions 409 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> ALTER TABLE EMPsamplelist 2 MERGE PARTITIONS 3 jpart1, jsalesman 4 INTO PARTITION jpart1; Table altered. SQL> ALTER TABLE sampletablepart 2 MERGE PARTITIONS 3 sampidpart2, samplepart3 4 INTO PARTITION sampidpart3; sampidpart2, samplepart3 * ERROR at line 3: ORA-02149: Specified partition does not exist

Dropping a Table Partition


SQL> Ed Wrote file afiedt.buf 1 ALTER TABLE sampletablepart 2* DROP PARTITION sampleidpart3 SQL> / DROP PARTITION sampleidpart3 * ERROR at line 2: ORA-02149: Specified partition does not exist SQL> ALTER TABLE EMPsamplelist 2 DROP PARTITION jpart1; Table altered.

Creating Indexes upon Partitions Once a partitioned table is created, we have to create an index upon that table The index may be partitioned according to the same range of values as that were used to partition the table. The indexed partitions can be placed into specific table spaces.
SQL> CREATE INDEX EMPsamplelistinx 2 ON EMPsamplelist (job) 3 LOCAL 4( 5 PARTITION jpart1, jpart2 6); PARTITION jpart1, jpart2 * ERROR at line 5: ORA-14004: missing PARTITION keyword

410

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

The local keyword tells oracle to create a separate index for each partition on the table. The global keyword tells oracle to create a non partitioned index. Local indexes are easier to manage than global indexes. Global indexes can perform uniqueness checks faster than local indexes.

411

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Object Oriented Concepts in Oracle

Object Tables Object tables are created by using the user defined data types. In an object table each row or record is treated as an object. 412 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Each row in an object table has an object identifier (OID), which is unique throughout the database. The OID is generated and assigned by oracle when the row or object is created. The rows or objects of an object table can be referenced by other objects within the database. An object table is created using the create table command. All object tables automatically inherit the data types from the user defined data types. All object types are associated with default methods applied upon the relational tables i.e. insert, delete, update and select. The relational DML operation style is accepted only when the user defined data type is a collection of built-in data types, and the object table does not contain any ref constraints. Creating an User Defined Object Type Syntax SQL>CREATE OR REPLACE TYPE<TypeName> AS OBJECT ( ColumnName1 DataType (Size), ColumnName2 DataType (Size), ColumnNameN DataType (Size) ); All user defined data types are schema objects of the database. The user defined object data type can be used as reference in other tables, or instantiated as object table directly. All user defined data types and objects are stored permanently in the data dictionaries. User_types User_objects We can query for the user defined data types and objects using the relational select.
SQL> SELECT TYPE_NAME, TYPECODE, 2 ATTRIBUTES, METHODS 3 FROM USER_TYPES; No rows selected SQL> SELECT OBJECT_NAME, 2 OBJECT_TYPE 3 FROM USER_OBJECTS; OBJECT_NAME --------------------------------------------PK_DEPT EMP PK_EMP BONUS SALGRADE ITEMTYPEPK ITEMTYPES ITEMS ITEMIDPK

413

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

DIVIDPK DIVISIONS JOBMASTER JOBIDPK EMPSTORES EMPSTORESPK ALLSALES ALLSALESPK EXAMTIMETABLE MYBONUS EXAMNAMEPK DEPARTMENT SAMDEPT SAMPDEPT1 SAMPDEPT3 SAMPDEPT4 SAMPDEPT5 SAMPDEPT6 SAMPDEPT7 SAMPLE1 SAMPIDSAMPNAMEPK SAMPLETABLE SAMPIDPK SAMPLETABLEPART SAMPLETABLEPART SAMPLETABLEPART SAMPLETABLEPART SYS_C005297 EMPTABLEHASH EMPTABLEHASH EMPTABLEHASH EMPTABLEHASH EMPTABLEHASH EMPTABLEHASH EMPTABLEHASH EMPTABLEHASH EMPTABLEHASH EMPTABLEHASH EMPNOPK EMPSAMPLELIST EMPNO1PK EMPSAMPLESUBPART EMPSAMPLESUBPART EMPSAMPLESUBPART EMPSAMPLESUBPART EMPSAMPLESUBPART EMPSAMPLESUBPART EMPSAMPLESUBPART EMPSAMPLESUBPART EMPSAMPLESUBPART EMPSAMPLESUBPART EMPSAMPLESUBPART EMPSAMPLESUBPART EMPSAMPLESUBPART

414

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SYS_C005303 SAMPLETABLEPART EMPSAMPLELIST 66 rows selected.

Creating User Defined Student Type


SQL> CREATE OR REPLACE TYPE student 2 AS 3 OBJECT 4( 5 studid NUMBER (6) 6, sname VARCHAR2 (20) 7, DOB DATE 8, DOA DATE 9, fees NUMBER (7, 2) 10); 11 / Type created.

The above statement creates the user defined object data type called as student and stores it in the data dictionary called USER_TYPES. This data type is also called as collection in oracle, and this collection is reusable where ever the same data type collection is expected in project development. Creating an Object Table Syntax SQL> CREATE TABLE TableName OF TypeName; Illustration
SQL> CREATE TABLE mcastudent 2 OF student; Table created.

The above statement creates the object table mcastudent as an abstract data type. Each row in the object table has an oid 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 relational insert statement. The normal insert or relational insert is possible only when the table does not contain any nested data types. Relational Insert
SQL> INSERT INTO mcastudent 2 VALUES (1234,'kumar','07-oct-98', sysdate, 15000); 1 row created.

415

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Insert Records into Specific Columns


SQL> INSERT INTO mcastudent (studid, sname) 2 VALUES (1235,'krishna'); 1 row created.

Insert Using Constructor Method


SQL> INSERT INTO mcastudent 2 VALUES (student ( 3 1236, 4 Satish, 5 05-sep-99', 6 sysdate, 7 1300 8) 9); 1 row created.

Update Data from Object Table


SQL> UPDATE mcastudent 2 SET sname='Sri Ram' 3 WHERE studid=1234; 1 row updated.

Delete Data from Object Table


SQL> DELETE FROM mcastudent 2 WHERE studid=1234; 1 row deleted. SQL> DELETE FROM mcastudent; 2 rows deleted.

Select Data from Object Table The abstract data types column can be referred as a part of the tables columns.
SQL> SELECT* 2 FROM mcastudent; No rows selected SQL> SELECT studid, sname 2 FROM mcastudent; No rows selected

416

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> SELECT studid, sname 2 FROM mcastudent 3 WHERE studid=1234; No rows selected

Creating Table with User Defined Data Type


SQL> CREATE TABLE mbastudent 2( 3 studentcoll STUDENT, 4 semester VARCHAR2 (10), 5 semstartdate DATE, 6 semenddate DATE, 7 specialization VARCHAR2 (20) 8); Table created.

Once the user defined data types are created we can instantiate them in the normal relational tables. These instances look as normal attributes within the table, but can be operated only with constructor method or object views. In any of the operation we have to provide reference to all attributes within the instance, but partial association is not accepted.

SQL> INSERT INTO mbastudent 2 VALUES ( 3 STUDENT ( 4 1234, 5 sampath, 6 10-dec-85', 7 sysdate, 8 25000 9), 10 first, 11 25-jul-07', 12 25-oct-07', 13 marketing 14); 1 row created.

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
SQL> SELECT REF (A) 2 FROM mcastudent A 3 WHERE sname='SATISH'; No rows selected

417

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

REF() always returns the OID of the registered objects in the object table REF() always expects the alias to the object table as argument The ref (A) value will be different under different systems and may be wrapped onto multiple lines. The REF () function can only reference row objects, hence we cannot use REF () for referencing column objects. The column objects can be of Abstract data types. Lobs. Collections. The ref () function by itself does not give any useful information. Deref () Function The deref () function takes a reference value i.e., the OID generated for a reference and returns the original value of the row object.
SQL> CREATE TABLE studentincharges 2( 3 inchargename VARCHAR2 (30), 4 studentincharge REF STUDENT 5); Table created.

The studentincharge column references the data that is stored elsewhere in the system. The REF () function points the studentincharge column to a row object of the student data type. As mcastudent is an object table of the student data type, the studentincharge column can point to The row object within the mcastudent object table. The studentincharge table can be described as an ordinary table.

SQL> SET DESCRIBE DEPTH 2; SQL> DESC studentincharges; Name Null? Type ----------------------------------------------------------------------------------- -------- -----INCHARGENAME VARCHA STUDENTINCHARGE REF OF STUDID NUMBER SNAME VARCHA DOB DATE DOA DATE FEES NUMBER

Seeing full details of the reference column.

Insert Records into Reference Table


To insert records into reference tables we have to use the ref () function. The ref column always contains only OIDs 418 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> ED Wrote file afiedt.buf 1 INSERT INTO studentincharges 2 SELECT 'SUBRAMANYAM SHARMA', 3 REF (A) 4 FROM mcastudent A 5* WHERE sname='SATISH KUMAR' SQL> / 0 rows created.

In the Above Case The mcastudent table is queried first. The REF () function returns the OID for the row object selected. The selected OID is stored in the studentincharge table as a pointer to that row object in the mcastudent object table. The studentincharges table actually contains the name of the studentincharge and a reference to a row object in the mcastudent table. The reference OID can be seen by querying upon the studentincharge table.
SQL> SELECT* 2 FROM studentincharges; No rows selected

The reference value cannot be seen until we use the DEREF () function. The parameter for the deref () function is the column name of the ref column but not the table name.

SQL> SELECT DEREF (X. studentincharge) 2 FROM 3 studentincharges X 4 WHERE inchargename='SUBRAMANYAM SHARMA'; No rows selected

Points to Note The query uses a reference to a row object to travel from one table to the second. A join is performed in the background without specifying the join criteria. The object table itself is not mentioned in the query. The name of the object table need not be known to deref the values. The entire referenced object is returned not just part of the row. Implementing Value () Function The value () function is useful when debugging references. The value () function allows to query the formatted values directly from the object table. We can select the values from object table without using the deref query upon the studentincharges, studentincharge column.
SQL> SELECT VALUE (A)

419

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 FROM mcastudent A 3 WHERE sname='SESHU'; No rows selected

Invalid References We can delete the object to which a reference points. We can delete a row from mcastudent object table to which studentincharge record points.
SQL> DELETE 2 FROM mcastudent 3 WHERE sname='SESHU'; 0 rows deleted.

Dangling Ref It is a record which has an OID pointing to a record in an object table, for which the reference record is not existing in the original object table. As oracle generates a OID for the row object which can be referenced by any other row from other table when the row object is deleted the OID is lost and the oracle doesnt reuse the OID numbers. Hence it a New record for seshu is inserted this is given an OID value, but the studentincharge record still points to the OLD value only. In a relational system the join between two tables is dependent only on the current data. In an OOP system the join is between objects, hence the fact that two objects having the same data does not mean they is same. Object Views with REFs Object views are very important to super impose OOPS structures on an existing relational table. We can create abstract data type and use them within the object view of an existing table. Object view acts as a bridge between the existing relational applications to object relational applications. Integrating User Defined Data Types to Relational Tables Relational Stage
SQL> CREATE TABLE students 2( 3 studid NUMBER (6) 4 CONSTRAINT studidPK PRIMARY KEY, 5 sname VARCHAR2 (30), 6 street VARCHAR2 (40), 7 cityname VARCHAR2 (25), 8 statename VARCHAR2 (40), 9 pincode NUMBER (6) 10); Table created.

Creating Abstract Data Types 420 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

SQL> CREATE OR REPLACE 2 TYPE myaddress 3 AS OBJECT 4( 5 street VARCHAR2 (40), 6 cityname VARCHAR2 (25), 7 statename VARCHAR2 (40), 8 pincode NUMBER (6) 9); 10 / Type created. SQL> CREATE OR REPLACE TYPE mystudent 2 AS OBJECT 3( 4 sname VARCHAR2 (30), 5 saddress myaddress 6); 7/ Type created.

As student table was created without using the myaddress and mystudent data types it has to be accessed via object views. The above principle of accessing data is called as object based access. An object view can be specified upon the abstract data types to apply onto the relational table. Creating an Object View
SQL> CREATE OR REPLACE VIEW 2 studentov (studid, studef) 3 AS 4 SELECT studid, 5 mystudent (sname, 6 myaddress ( 7 street, 8 cityname, 9 statename, 10 pincode 11) 12) 13 FROM students; View created.

We can access the students table directly as a relational table or via the constructor methods of the abstract data types. Relational Select on Students Table
SQL> SELECT*

421

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

2 FROM students; No rows selected

Selecting Data from the Relational Table Using the Object View
SQL> SELECT* 2 FROM studentov; No rows selected

Object Views with References If the students table is related to another table, then the object views can be created as a reference between these tables. By using the above concept oracle uses the existing primary key or foreign key relationships to simulate OIDs for use by REFs between the tables. By implementing the above concept we can access the table either as relational table or as objects. When the tables are treated as objects we can use the REFs, to automatically perform joins upon the tables using the DEREF () function. Create a Reference Table for Students
SQL> CREATE TABLE studentbooks 2( 3 libtranno NUMBER (6), 4 studid NUMBER (6), 5 booktitle VARCHAR2 (50), 6 lendingdate DATE, 7 CONSTRAINT libtreamnoPk 8 PRIMARY KEY (libtranno, studid), 9 CONSTRAINT studentbooksFK 10 FOREIGN KEY (studid) 11 REFERENCES students (studid) 12); Table created.

Inserting the Data into Library Table


SQL> INSERT INTO studentbooks 2 VALUES (2000, 1200,'THERMO DYNAMICS', SYSDATE); 1 row created. SQL> SELECT* 2 FROM studentbooks; LIBTRANNO STUDID BOOKTITLE ---------- ---------- -------------------------------------------------- --------2000 1200 THERMO DYNAMICS LENDINGDA 19-SEP-10

422

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

1 row selected. SQL> SELECT sname, booktitle, lendingdate 2 FROM students s, studentbooks sb 3 WHERE s.studid=sb.studid; SNAME BOOKTITLE LENDINGDA ------------------------------ -------------------------------------------------- --------THERMO DYNAMICS 19-SEP-10 1 row selected.

Generating OIDs We can use an object view to assign OIDs to the records in students table. OIDs are assigned to records in an object and an object table in turn is based on an abstract data type. As first step create an abstract data type that has the same structure as the student table i.e. the relational table.
SQL> CREATE OR REPLACE TYPE 2 studenttype AS OBJECT 3( 4 studid NUMBER (6), 5 sname VARCHAR2 (30), 6 street VARCHAR2 (40), 7 cityname VARCHAR2 (25), 8 statename VARCHAR2 (40), 9 pincode NUMBER (6) 10); 11 / Type created.

As the next step create a view based upon the studenttype by assigning OID values to the records in student table.

SQL> CREATE OR REPLACE VIEW studentov 2 OF studenttype 3 WITH OBJECT IDENTIFIER (studid) 4 AS 5 SELECT 6 studid, sname, street, cityname, statename, pincode 7 FROM students; View created.

The first part of the statement tells the database to create a view based on the structure defined in student type. The next part of the create view tells the database how to construct OID values for the rows in students table.

423

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

With the above step the rows of students are now accessible as row objects via the studentov view. The OID values generated for the studentov rows are called as PKOIDs as they are based upon students primary key values. The relational tables can be accessed as row objects if the object views are created upon them. Generating References Actually the rows of studentbooks reference rows in students table. As per relational concept the relationship is determined by the foreign key pointing from the studentbooks.studid column to the student.studid column. From the studentov object view that has been created, the rows in students table can be accessed via OIDs. We have to create reference values in studentbooks that reference students table. Once the REFs are created we can use DEREF () function to access the students data from student books.
SQL> CREATE VIEW studentbooksov 2 AS 3 SELECT 4 MAKE_REF (studentov, studid) studid, 5 libtranno, booktitle, lendingdate 6 FROM studentbooks; View created.

MAKE_REF () Function It creates references which are called PKREFs from an existing view to another view. PKREFs are named so as they are based on primary keys. The function takes as an argument(s) as the name of the object view being referenced and the name of the column or columns that form the foreign key in the local table. Since make_ref () create a view the result of an operation must be given a column alias. Querying Through Object Views We use the DEREF () function to select the value of the referenced data. The concept is almost all same as that of object views.
SQL> SELECT DEREF (sb.studid) 2 FROM studentbooksov sb 3 WHERE booktitle='THERMO DYNAMICS'; DEREF (SB.STUDID) (STUDID, SNAME, STREET, CITYNAME, STATENAME, PINCODE) ---------------------------------------------------------------------------STUDENTTYPE (1200, NULL, NULL, NULL, NULL, NULL) 1 row selected.

Steps Performed The query finds the records in the studentbooks table for the which the lendingdate is the current system date. 424 Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

Taking the studid value from that record evaluates its reference. The evaluated reference studid is pointed to the PKOID value in the studentov object view using make_ref. The studentov object view returns the record whose PKOID matched the referenced value. The DEREF () function then gets activated returning the value of the referenced row. The query returns rows from students even though the user actually queried on studentbooks.

Things to Note Object views of column objects enable to work with table as if they were both relational tables and object relational tables. When object views are extended to row object they enable to generate OID values based on established foreign key or primary key relationship. Object views allow us to continue to use the existing constraints and standard insert, delete, update and select statements. They help in using OOP features such as references against the object tables. They provide a technological bridge for migrating to an OOPS DB architecture. Oracle performs JOINS that resolve the references defined in the database. When referenced data is retrieved it beings the entire row object that was referenced. To reference the data we need to establish PKOIDs in the table that is primary key table relationship. Use make_ref () to generate references in the table that is foreign key table relationship. Once the above specifications are completed we can work with the data as if was stored in object tables.

425

Under the Guidence By Mr. Satish Kumar Yellanki. Prepaired By

[ K . Sekhar ]

You might also like