Naresh i Technologies

FIRST STEPS TOWARDS ORACLE 10g
SOME THINGS WHAT WE SHOULD CONSIDER :  As per Oracle database is a collection of data in one or more files.  The database can contain Physical and Logical structure.  The Course of developing an application consists of     Creating structures (Tables & Indexes) Creating Synonyms for the object names. View objects in different databases Restricting Access to the objects.

 External Tables can be accessed for files outside the database, as if the rows in the files were rows in the table.  An Oracle Instance Comprises of    A memory area called System Global Area (SGA) Background processes which interact between the SGA and the database files on disk. The Oracle Read Application Cluster (RAC) can make more than one instance to use the same database.

Database as per Oracle :  With in the Oracle database, the basic structure is a table.  The different tables supported by Oracle Database are….. 1) 2) 3) 4) 5) 6) 7) 8) 9) Relational Tables Object Relational Tables Index Organized Tables External Tables Partitioned Tables Materialized Views Temporary Tables Clustered Tables Dropped Tables

 The Access to the data in the tables is tuned by indexes, they are 1) 2) 3) 4) 5) 6) B+ Tree Indexes Bitmap Indexes Reverse Key Indexes Function Based Indexes Partitioned Indexes Text Indexes

ORACLE STYLE FOR DATA STORAGE :  All the logical structures in the database must be stored in the database.  Oracle maintains a data dictionary, which records METADATA about object.  The OBJECTS which need physical storage space, are allocated space within a Tablespace.

1

Oragle 10 g Material

Naresh i Technologies

Table Spaces :  It consist of one or more data files  A data file can be a part of one and only one table space  As per 10g minimum table space is created are  SYSTEM and SYSAUX : which are used to support its internal management needs

 In 10g a bigfile tablespace can be created , which can grow to the size of tera bytes
 The Oracle managed files concept can be used to simplify the creation and maintenance of data files Temporay Tablespace :  The actual table space is permanent , but the segments saved in the table space are temporary  It is used to support sorting operations such as index creation and joint processing.  Tables can be either Dictionary Managed / Logically Managed  Oracle maintains a Bitmap in each data file of the table space to trace space availability AUTOMATED STORAGE MANAGEMENT (ASM) :  It automates the layout of datafiles and other operating system level files , used by the database  It is done by distributing the files across all available disks.  It supports multiplexing features, minimizing the possibility of data data loss  As new disks are added , the database files are automatically redistributed access all disks in the defined groups for optimal performance AUTOMATIC UNDO MANAGEMENT :     The transaction are supported by dynamically creating and managing undo segments It helps in maintaining prior images of the changed Blocks and Rows The UNDO segments are managed directly without the intervention of the DBA Flashback version Queries can be executed to see the different versions of a row as it changed during a specified time interval.

DROPPED DATA :

 The Recycle Bin concept was introduced with Oracle Database 10g
 This concept impacts the space requirements for the table spaces and datafiles  This architecture greatly simplifies recoveries of accidentally dropped tables  The concept may considerably increase the space used in the database  The PURGE Command is used to remove old entries from the recycle bin PROGRAMMATICAL STRUCTURES IN ORACLE :

1) PL/SQL : 2 Oragle 10 g Material

Naresh i Technologies  It is the most critical component of all the application implementations  The component can be used to create stored procedures and functions  Using this component the stored procedures and functions can be collected into single unit called packages  Using the same component the Database trigger can also be designed.

2) DYNAMIC SQL :
 Using this concept SQL can be generated at runtime and pass it to procedures which execute it.

3) SQL * PLUS :
 It provides simple interface to the Oracle database.  It supports Rudimentary Reporting and is the best tool for scripting.  It provides consistent interface for 1. Retrieving data from data dictionary. 2. Creating database objects.

4) JAVA & JDBC :
 It supports JAVA and JDBC and help in using JAVA in the place of PL/SQL.  JAVA based stored procedures can be written.

5) XML :
 Oracles XML interfaces and XML types can be usied to support inserting and retrieving of data via XML.

6) Object Oriented SQL & PL/SQL :
 Oracle can be used to create and access object oriented structures, including user defined data types, methods, large objects object tables nested tables. Data Pump :  Data Pump import and Data Pump Export, enhance the manageability and performance.  Data Pump can be used to quickly extract data and move it to different databases while altering the schema and changing the rows.

7)

8) SQL * LOADER :
 It is used to load flat files quickly into Oracle Tables.  A single flat file can be loaded into multiple tables during the same load, and loads can be parallel zed.

9) External Programs and Procedures :
 SQL can be embedded with in external programs.  Procedural Libraries can be created and can be linked later to Oracle. 10 ) UTL – MAIL :

3

Oragle 10 g Material

3) Personal Edition :  It allows for the development of applications which run on either the standard or Enterprise Edition. DATABASE MANAGEMENT SYSTEMS :  DBMS is a program which takes care of     Storing of Information. Retrieving of Information. F. Modification of Information. 4 Oragle 10 g Material . Deletion of Information.  The Edition is not suitable for Production Environment. E.  The licensed functionalities that are supported are :     Oracle Spatial Oracle OLAP Oracle Label Security Oracle Data Mining 2) Standard Edition :  It provides some subset features of Enterprise Edition.  The components of Relational Model are :  Collection of objects or relations that store the data. TYPES OF EDITIONS : 1) Enterprise Edition :  It contains all features and is the rich extensible version of the Oracle databse.  It allows a PL/SQL application developer to see e-mails without having to know how to use the underlying SMTP Protocal stack.  Type of Databases ** Hierarchical ** Object Relational RELATIONAL MODELS : ** Network ** Relational ** Object Oriented  The Model was first outlined by Dr.  It includes features such as Flash Back Database. Codd in 1970.  It includes features that are needed by a small business entity.Naresh i Technologies  It is a package introduced in Oracle 10g.

It uses a set of operators. We need not specify the access route to the tables There is no need to identify how the data is arranged physically. It contains a collection of tables with no physical pointers.  Should contain sufficient detail for a developer to build the database system RELATIONAL DATABASE PROPERTIES :      It can be accessed and modified by executing Structured Query Language statements.Naresh i Technologies    A set of operations that can act on the relations to produce other relations.  It provides a new engine which supports    Object oriented programming Complex data types Complex business objects 5 Oragle 10 g Material . ABOUT ORACLE 8 :  It is the first object capable database. DATA MODELS :  The Data Models help in exploring ideas and improve the understanding of the database design. PURPOSE OF DATA MODELS : ** Communicate ** Evolve ** Categorize ** Analyze ** Describe ** Specify ** Imitate ** Investigate OBJECTIVE OF THE MODELS :  To produce a model that fits a multitude of uses  Should be understood by an end user. COMMUNICATING WITH RDBMS :  The Structured Query Language is used to Communicate with RDBMS. Data integrity for accuracy and consistency  A Relational database uses relations or two dimensional tables to store information. retrieve and manipulate the data. by allowing the use to define. STRUCTURED QUERY LANGUAGE :     It allows the user to communicate as the server It is Efficient It is easy to learn and use It is functionally complete.

with sharing of runtime data structures. precise format.  The Internet File System ( IFS) combines the power for ease of use a file system. native integration with Microsoft Transaction Server (MTS).  It supports Client Server and Web based application which are distributed and multitired. Application servers to execute business logic and serve presentation logic to browser based clients. ER – MODEL BENEFITS :     It documents information for the organization in a clear. ENTITY RELATIONSHIP MODEL :  In an effective system data is divided into discrete categories or entities.  End users can easily access files and folders in ORACLE IFS via a variety of protocols. KEY COMPONENTS INDIA ER – MODEL :  ENTITY : It is a thing of significance about which the information need to be known.  It provides high performance Internet platform for e-commerce and data warehousing.  It provides OLTP applications.  An ER – Model is an illustration of various entities in a business and the relationships between them. 6 Oragle 10 g Material . Provides a clear picture of the scope of the information requirement.  ER – Model separates the information required & the business from the activities performed. ABOUT ORACLE 8i :  It is the database of Internet Computing.Naresh i Technologies  Full compatibility with the relational concepts. ** Each attribute may be mandatory or optional.  It can scale tens and thousands of concurrent users.  The core pieces of Oracle Internet Platform are :   Browser based clients to process presentation. large buffer caches and deferrable constrains.  Databases to execute database intensive business logic and serve data.  ATTRIBUTES : It is something that describes or qualifies an entity. Provides an easily understood pictorial map for the database design It offers an effective framework for integrating multiple application.  It enables the users to web-enable their multimedia data  It provides full.  It provides advanced tools to manage all types of data in Web Sites.  It is built during the analysis phase of the System Developing Life Cycle.

Date about different entities is stored in different tables.  The Database is accessed using Structured Query Language ( SQL )  The language is a collection of set of operators. the absence of value in Oracle is represented as NULL. A Foreign Key is a column or a set of Column that refer to a Primary Key in the same table or another table.Naresh i Technologies RELATIONAL DATABASE TERMINOLOGY :  ROW OR TUPLE :  It represents all data required for a particular instance in an entity. RDBMS enables the data in one table to be related to another table by using the foreign keys.  The order of the rows is not significant.  A Field can have only one value. STRUCTURED QUERY LANGUAGE STATEMENTS : ORCLE SQL Compiles with industry accepted standards. RATIONAL DATABASE PROPERTIES :  Should not specify the access route to the tables. while retrieving the data. RELATING MULTIPLE TABLES :     Each table contains data that describes exactly only one entity. and should not reveal the physical arrange.  The different categories into which the SQL statements fall are  Data Retrieval Statements : • SELECT Data Manipulation Language Statement ( DML ) •  INSERT UPDATE DELETE  Data Definition Language Statement (DDL ) • • CREATE RENAME ALTER DROP TRUNCATE  Transaction Control Language Statement ( TCL ) 7 Oragle 10 g Material .  COLUMN OR ATTRIBUTE :  It represents one kind of data in a table  The column order is not significant when storing the data.  A FIELD :  It can be found at the Intersection of a row and a column.  Each row is an entity is uniquely identified by declaring it as PRIMARY KEY or UNIQUE . or may not have a value at all.

To run the previous or current SQL statement in the Buffer type ‘ / ‘at SQL prompt.  The Table name should begin with a letter and can be 1 – 30 characters long. Basic Unit Logically represents subsets of data from one or more tables. The SQL statement can be divided into different lines within the SQL Buffer. SYNONYM : Used to give alternate names to objects. To open the SQL Editor type ed at SQL prompt.  The different Database objects in Oracle are : TABLE : VIEW : Used to store date. INDEX : It is used to improve the performance of some queries.. SEQUENCE : Used to Generate Primary Key values..e. $ . The Current SQL statement replaces the previous SQL statement in the Buffer.     CREATING AND MANAGING TABLES : DATABASE OBJECTS :  A Oracle database can contain multiple data structures. editing is possible only in the current SQL Buffer line.Naresh i Technologies •  COMMIT ROLLBACK SAVEPOINT Data Control Language ( DCL ) • GRANT REVOKE ABOUT THE SQL BUFFER :       All Commands of SQL are typed at the SQL prompt. Rules to Create A Table :  The user should have permission or CREATE TABLE command.  Size of the table need not be specified.  The structure of the table can be modified online. Tables in ORACLE 8 / 9 / 10 :  Tables can be crated at any time. Only one SQL Statement is managed in the SQL Buffer. and storage area.  Names can contain : ** A – Z ** a .z ** 0 – 9 ** . Only one line i. the current line can be active at a time in the SQL Buffer. even when the users are using the database. At SQL prompt. # 8 Oragle 10 g Material . Every statement of SQL should be terminated Using One SQL statement can contains only one.

The data types value associates fixed set of properties with the value. The Built-in data types of ORACLE are Categorized as       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 Alphanumaric data  The Information can be     Words Free – Form Text Database Character set National Character set  They are less restrictive than other data types an have very few properties 9 Oragle 10 g Material . Building Blocks of SQL Statements : * Data types * Literals * Format Models * Database Objects * Nulls * Pseudo Columns * Comments * Schema Object Names and Qualifiers * Syntax for Schema objects and parts of SQL Statements. Column_Name2 < Data type > (Width).  Names cannot be oracle servers reserved word  Names are not case sensitive Create Table Statement : Syntax : SQL > CREATE Table < Table_Name > ( Column_Name1 < Data type > (Width). The values of one data type are different from another data type. Data Types in Oracle :      Each value in ORACLE is manipulated by a date type.Naresh i Technologies  Names can not be duplicated for another object in the same ORACLE Server. : : Column_Namen < Data type > (Width) ). The data type defines the domain of values that each column can contain.

 It occupies only that space for which the data is supplied.  The different character data types are :  CHAR NCHAR VARCHAR2 NVARCHAR2 CHAR DATATYPE :  It specifies fixed length character string. Varchar Datatype :  It specifies the variable length character string.  The range of magnitude is 1. and contains Unicode data only. s ) 10 Oragle 10 g Material . NUMBER DATATYPES : Number Data Type :  It stores zero.  If the data is less than the original specified size. positive and negative fixed and floating point numbers..Naresh i Technologies  The data is stored in strings with byte values  The information can belong to either   7 – list ASCII Character set EBCDIC  ORACLE supports both single byte & multi byte character sets.9 * 10 125  The general declaration is NUMBER ( p .9 …….  If the data is shorter than the actual size then the blank pads are applied.  The Minimum size is 1 Byte and the Maximum size is 4000 Bytes. Nvarchar Datatype :  It is first time defined in ORACLE 9i. NCHAR DATATYPE :  It is first time defined in ORACLE 9i.0 * 10 -130 to 9.  The Maximum size allowed is 2000 Bytes and size has to be specified.  The minimum for the size is 1 Byte and maximum is 4000 Bytes. blank pads are applied  The default length is 1 Byte and the Maximum is 2000 Bytes.  It is defined for Unicode only date.  The size of a character can range from 1 Byte to 4 Bytes depending on the database character set.  The size should be specified.  The column’s maximum length is determined by the National Character set definition.

Naresh i Technologies • • Float Data Type : P  It specifies the precision. Object types cannot be created on LONG attribute.  The scale value is not applicable to floating point numbers.30103. It is used to store very lengthy text strings The length of LONG values may be limited by the memory available on the computer.e.  To convert from decimal to binary precision multiply the decimal precision by 3.  The dates can be specified as literals. using the Gregorian Calender.. Indexes cannot be created on LONG Columns LONG can be returned through a functions. Restrictions :       A single table can contain only one LONG column. It can be declared in a PL/SQL unit but cannot be referenced in SQL. but not through a stored procedure. the total number of digits ( 1 to 38 ) S  it specifies the scale.  To convert from binary to decimal precision multiply ‘ b ‘ by 0. i.32193.  It specifies to have a decimal point anywhere from the first to the last digit.  The maximum of 126 digits of binary precision is roughly equivalent to 38 digits of decimal precision. LONG columns can be referenced in ** SELECT Lists ** SET Clauses of UPDATE statements ** VALUES clauses of INSERT statements.  The precision can range from 1 to 126. i. Float (B)  It specified a floating point number with binary precision b. It can range from –84 to 127.. Syntax : Float  It specifies a floating point number with decimal precision 38 or binary precision of 126.e. LONG columns cannot appear in WHERE clauses or in Integrity Constraints. or can have no decimal point at all. DATE & TIMME DATA TYPES : Date Data Type :  It is used to store data and time information. the number digits to the right of the decimal point. as the number of digits that can appear after the decimal point is not restricted. Long & Raw Data Types : Long Data Type :     This datatype stores variable length charcgter strings.  The information revealed by date is : 11 Oragle 10 g Material .

4712 BC to DECEMBER 31.  It can be a number in the range of 0 – 9 . 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 are stored inernally. RAW and LONG RAW are variable length data types They are mostly used to store graphics. Image. 9999 AD.  It stores * Day * Minute * Month * Second * Year * Hour Syntax : TIMESTAMP [ { Fractional – Seconds – Precision } ]  Fractional – Seconds – Precision optionally specifies the number of digits in the fractional part of the SECOND datetime field. sounds documents etc. Timestamp Data Type :  It is an extension of the DATE data type.  The Date range provided by Oracle is JANUARY 1. Video and Spatial data. Raw & Long Raw Data Types :      RAW and LONG RAW data types are intended for storage of binary data or Byte Strings.  The default time accepted by ORACLE date is 12 : 00 : 00 AM ( Midnight )  The default date accepted by ORACLE data is the First day of the Current Month. which can refer to out-of-line or in-line LOB values. The ORACLE converts the RAW & LONG RAW data into Hexadecimal form.Naresh i Technologies * Century * Date * Year * Hour * Month * Minute * Second  The default date format in ORACLE is DD-MON-YY.  The Bfile is an LOB which is stored externally  The LOB data types can store large and unstructured data like Text. with default as 6.  The maximum size is upto 4 GB  LOB columns contain LOB locators. and is specified in NLS – DATE – FORMAT. 12 Oragle 10 g Material .

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. The maximum size is 4 GB. SQL > Create Table LabSpecification ( ProdId Number(6). ProdGraphic BFILE. DOB Date. DOJ Date.  The rows address can be queried using the pseudo column ROWID.  ROWID’s efficiently support partitioned tables and Indexes.Naresh i Technologies  LOB’s selection actually returns the LOB’s locator. ProdPhoto BLOB. The BFILE locator maintains the directory alias and the filename. The Binary File LOB’s do not participate in transactions and are not recoverable. ROWID Data Type :  Each row in the database has as address. Example : SQL> Create Table Students ( StuId Number (6). BLOG Data Type :  It stored unstructured Binary Large Objects  They are Bit streams with no character set semantics.2). ProdDesc LONG 13 Oragle 10 g Material . A BFILE column or the attributes stores the BFILE locator. Fees Number(7. Fname Varchar2(30). NCLOB Data Type :  It stores Unicode data using the National Character set.  They are provided with full transactional support. Lname Varchar2(30). Gender Varchar2(1) ). BFILE Data Type :      It enables access to binary file LOB’s which are stored in the file systems outside ORACLE.

Lname. 30-MAR-95’. Populating the Data into Tables : INSERT Statement :  The INSERT statement is used to add rows to a Table Views Base Tables A partition of a Partition Table. …..’Raj’..’M’) . Examples: INSERTING DATA INTO ALL COLUMNS OF A TABLE : SQL> INSERT INTO STUDENTS VALUES (123.Naresh i Technologies ). ORACLE reuses free space in the table into which the data in being inserted and maintains referential integrity constraints. 25000. the free space is not reused. ’29-JAN-80’. ‘M’) .  The order in which the values are declared in the values clause should follow the same order as that of the original table order..  In this case the values should be provided to all the columns that exist inside the table. ‘Kumar’. Fname. A subpartition of a Composite_Partitioned Table An object table An object view’s base Table. COL2. ’20-Feb-85’. VALUE2.…. ‘ SAMPATH’. Syntax : INSERT INTO < TABLE-NAME > ( COL1. ORACLE appends the inserted data after existing data in the Table. Doj. INSERTING DATA INTO THE REQUIRED COLUMNS: SQL> INSERT INTO STUDENTS (Studno. 14 Oragle 10 g Material . o o Conventional INSERT Direct – path INSERT  In Conventional Insert statement.) . Gender) VALUES (1235. varchar and data type data should be declared in single quotes. ‘KUMAR’.  The char.  Insertion of data into a table can be executed in two ways. ) VALUES ( VALUE1..  In Direct-path insert .

Lname. Fname.  The targeted column should not be set as NOT NULL Constraint.  The values can be stored temporarily through 1. SQL> INSERT INTO STUDENTS (StudNo. EXPLICT → → Omit the column from the list. Gender) Values (1234. Sysdate. Fees. Gender) VALUES (1234. ’25-jan-80’. DOJ. Fees) 15 Oragle 10 g Material . NULL.  The columns for which the data is not supplied are filled with NULL values. USER FUNCTION :  It is special function. Double Ampersand (&&) 3. NULL.  The function returns the current date & time. SQL> INSERT INTO Students (StudNo.Naresh i Technologies  In this case the order of the columns declared in the SELECT list need not be the same order as that of the original table. IMPLICIT 2. Dob. Specify the NULL Keyword. Sysdate. Specify Empty String ‘ ‘ . DOJ. INSERTING NULL VALUES :  NULL Values can be inserted in two ways 1.’M’) . INSERTING SPECIAL VALUES : SYSDATE FUNCTION  It is a Pseudo column provided by the oracle. DOB. SUBSTITUTION VARIABLES :  These variables are used to stored values temporarily. Fname. SQL> INSERT INTO Students (StudNO. which records the current USER Name. 25000.  If the columns that were not supplied with data are declared with NOT NULL Constraints then the INSERT Statement is Rejected. Fname. Fname. USING SINGLE AMPERSAND SUBSTITUTION VARTIABLE : SQL> INSERT INTO Students (StudID. User. 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 variables applied for all instances until that SQL statement is existing. ‘Mohan’. Fees) Values (1234. ’28-FEB-04’. ‘M’) . DOJ. Fees. LName. only for character strings and dates. Single Ampersand (&) 2. DOB. ‘Suresh’. 30000) . Lname.  The data values in the values clause should match with that of SELECT list.’Krishna’.

16 Oragle 10 g Material . ‘& LastName’.Naresh i Technologies VALUES (&StudNo. ’&Location’ ) . ’&Department_Name’. Doj. Loc) VALUES (&Dapartment_Id. Fees. 25000) . the prompts can be customized.sql extension.sql REPLACE ALL QUERYING THE DATA FROM TABLES: QUERY: It is an operation that retrieves data from from one or more tables or views.sql SQL> SAVE D:\My Dir\SQLscript\Insert prompt. After creating a script using the substitutions variable to a file it can called with ACCEPT and PROMPT with greater meaning. ‘&FirstName’. Dob. Fname. Lname. EXAMPLE: ACCEPT Stud_id PROMPT ‘Please Enter the Student Number:’ ACCEPT Fir_name PROMPT ‘Please Enter the First Name:’ ACCEPT Cou_fees PROMPT ‘Please Enter the Course Fees:’ SQL> INSERT INTO Students (StudNo. &Gender) . 2. 3. ACCEPT Command stores the values in a variable.’&Fir_name’. ‘Dob’. DEFINING CUSTOMIED PROMPTS :     Using the ACCEPT Command of SQL *Plus. &Last Name. Fees) VALUES (&Stud_id . Gender) Values (&StudNo. If the file has to be replaced with the same existing name then use REPLACE ALL clause. EXAMPLE: SQL> SAVE D:\My Dir\SQLscript\Insert prompt. USING DOUBLE AMPERSAND SUBSTITUTION VARIABLE : SQL> INSERT INTO Students (StudNo. PROMPT Command displays the Customized text. ‘Date –of –Birth. &&Fees. Give the name of the file with . EXAMPLE: ACCEPT Department_Id PROMPT ‘Please Enter the Department Number:’ ACCEPT Department_Name PROMPT ‘Please Enter the Department Name:’ ACCEPT Location PROMPT ‘Please Enter the Location:’ SQL> INSERT INTO DEPT (Deptno. Sysdate. &Cou_fees) . Fname. Dname. At SQL prompt type the full name of the path where the file has to be created. ‘Name’. CREATING AN SQL SCRIPT FILE:  The SAVE Command is used to store the current contents of the SQL Buffer  Steps: 1.

Naresh i Technologies SELECT STATEMENT:  The SELECT statement is used to retrieve data from one or more tables .  COLUMN  Selects the Named Column. object tables . o JOIN :  It chooses the data in from one or more numbers of tables by creating a link between them.  Alias  Gives selected columns different columns.  The SELECT ANY TABLE allows to select the data from any recognized object. Basic SELECT Syntax : SELECT [ DISTINCT ] { * . 17 Oragle 10 g Material . object views or management views.views.. } From Table . FROM  Identifies Tables . o SELECTION :  o It chooses the rows in a table that are expected to return by a query. Column [ Alias ] . PROJECTION :  It chooses the columns in a table that are expected to return by a query. CAPABILITIES IF SQK SEKECT STATEMENT :  The SELECT statement can be used to select or Retrieve data from the object using any one of the following criteria.  FROM Table  Specifies the table containing the columns. PREREQUISITES :  The user must have the SELECT privileges on the specified object. SELECT  Identifies Columns. ….  SELECT  Specifies a list of Column ( one / more )  DISTINCE  Suppresses Duplicates  *  Select all Columns.

job. Retrieving Data from Specific Columns : Sql > Select empno. 18 Oragle 10 g Material . Sql > Select * from Salgrade.Naresh i Technologies WRITING SQL STATEMENTS TO SELECT OR RETRIVE DATA FROM TABLES : The Sample Tables Used : Table 1 : EMP Column Name Data Type -----------------------------------------------------Empno Ename Deptno Job Sal Comm Mgr Hiredate Table 2 : DEPT Column Name Data Type -----------------------------------------------------Deptno Dname Loc Table 3 : SALGRADE Column Name Data Type -----------------------------------------------------Hisal Losal Grade Retrieving Data from All Columns : Sql > Select * from Emp. ename. sal.  It projects data from all the columns existing in the table with all records. NUMBER NUMBER NUMBER NUMBER VARCHAR VARCHAR NUMBER VARCHAR NUMBER VARCHAR NUMBER NUMBER NUMBER DATE  In this the ‘ * ‘ is a projection operator. Sql > Select * from Dept. deptno form emp. sal from emp. Sql > Select ename.  The data is displayed in a table format.

o Addition  + * / o Subtraction  o Multiply o Divide   19 Oragle 10 g Material . Column Heading Defaults :  The default justification of the data after it is retrieved from the table is …. dname.     The column names need not be in the same order as table. Grade from Salgrade. Applying Arithmetical Operations in Select Statements :  Arithmetic Expressions can be implemented through SELECT statement.  Arithmetic Expressions can be implemented to o o o Modify the way the data is displayed... Losal. Perform calculations. Sql > Select Hisal. The column names can be separated onto different lines within the SQL Buffer. The columns should be separated using comma. But numb ers cannot be truncated. Implement WHAT – IF Scenarios. The casing of column names is not important. hiredate from emp.  The character and date column headings can be truncated. ename. Sql > Select empno. LEFT  Date and Character Data RIGHT  Numeric Data  The default display of the data is always is UPPER Casing.  An Arithmetic Expression can contain o o o Simple Column names Constant numeric values Arithmetic operators. sal .  The Arithmetic operators supported are …. loc from dept.Naresh i Technologies Sql > Select deptno. ARITHMETIC OPERATORS :  The Arithmetic operators can be used to create expressions on NUMBER and DATE data.

( 12 * sal ) + 100 from Emp. job. 12 * sal + comm from Emp . the return value is always the same as the data type of Expr1. sal. 20 Oragle 10 g Material . sal. sal. sal + 500 from emp. Handling Null Values : NULL : It is a value which is  Unavailable  Unassigned  Unknown  Inapplicable A NULL is not same as zero or blank space. Except the FROM clause. job. sal.  NVL Function can be used to convert any data type. Sql > Select ename. Sql > Select empno.  SQL * Plus ignores Back Spaces before and after the Arithmetic operator. comm From Emp .Naresh i Technologies  The Arithmetic operators can be used in any clause of a SQL statement. ename. Sql > Select empno. If a row lacks the data for a particular column. sal – 1000 from emp. comm. Expr2 )   Expr1 : is the source value or expression that may contain NULL. Sql > Select empno. than that value is said to be NULL or to contain NULL. Expr2 : is the target value for converting NULL.   NVL Function :  The NVL function is used to convert a NULL value to an actual value. sal. ename. the overall result is also NULL. job. ename.)  Operators of the same priority are evaluated from left to right. comm. Sql > Select ename. Operator Precedence :  Multiplication and Division take priority over addition and subtractions ( * / + . Syntax : NVL ( Expr1 . ename. 12 * ( sal + 500 ) from Emp.  The above situation is termed as NULL propagation and has to be handled very carefully.  If any column value is an Arithmetic expression is NULL. sal. sal. 12 * Sal + comm From Emp . Sql > Select ename.  To prioritize evaluation and to increase clarity parenthesis can be implemented. Sql > Select empno.

’01-JUN-99’) NVL ( Job . 0 ) From Emp. Sql > Select Empno Numbers.  The types of Literals recognized by Oracle are 21 Oragle 10 g Material . “ Maximum Range “ . any where in the SELECT list for operational purpose.  The AS keyword can be used between the Column Name and Alias. 0 ) From Emp. Sal. “ Department Name “ . Sal + NVL ( Comm. Place Sql> Select Hisal As Losal As Grade From Salgrade . 0 ) NVL ( Hiredate . Working with Aliases :  An Alias is an alternate name given for any Oracle Object. ( Sal * 12 ) + NVL (Comm . Comm. Job Designation From Emp.  An alias effectively renames the SELECT list item for the duration of the query. 0 ) From Emp. ( Sal + 500 ) + NVL ( Comm . Sal. Sql > Select Ename. Comm.  An alias cannot be used.  The Alias should be declared in double quotes if it is against the specifications of Naming Conversions.  Aliases is Oracle are of two types ** Column Alias ** Table Alias  Column Alias Renames a Column Heading  The Column alias is specified in the SELECT list by declaring the Alias after the Column Name by using the space separator. Sql> Select Deptno AS Dname AS Loc AS From Dept. LITERALS IN ORACLE :  A Literal and a Constant value are synonyms to one another and refer to a fixed data value. Sal. Comm. Sal “Basic Salary”. Sql > Select Ename. “ Minimum Range “ .Naresh i Technologies  The Data types of the Source and Destination must match o o o NVL ( Comm . ‘Not Assigned’) Sql > Select Ename. Ename Name.  ALIAS Headings appear is UPPER Casing by default. “ Department Id ” .

 It should be enclosed in single quotes  They have properties of both CHAR and VARCHAR2 data types.Naresh i Technologies o o o o Text Literals : Text Literals Integer Literals Number Literals Interval Literals  It specifies a text or character literal. Date and character literals must be enclosed within the single quotation marks ‘ ‘ Literals increase the readability of the output. Sql > Select Ename | | ‘ Works in Department Number ‘ | | Deptno | | ‘ as ‘ | | Job From Emp . Sql > Select Ename | | ‘ : ‘ | | ‘ Month Salary = ‘ | | Sal As Salaries From Emp . that is retrieved by the SELECT statement. A literal is not a column name or a column alias. Designation is ‘ || Job “ Employees Information “ 22 Oragle 10 g Material . Sql > Select ‘ The Annual Salary of ‘ | | Ename | | ‘ is ‘ | | Sal * 12 As Annual_Salary From Emp .  The Concatenation operator is represented in Oracle by double pipe symbol ( | | ) Sql > Select Empno || Ename || ‘ . or a Date.  It is used to specify values whenever ‘text’ or CHAR appear in ** Expression ** Condition ** SQL Function ** SQL Statements. Sql > Select Ename | | ‘ Joined the Organization on ‘ | | Hiredate From Emp .  The resultant column is treated as an character expression. A literal is printed for each row. Sql > Select ‘ The Designation of ‘ | | Ename | | ‘ is ‘ | | Job As Designation From Emp. Sql > Select Dname | | ‘ Department is Located at ‘ | | Loc From Dept . Arithmetic expressions. Ex : ‘ mployee Information ‘ ‘ Manager”s Specification ‘ N ‘n char Literal ‘ Using Literal Character Strings :       A literal that is declared in a SELECT list can be a character. Applying Concatenation Operator :  The Concatenation operator links columns to other columns. or constant values. Literal strings of Free-Form test can be included in the query as per the requirement.  A text literal can have a maximum length of 4000 Bytes.  Columns on either side of the operator are combined to make a single output column. a Number.

Job From Emp . Sql > Select DISTINCT Deptno . ^ = . Sql > Select ‘ The Basic Salary of ‘ || Ename || ‘ is Rs ‘ || Sal Employee From Emp . The DISTINCT qualifier affects all the selected columns. ! = . Eliminating the Duplicate Rows from the Output :     Until it is instructed SQL * Plus displays the results of a query without eliminating duplicate rows.  A WHERE Clause contains a condition that must be met and should directly follow the From Clause. Sql > Select DISTINCT Deptno From Emp .  Character values are case sensitive and Date values are format sensitive (DD-MON-YY)  The Comparison operator are used in conditions that compare one expression to another.  The different comparison operators are ** = ** < > . constant or list of values. Deptno From Emp . Filtering of Records :  The number of rows returned by a query can be limited using the WHERE clause. Sql > Select DISTINCT Job .Naresh i Technologies From Emp . the DISTINCT keyword is used. …. To eliminate the duplicate rows in the result.  The Character strings and dates should be enclosed in single quotation marks.} From Table [ WHERE Condition(s) ] . Multiple columns can be declared after the DISTINCT qualifier. ** > ** < ** > = ** < =  The format of the WHERE clause is WHERE Expr operator value. Syntax : SELECT [ Distinct ] { * | Column [ alias ] . Examples : 23 Oragle 10 g Material .  The WHERE clause can compares ** ** ** ** Values in Columns Literal Values Arithmetic Expressions Functions  The components of WHERE clause are ** Column Name ** Comparison Operator ** Column Name. and represents a distinct combination of the columns.

Job. Ename. Deptno.Naresh i Technologies Sql > Select Ename. Ename. Sal. Logical Operators :  The Logical operators combine the results of two components conditions to produce a single result. Deptno. Job From Emp Where ( Sal > = 1500 AND Sal < = 5000 ) AND Job = ‘MANAGER’ . Sal Basic . Sql > Select Ename. Sql > Select Ename Name . Sql > Select Empno. else returns unknown. Sal From Emp Where Deptno = 10 . Sal. Job From Emp Where Job = ‘ MANAGER ‘ Sql > Select Ename. Sal From Emp Where Sal > = 3000 . Sal From Emp Where Sal > = 1100 AND Job = ‘CLERK’ . Sql > Select Ename || ‘ Joined on ‘ || Hiredate “ Employees Joining Dates “ From Emp Where Hiredate = ‘ 01 – JAN – 95 ‘ . Ename . OR Operator :  It returns TRUE if either component conditions is TRUE 24 Oragle 10 g Material . Hiredate . Job From Emp Where Sal > = 1500 AND Sal > 5000 .  The Logical operators provided by Oracle are ** AND Operator :  It Returns TRUE if both or all component conditions are TRUE. Sal * 12 Annual From Emp Where Sal * 12 > 6000 . Sal From Emp Where Deptno = 10 AND Job = ‘MANAGER’ . Job From Emp Where Job < > ‘ CLERK ‘ . Job . Sql > Select Ename. Sal .  Truth Table : AND TRUE FALSE NULL TRUE T F NULL FALSE F F F NULL NULL F NULL AND ** OR ** NOT Sql > Select Empno. Sql > Select Ename. Sal. Sql > Select Empno.  It Returns FALSE if either is FALSE. Sql > Select Ename || ‘ Works in Department ‘ || Deptno ‘ Employees and Deaprtments ‘ From Emp Where Deptno < > 20 .

else returns unknown  Truth Table : OR TRUE FALSE NULL TRUE T T T FALSE T F NULL NULL T NULL NULL Sql > Select Empno. Ename. Sal. Deptno From Emp Where Deptno = 10 OR Deptno = 20 . Sal From Emp Where Deptno = 10 OR Job = ‘MANAGER’ . Sql > Select Ename. NOT Operator :  It returns TRUE if the following condition is FALSE. Job. Sal From Emp Where Sal > = 1100 OR Job = ‘CLERK’ . Sql > Select Ename. it returns Unknown. Job. Job From Emp Where NOT Sal > 5000 . Job From Emp Where NOT Job = ‘MANAGER’ . Sal. Sql > Select Empno. Sql > Select Ename. Sal. Sql > Select Empno. Sal. Job From Emp Where Job = ‘CLERK’ OR Job=’MANAGER’ .Naresh i Technologies  It returns FALSE if both are FALSE. Job. Ename. Sql > Select Ename. Job. Sal From Emp Where ( Deptno = 10 AND Job = ‘MANAGER’ ) OR Sal > = 3000 . Ename. 25 Oragle 10 g Material . Job From Emp Where ( Sal < = 2500 OR Sal > = 5000 ) OR Job = ‘MANAGER’ . Sal From Emp Where ( Sal > 1100 OR Job=‘CLERK’ ) AND Deptno = 20 . Sql > Select Ename.  Truth Table : TRUE NOT F FALSE T NULL NULL Combination of AND and OR Operators : Sql > Select Empno. Not Operator Examples : Sql > Select Ename. Sal.  It returns FALSE if the following condition is TRUE. Sal. Job.  If the condition is Unknown. Job From Emp Where Sal > = 1500 OR Sal > = 5000 . Ename.

Job From Emp Where NOT Job > ‘MANAGER’ . Job From Emp Where Job > ‘MANAGER’ . Sal. Hiredate From Emp Where NOT Hiredate = ’17-DEC-1980’ . Sal. Sal. Job From Emp Where Job < ‘MANAGER’ . Sal. 26 Oragle 10 g Material . Sal. Sql > Select Ename. Sql > Select Ename. Sql > Select Ename. SQL * PLUS Operators :  BETWEEN …. This Operator is used to display rows based on a range of values.. . AND …. Sql > Select Ename. Sal. Sal. AND …. Hiredate From Emp Where Hiredate<>’20-FEB-1981’ . o NOT BETWEEN …. Hiredate From Emp Where Hiredate < ’20-FEB-1981’ . Job From Emp Where NOT Sal < 5000 . Sal. Sql > Select Ename. Hiredate From Emp Where Job < > ‘CLERK’ . Sql > Select Ename. Sal. Sal. Sql > Select Ename. Some Things To Note ……. Rules of Precedence :  The default Precedence order is ** All Comparison Operators ** NOT Operator ** AND Operator ** OR Operator  The Precedence can be controlled using parenthesis. Sql > Select Ename. Sal.Naresh i Technologies Sql > Select Ename. Sql > Select Ename. Hiredate From Emp Where Not Hiredate=’20-FEB-81’ . Sal. Deptno From Emp Where NOT Job = ‘ SALESMAN’ AND Deptno = 30 . Sql > Select Ename. Hiredate From Emp Where Hiredate > 20-FEB-1981’ . Comm From Emp Where Comm is NULL . Job. Sql > Select Ename. Sql > Select Ename. Sal. Hiredate From Emp Where NOT Hiredate > ’17-DEC-1980’ .

LIKE Operator . Job From Emp Where Ename IN( ‘FORD’. NOT LIKE Operator : 27 Oragle 10 g Material . Sql > Select Ename. Comm From Emp Where Comm IS NULL . Deptno From Emp Where Deptno NOT IN( 10 . ’09-JUN-1981’ ) . Deptno. Hiredate From Emp Where Hiredate IN( ’20-FEIB-1981’ . 30 ) . ‘ALLEN’ ) . Sal. Hiredate From Emp Where Hiredate NOT Between ’17-FEB-1981’ AND ’20-JUN-1983’ . 30 ) . ‘ALLEN’ ) . Sal. Comm From Emp Where Mgr IS NOT NULL . Job From Emp Where Mgr IS NULL . Sql > Select Ename. Sal.  NULL means the value is unavailable. Job. Deptno From Emp Where Deptno IN( 10 .  The Operator can be used upon any datatype. Sal. Unknown. Sal. Hiredate From Emp Where Hiredate Between ’17-FEB-1981’ AND ’20-JUN-1983’ . Job From Emp Where Sal Between 1000 AND 1500 . Sql > Select Ename. IS NULL Operator . Sql > Select Ename. Unassigned. Sql > Select Ename. Sal.Naresh i Technologies o o The declared range is inclusive The lower limit should be declared first. Deptno. Comm From Emp Where Comm IS NOT NULL . Sql > Select Ename. Sql > Select Ename. Deptno. Sal. Sal. Sql > Select Ename . Sal. Sql > Select Ename. Sql > Select Ename. or inapplicable. Sal. Sql > Select Ename. Job From Emp Where Job Between ‘MANAGER’ AND ‘SALESMAN’ . Job From Emp Where Sal NOT Between 1000 AND 1500 . Sql > Select Ename. Sal. IS NOT NULL Operator :  The Operator tests for NULL values  lt is the only operator that can be sued to test for NULL’s. Sql > Select Ename. Deptno. Sql > Select Ename. ’09-JUN-1981’ ) . Job From Emp Where Job NOT Between ‘MANAGER AND ‘SALESMAN’ . Hiredate From Emp Where Hiredate NOT IN( ’20-FEIB-1981’ . Job. Sql > Select Ename. IN Operator . Sal. Sql > Select Ename. NOT IN Operator :  The Operator is used to test for values in a specified list. Job From Emp Where Ename NOT IN( ‘FORD’ .

Syntax : SELECT Expr From Table Name [ WHERE Condition(s) ] [ ORDER BY { Column.Naresh i Technologies  The LIKE Operator is used to search to search for a matching character. which is ‘ \ ‘ symbol with ESCAPE Option. Job From Emp Where Ename LIKE ‘_A%’ .  Default ordering of Data is Ascending ** Numbers ** Dates ** Strings 1 – 999 Earliest – Latest A – Z . NULLS  Last. Job From Emp Where Ename NOT LIKE ‘S%’ . Ordering Information :  The Order of rows returned in a query result is undefined. Sql > Select Ename. Sql > Select Ename. Sql > Select Ename Sal From Emp Where Ename = ‘SM%’ . Hiredate From Emp Where Hiredate LIKE ‘%-FEB-1981’ . only at that position only. 28 Oragle 10 g Material .  An expression or an alias can be specified to sort. Hiredate From Emp Where Hiredate LIKE ’03-%-1981’ . /  Represents any single character.  The ORDER BY Clause can be used to sort the rows  The ORDER BY Clause should be the last clause in the order of all clauses in the SELECT statement. Sql > Select * From Dept Where Dname LIKE ‘%\_%’ ESCAPE ‘\’ . Job From Emp Where Ename LIKE ‘S%’ . Sql > Select Ename Job From Emp Where Ename NOT LIKE ‘_A%’ . Sql > Select Ename. Sql > Select Ename.  The Wild Card symbols can be used in any combination with literal characters. Sql > Select Ename.  For finding exact match for ‘ % ‘ and ‘ – ‘ the ESCAPE option has to be used. Expr } [ ASC / DESC ] ] . Sql > Select Ename. Sal From Emp Where ‘SM%’ LIKE Ename .  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.

** NUMBER ** DATE ** CONVERSION Syntax : Func_Name ( Column / Expr. Ename DESC . Sal * 12 Annsal From Emp ORDER BY Annsal .  Sorting can be implemented on column aliases.  The controversy of sorting is broken only when there arises a conflict of consistency upon the data in a column. [ Arg1. Hiredate . Hiredate From Emp ORDER BY Hiredate . Arg2.Naresh i Technologies  The default ordering upon a column is Ascending.  An argument can be : ** ** ** ** User Supplied Constant. Single Row Functions :  They are used to manipulate data items. ……] ) 29 Oragle 10 g Material . Expression. Sal From Emp Where Sal > = 2000 ORDER BY Hiredate. Ename. Sal DESC . Sal. Deptno. Job. Sal. Sql > Select Empno. Sql > Select Ename.  The single row functions can appear in ** ** ** ** SELECT List WHERE List START WITH Clause CONNECT BY Clause  The types of single row functions are ** CHARACTER Multiple Row Functions :  These functions manipulate groups of rows to give one result per group of rows. Sql > Select Empno. Deptno.  They accept one or more arguments and return one value for each row returned by the query. Sql > Select Ename. Hiredate From Emp ORDER BY Hiredate DESC . Ename. to change the default ordering DESC should be used after the column name. Sql > Select Ename. Sql > Select Ename. Ename. Sql > Select Empno. Sal From Emp Where Job = ‘MANAGER’ ORDER BY Sal . Job. Variable Value. and can also be implemented upon multiple columns. Job. Job. Column Name. Sal From Emp Where Sal > = 2500 ORDER BY Job. Sal From Emp ORDER BY Deptno.

 Date Functions : Operate on values of date data type. LOWER ( Ename ) From Emp Where Job = ‘MANAGER’ . then the return value is truncated. ** CASE CONVERSION FUNCTIONS. Sql > Select Ename. limited to a length of 4000 Bytes If the return value length exceeds. Sql > Select ‘ The ‘ || Ename || ‘ “ s Designation is ‘ || Job From Emp 30 Oragle 10 g Material .  Conversion Function : Covert a value from one data type to another. Character Functions :     They are functions that return character values. The functions are categorized as ** CHARACTER MANIPULATION FUNCTIONS. Return one result per row May return a data value of a different type than that referenced May expert one or more arguments. They return the data type VARCHAR2.  Number Functions : Accept Numeric input and return Numeric Values.Naresh i Technologies Single Row Functions Features :       Acts on each row returned in the Query. unless stated. Can be used in SELECT. LOWER ( ‘ MY INFORMATION’ ) From Emp.  General Functions : ** NVL  Operates on NULL Values. Sql > Select Ename. Specification Behavior of Functions :  Character Functions : Accept Character input and can return both Character and Number Values. ** DECODE  Operates on any data type and can return any data type. can return both Date and Number. Can be nested. WHERE and ORDER BY Clauses. without an error. Character Manipulation Functions : 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 LOWER( ‘ORACLE CORPORATION’ ) From Dual .

Initcap ( Ename ).  Words re delimited by White spaces or characters that are not alphanumeric. Sql > Select ‘ The Job Title for ‘ || Initcap ( Ename ) || ‘ is ‘ || lower ( Job ) Details From Emp. Sql > Select Ename. Upper ( Ename ) . INITCAP Function :  It converts the Alpha character values to Uppercase for the first letter of each word.  It return the character data type. 31 Oragle 10 g Material . keeping all other letters in Lower case. Sql > Select Ename. Only two parameters accept . Sql > Select Ename. Lower ( Ename ).Naresh i Technologies Where LOWER ( Job ) = ‘ manager’ . Lower ( Ename ) . CONCAT Function :  It Concatenates the first characters value to the second charactger value. Upper ( ‘clerk’ ) ) Order By Sal Desc . Sql > Select Ename. Upper ( ‘ My Information ‘ ) From Dual . Sql > Select Upper ( ‘ The ‘ || Ename || ‘ “ s Basic Salary is Rupees ‘ || Sal ) “Employee Salaries “ From Emp Where Job In( ‘MANAGER’ . Initcap ( Ename ) From Emp . Sal. Upper ( Ename ) From Emp Where Job = ‘MANAGER’ . Job From Emp Where Job = Upper ( ‘Manager’ ) . Sql > Select Ename. Syntax : UPPER ( Column / Expression ) Sql > Select Upper ( ‘ Oracle Corporation’ ) From Dual . Job. Deptno From Emp Where Ename = Upper ( ‘blake’ ) . Sql > Select ‘ The ‘ || Ename || ‘ “ s Designation is ‘ || Lower ( Job ) Where Job = Upper ( ‘manager’ ) Order By Sal . Syntax : INITCAP ( Column / Expression ) Sql > Select Initcap ( ‘oracle corporation’ ) From Dual .  The return value has the same data type as the argument char. Sal * 12 From Emp Where Job = Upper ( Lower ( ‘MANGER’ ) ) . Sql > Select Empno. Upper Function :  It Converts the Alpha character values to Upper Case.

0 . 3. If n is Omitted . Floating point numbers passed as arguments to Substr are automatically converted to Integers. Sql > Select Ename. it return NULL . If n is less than 1 or 0 . to ‘ n ’ characters long. If m is Negative. -5. Sql > Select Substr ( ‘ABCDEFGH’ . Sql > Select Ename. Concat ( Ename. 4 ) From Dual . o o o o o  If m is 0 .  If the char is NULL . starting from a specified position ‘ m ’ . Sql > Select Concat ( Initcap ( Ename ) . Sql > Select Substr ( ‘ABCDEFGH’. m. Syntax : SUBSTR ( Col / Expr. Oracle returns all characters to the end of Char. 4 . Concat ( ‘ is a ‘ . Sql > Select Concat ( ‘ The Employee Name is ‘ . Sql > Select Substr ( ‘ABCDEFGH’ . 3 ) ). 3 ) = Upper( ‘age’ ) . Sql > Select Concat ( Concat ( Initcap ( Ename ). Job ) From Emp Where Deptno = 10 . A NULL is returned. ‘Corporation’ ) From Dual . Column2 / Expr2 ) Sql > Select Concat ( ‘Oracle’ . 4. ‘ is a ‘ ) . -2 ) From Dual . 4.4 ) From Dual . 3 ) = Upper ( ‘Age’ ) . Job ) Job From Emp Where Deptno in( 10. it is treated as 1. 4. 20 ) . Oracle counts from the beginning of char to find the first character. Points to Remember …….’ ) ) ) From Emp Where Substr ( Job . Sql > Select Substr ( ‘ABCDEFGH’. Oracle counts backwards from the end of the Character. If m is positive.Naresh i Technologies Syntax : CONCAT ( Column1 / Expr1. 1. 4 ) From Dual . Concat ( Initcap (Substr ( Job. n ) Sql > Select Substr ( ‘ABCDEFGH’ . the length includes all trailing blanks. SUB STRING Function :  Returns specified characters form character value. Job From Emp Where Substr ( Job. Initcap ( Ename ) ) As “Employee Names “ From Emp Where Deptno in( 10. 32 Oragle 10 g Material . 4 ) From Dual . ‘Eater. Job. 30 ) .  If the char has data type CHAR. 0 ) From Dual . Sql > Select Substr ( ‘ABCDEFGH’ . LENGTH Function :  Returns the number of characters in a value.

2 ) From Dual . Sql > Select Instr ( ‘CORPORATE FOOR’.  The value of ‘ m ‘ should be positive . 3 ) ) ) = ‘AGE’ .Naresh i Technologies Syntax : LENGTH ( Column / Expression ) Sql > Select Length ( ‘ORACLE’) From Dual . 4. LPAD Function :  Pads the character value right justified to al total width of n character positions. 2. Sql > Select Instr ( ‘CORPORATE FLOOR’. Instr ( Job. 33 Oragle 10 g Material . -3. Job from Emp Where Length ( Job ) = 7 . Char .’ ) From Dual . 4. Sql > Select Inticap ( Ename ) . Syntax : INSTR ( Column / Expression.‘ As “Names and Lengths “ From Emp . n. ‘A’. if negative searches backward from the end of column / Expression. ‘*. 2 ) From Dual . ‘A’. 15. Sql > Select Job. Instr ( Job. Sql > Select Initcap( Ename ) . Char 2 ) Sql > Select Lpad ( ‘Page 1’. INSTRING Function :  It returns the numeric position of a named character. that is the first character of this occurrence. Sql > Select Job.  The return value is relative to the beginning of char1 regardless of the value of n.  ‘ n ‘ can be positive or negative. 2 ) From Emp Where Job = ‘MANAGER’ . 3. 1. Sql > Select Job. m )  Searches for Column / Expression beginning with its ‘ n ‘th character for the ‘ m ‘th occurrence of char2. Instr ( Job. Syntax : LPAD ( Char1. 2 ) From Emp Where Job = ‘MANAGER’ . Sql > Select Job. ‘A’. 3. ‘r’) From Dual . ‘OR’. and is expressed in characters. and returns the position of the character in char1. Job From Emp Where Substr ( Job. Length ( Substr ( Job.  The default values of both m and n are 1. Sql > Select Length ( Ename ) || ‘ Characters exit in ‘ || Initcap ( Ename ) || ‘ “s Name.  The default padding character is space. n. Sql > Select Lpad ( ‘Page 1’. the return value is zero. 2) From Emp Where Job = ‘MANAGER’ . Sql > Select Instr ( ‘String’ .  If the search is unsuccessful. 2 ) From Emp Where Job = ‘MANAGER’ . ‘A’. Instr ( Job. ‘OR’. 15) From Dual .

Rpad(Ename. set ) Sql > Select Rtrim ( ‘BROWNINGyxXxy’.  The Default padding character is space. Sql > Select Ename. Sql > Select Ename. RTRIM Function :  It enables the trimming of trailing characters from a character String. ‘-‘ ). Syntax : RPAD ( Char1. If Leading is specified concentrates on leading characters. Job From Emp Where Ltrim ( Job . n. 15 ) From Dual . 10. Sql > Select Rpad ( ‘Page 1’ . Syntax : RTRIM ( Char. ‘xy’ ) From Dual . Returns the varchar2 type. 10.’ ) From Dual . RPAD Function :  Pads the character value left justified to a total width of n character positions. ‘-‘ ) From Emp . ‘*. Sql > Select Trim ( ‘S’ From ‘SSMITH’ ) From Dual . set ) Sql > Select Ltrim ( ‘xyzXxyLAST WORD’. Lpad (Ename. Sql > Select Rtrim ( Job. ‘-‘ ) .Naresh i Technologies Sql > Select Ename. Sql > Select Job. 34 Oragle 10 g Material . ‘xy’ ) From Dual . ‘ER’ ) . ‘MAN’ ) Like ‘GER’ . 15. 10. ‘-‘ ) From Emp . TRIM Function ( 8 i )      It enables to trim heading or trailing characters or both from a character string. Char 2 ) Sql > Select Rpad ( ‘Page 1’ . Rpad ( Ename.  All the leftmost characters that appear in the set are removed. Lpad ( Ename. Ltrim ( Job ) From Emp Where Job Like ‘MANAGER’ . 10. Lpad ( Rpad ( Ename. 10. Trim character From Trim source ) Sql > Select Trim ( ‘S’ From ‘MITHSS’ ) From Dual . ‘-‘ ) from Emp Where Sal > = 2500 . Sql > Select Ename. LTRIM Function :  It enables to trim heading characters from a character string. Syntax : TRIM ( Leading / Trailing / Both.  All the right most characters that appear in the set are removed. Syntax : LTRIM ( Char. 15. If Both or none is specified concentrates both on leading and trailing. ‘-‘ ) From Emp Where Sal > = 2500 . If Trailing is specified concentrates on trailing characters.

Syntax : TRANSLATE ( char. 35 Oragle 10 g Material . all occurrences of search string are removed. CHR Function :  It returns a character having the binary equivalent to ‘ n ‘. Sql > Select Job. Replace_Str ) Sql > Select Replace ( ‘Jack and Jue’ . To )  It returns a char with all occurrences of each character in ‘ From ‘ replaced by its corresponding character in ‘ To ‘. Sql > Select Chr ( 16705 Using NCHAR_CS ) From Dual .  It substitutes one string for another as well as to remove character strings. Search_Str. ‘A’. ‘P’ ) From Emp Where Job = ‘PRESIDENT’ . Translate ( Job. ‘DAM’ ) From Emp Where Job = ‘MANAGER’ . Sql > Select Job. Translate ( Job. Sql > Select Job. ‘ ‘ ) From Emp Where Job = ‘PRESIDENT’ . Replace(Job. Syntax : CHR ( n ) CHR ( n Using NCHAR_CS ) Sql > Select Chr ( 67 ) || Chr (65 ) || Chr ( 84 ) Sample From Dual . Sql > Select Trim ( Trailing ‘S’ From ‘SSMITHSS’ ) From Dual . Replace ( Job. REPLACE Function :  It returns the every Occurrence of search string replaced by the replacement string.  The argument From can contain more characters than To. Translate ( Job. Sql > Select Trim ( Both ‘S’ From ‘SSMITHSS’ ) From dual . Sql > Select Trim ( Leading ‘S’ From ‘SSMITHSS’ ) From Dual . ‘MAN’. Sql > Select Job. ‘P’. Syntax : REPLACE ( Char. they are removed from the return value.  If the replacement string is omitted or null. ‘MN’. ‘MAN’. TRANSLATE Function :  Used to Translate Character by character in a String . ‘BL’) From Dual . ‘EXECUTIVE’ ) From Emp Where Job = ‘SALES MAN’ . From. ‘DM’ ) From Emp Where Job = ‘MANAGER’ .  If the extra characters appear in Char.Naresh i Technologies Sql > Select Trim ( ‘S’ From ‘SSMITHSS’ ) From Dual . ‘J’.  Characters in char that are not in From are not replaced. ‘O’ ) From Emp Where Job = ‘SALESMAN’ .  It returns the equivalent for ‘ n’ in database character set or national character set. Sql > Select Job. Sql > Select Ename. Replace ( Job.

Naresh i Technologies ASCII Function :  It returns the decimal representation in the character database set of the first characters of the Char.79. Sql > Select Round ( 45923. 0 ) .7 ) From Dual . 1) From Dual . ROUND Function : Syntax : ROUND ( n. Round ( 45. places ‘ m ‘ can be negative.  The adjustment is done to the highest nearest decimal value. and rounds off the digits to the left of the decimal point. Sql > Select Round ( 15.193. -1 ) From Dual .  Many functions return values that are accurate to 38 decimal digits.  ‘ n ‘ can be negative to truncate m digits left to the decimal point. Trunc ( 42.193. M must be an integer. Round ( 45. -1 ) From Dual . m )     It returns ‘ n ‘ rounded to n places right of the decimal point.79. 36 Oragle 10 g Material . -1 ) From Dual . -1 ) From Dual .923.923.923. Sql > Select Trunc ( 15. Sql > Select Ceil ( 15. m )  It returns n truncated to m decimal places. TRUNCATE Function : Syntax : TRUNC ( n. Sql > Select Trunc ( 45. CEIL Function : Syntax : CEIL ( n )  Returns the smallest integer greater than or equal to ‘ n ‘ . Ascii ( ‘APPLE’) From Dual . NUMBER Functions :  These functions accept numeric input and return numeric values. 2 ) . n is rounded to 0. 2 ) . Trunc ( 45.923 ). Sql > Select Trunc ( 15. Sql > Select Round ( 15. Syntax : ASCII ( Char ) Sql > Select Ascii ( ‘A’ ) . n is truncated to 0 places.  If ‘ m ‘ is omitted.923. If ‘ m’ is omitted. 1 ) From Dual .

-2 ) . Power ( -3. 2 ) From Dual .Naresh i Technologies Sql > Select Ceil ( 14. MODULUS Function : Syntax : MOD ( m. -2 ) From Dual . Floor ( 14. Power ( -3.2 ) . Sql > Select Power ( -3. Floor ( 14 ) From Dual . Power ( 3.5.5 ) From Dual . Power ( 3. Sql > Select Floor ( 15.5.2 ) . Mod ( 10 . n )  It returns remainder m divided by n . FLOOR Function : Syntax : FLOOR ( n )  Returns the largest integer less than or Equal than n .  It returns m if n is 0. -2 ).5 ) From Dual .5 ) . Ceil ( 14. n must be an integer Sql > Select Power ( 3. Sql > Select Floor ( 14. SQUARE ROOT Function : Syntax : SQRT ( n )  It returns square root of n. Ceil ( 14 ) From Dual .7 ) From Dual . 4 ) .27 ) . Sql > Select Sqrt ( 25 ) From Dual . n )  Returns m raised to the nth power. Sql > Select Power ( -3. Sql > Select Power ( 3. ABSOLUTE Function : Syntax : ABS ( n ) 37 Oragle 10 g Material . 2 ). 2.  The base m and the exponent n can be any numbers. -2. -2. POWER Function : Syntax : POWER ( m. Sql > Select Mod ( 11.5.  The value of n cannot be negative  SQRT returns a real result. 2 ) From Dual .27 ) .  If m is negative.  The adjustment is done to the lowest nearest decimal values.

If n < 0 . Sql > Select Sal.  Number constants can be added or subtracted upon dates. The dates in Oracle range from January 1.Naresh i Technologies  It returns the absolute value of n. 9999 AD. Sal – Comm. Date – Date  Number of days . SIGN Function : Syntax :     SIGN ( n ) It returns the SIGN. Adds Number of Hours to a date. Sql > Select Abs ( -15 ) From Dual . Arithmetic operations can be implemented. Sql > Select Sysdate. Comm. Sign( Sal – Comm ) From Emp Where Sign( Sal – Comm ) = -1 WORKING WITH DATES :     Oracle stores dates in an internal numeric format. specification of a number. The numeric format represents ** Century ** Minutes SYSDATE :  It is a date function that returns current date and time . ** Year ** Seconds ** Month ** Day ** Hours Sql > Select Sysdate.  The operations that can be applied are o o o o Date + Number  Date . Sysdate +_ 72 / 24 From Dual . 38 Oragle 10 g Material . Comm. Sysdate + 3 From Dual . Sql > Select SYSDATE From Dual . Sysdte – 3 . Abs ( Sal – Comm ) From Emp Where Comm = 1400 . return 0 If n > 0. Date Arithmetic :  As database stores dates as numbers. return 1 Sql > Select Sign ( -15 ). 4712 BC to December 31. return –1 If n = 0 . Sign ( 15 ) . Date + Number / 24  Date .  SYSDATE is generally selected upon a DUMMY Table. Sql > Select Sal.Number  Date : Subtracts Number of days from a date. The default display and input format for any date is DD-MON-YY. Adds number of days to a date Date . Sign ( 0 ) From Dual . Subtracts one date from another.

Hiredate – 3 From Emp .  Mostly used to determine how many days are left in the current month .l Hiredate. Sql > Select Ename. Sql > Select Sal. Sql > Select Empno. Hiredate. Hiredate + 3 From Emp . 2 ) From Emp Where Deptno = 20 . Sql > Select Ename. Sql > Select Sysdate. Sql > Select Ename.  The CHAR must be a day of the week in the sessions date language. Next_Day Function: Syntax : Next_day( d.  The day of the week can be full name or the abbreviation. ‘MONDAY’ ) From Dual . Last_Day Function : Syntax : Last_day ( d )  It returns the date of the last day of the month that contains d. 2 ) From Dual . Hiredate ) From Emp Where Months_Between ( Sysdate. Next_day ( Sysdate. Char )  It returns the date of the first week day named by char. Add_months ( Sysdate.Naresh i Technologies Sql > Select Ename. Add_months ( Hiredate. Months_Between ( Sysdate . Months_Between Function : Syntax : Months_Between ( D1. D2 )  It returns number of months between dates d1 and d2. Hiredate. the result is Positive. the result is always an integer. Sysdate – Hiredate From Emp . Sql > Select Ename. that is later than the date d. Hidrdate. 39 Oragle 10 g Material . Sql > Select Sal. DATE Functions : Add_Months Function : Syntax : ADD_MONTHS ( D. Hiredate ) From Emp . Hiredate. Hiredate.  If d1 is and d2 are either the same days of the months or both last days of the months. n )  It returns the date d plus n months  The argumennt n can be any integer Sql > Select Sysdate . Next_day ( Hiredate. Months_Between ( Sysdate . else Negative. ‘WED’ ) From Dual . Hiredate ) < 2000 .  If d1 is later than d2. ( Sysdate – Hiredate ) / 7 Weeks From Emp Where Deptno = 10 .

‘YEAR’ ) From Dual . Last_day ( Sysdate ) – Sysdate Daysleft From Dual . date is truncated to the nearest day. 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 Conversions work according to the conversion specified by Oracle. ‘Format’ )  Returns Date rounded to the Unit specified by the format.  CHAR to NUMBER Conversions succeed only if the character strings represents a valid NUMBER. Sql > Select Round ( Sysdate. ‘MONTH’ ) From Dual . ‘YEAR’ ) . IN ASSIGNMENTS * Varchar2 / Char  Number * Varchar2 / Char  Date IN EXPRESSIONS * Varchar2/ Char  Number * Varchar2 / Char  Date 40 Oragle 10 g Material . Last_day ( Sysdate ) Last. ‘YEAR’ ) From Dual . ‘DAY’ ) From Dual . ‘DAY’ ) . Trunc ( Sysdate. ‘DAY’ ) From Dual .Naresh i Technologies Sql > Select Sysdate. Trunc ( Sysdate. ‘MONTH’ ) From Dual . ‘MONTH’ ). Sql > Select Round ( Sysdate. Date is rounded to the nearest day. Sql > Select Round ( Sysdate.  If format is omitted.  If format is omitted. Rounding of Dates : Syntax : Round ( Date. Trunc ( Sysdate.  CHAR to DATE Conversions succeed only if the character strings represent the default format DD-MON-YY. Sql > Select Round ( Sysdate. ‘Format’ )  Return Date with the time portion of the day truncated to the specified unit.  The assignment succeeds if the Oracle serves can convert the datatype of the value. Sql > Select Round ( Sysdate . Truncating Dates : Syntax : Trunc ( Date. Sql > Select Round ( Sysdate .

Naresh i Technologies * Number  Varchar2 * Date  Varchar2 Explicit Data type Conversion :  SQL provides three functions to convert a value from one data type to another.  The Functions are * To_Char * To_Date * To_Number For Conversion to Characters For Conversion to Dates For Conversion to Numbers

  

To_Char Conversion Function :  This function can be used in two different flavors • • To_Char ( Number Conversion ) To_Char ( Date Concersion )

 To_Char ( Number Conversion ) : Syntax : To_char ( Number , fmt, ‘nlsparms’ ) o o o Converts number of number data type to a value of Varchar2 data type. Fmt is the optional number format, that can be used. The ‘nlsparms’ specifies the characters returned by the number format elemtns.

 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. Formatting Models :  A formatting model is a character literal that describes the format of DATE or Number data stored in a character string.  D  99D99 : o o o It returns the specified position of the decimal character. The default decimal delimites is a period ( . ) Only one decimal character can be specified in a number format model.

Sql > Select To_char ( 1234, ‘99999D99’ ) From Dual ;

41

Oragle 10 g Material

Naresh i Technologies Sql > Select To_char ( 1234, ‘999D99’ ) From Dual ;  EEEE  9.9EEEE : o Returns a value using scientific notation.

Sql > Select To_char ( 1234 , ‘9.9EEEE’ ) , To_char ( 1234, ‘9.99EEEE’ ) From Dual ;  G  9G999 : o o Returns the specified position of the group separator Multiple group separators can be specified.

Sql > Select To_char ( 1234567, ‘99G99G999’ ) From Dual ; Sql > Select Sal, To_char ( Sal, ‘99G999D99’ ) From Emp ;  L  L999 : o Returns the specified position of the local currency symbol.

Sql > Select To_char ( 1234, ‘L9999’) From Dual ; Sql > Select Sal, To_char ( Sal, ‘L999999’ ) Currency From Emp Where Deptno = 10 ; Sql > Select Sal, To_char ( Sal, ‘L99G999D99’, ‘NLS_CURRENCY = IndRupees’ ) Salary From Emp Where Deptno = 20 ;  MI  9999MI : o o o Returns Negative value with a trailing minus sign ( - ). Return Positive value with a trailing blank. MI format should be declared as trailing argument only.

Sql > Select To_char ( -10000, ‘L99G999D99MI’ ) From Dual ; Sql > Select Sal, Comm, Comm_sal, To_char ( Comm – Sal , ‘L99999MI’ ) From Emp Where Deptno in(10, 20, 30 ) ;  PR  9999PR : o o Returns Negative value in < angle Brackets > It can appear only as trailing declaration.

Sql > Select To_char ( -1000 , ‘L99G999D99PR’ ) From Dual ; Sql > Select Sal, Comm, Comm – Sal , To_char ( Comm – Sal , ‘L99999PR’ ) From Emp  RN  Returns a value as Roman Number in Upper Case  rn  Returns a value as Roman Number in Lower Case • The Value can be an integer between 1 and 9999.

Sql > Select To_char ( 1000 , ‘RN’ ) , To_char ( 1000, ‘rn’ ) From Dual ;

42

Oragle 10 g Material

Naresh i Technologies Sql > Select Sal, To_char ( Sal, ‘Rn’ ) , To_char ( Sal, ‘rn’ ) From Emp ;  S  99999 : o o o Returns negative value with a leading minus sign Returns positive value with a leading plus sign 9999S : o o Returns negative value with trailing minus sign. Returns positive value with a trailing plus sign.

S can appear as first or last Value.

Sql > Select To_char ( 1000, ‘S9999’ ), To_char ( -1000, ‘S9999’ ) From Dual ; Sql > Select to_char ( 1000, ‘9999S’ ) , To_char ( -1000, ‘9999S’ ) From Dual ; Sql > Select Sal, To_char ( Sal, ‘S99999’ ) , To_char ( Sal, ‘99999S’ ) From Emp ; Sql > Select Sal, Comm, To_char ( Comm - Sal, ‘S99999’ ) , To_char ( Comm – Sal , ‘99999S’) From Emp ;  X  XXXX : xxxx : o o o Returns the hexadecimal value of the specified number of digits. If the number is not an integer, Orcle rounds it to an integer. Accepts only positive values or 0.

Sql > Select To_char(1000, ‘XXXX’) From Dual ; Sql > Select Sal, To_char ( Sal, ‘XXXXX’ ) From Emp ;  , ( Comma )  9,999 : o o Returns a comma in the specified position. Multiple commas can be specified.

Sql > Select To_char ( 10000, ’99,999D99’ ) From Dual ; Sql > Select Sal, To_char ( Sal, ’99,999D99’ ) From Emp ;  . ( Period )  99.99 : o o Returns a decimal point, at the specified position. Only one period can be specified in a number format model.

Sql > Select To_char ( 10000, ‘L99,999.99’ ) from Dual ; Sql > Select To_char ( Sal, ‘L99,999.99’ ) From Emp ;

43

Oragle 10 g Material

‘0999999’ ) .999. To_char ( Sal. ‘99999’ ) From Dual . ‘99999’ ) From Dual . Sql > Select To_char ( 10000. ‘$99. 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 . Sql > Select Sal.999.25 – 20.  0 ( Zero )  0999 : o Returns leading Zeros. and format items that represent similar information cannot be combined.  C  C9999 : o Returns specified position of the ISO Currency Symbol.  9990 : • Returns Trailing Zeros. Sql > Select To_char ( 1000. 44 Oragle 10 g Material . To_char ( 1000. Sql > Select Sal.Naresh i Technologies  $  $9999 : o Returns value with a leading Dollar Sign.  The total length of a date format model cannot exceed 22 characters.  9  9999 : o Return value with a specified number of digits with a leading space when positive or leading minus when negative. Sql > Select To_char ( 1000. Date Format Elements :  A date format model is composed of one or more date format elements. ‘$099. ‘C9999. ‘$99.99’ ) From Dual . ‘C9999.99’ ) From Emp . Sql > Select To_char ( 1000 – 600 . Sql > Select To_char ( 20. o For input format models. To_char ( Sal. ‘09999990’ ) From Dual .99’ ) From Dual .99’ ) From Emp . To_char( 600 – 1000 . format items cannot appear twice. Sql > Select Sal.999.99’ ) From Emp . To_char( Sal. ‘99999’ ) .

Sql > Select To_char ( Sysdate. o Pads to a length of 9 Characters.  AD or A. To_char ( Hiredate. slashes.’ ) From Dual .  DD  It Indicates The Day of the Month ( 1 – 31 ) Sql > Select To_char(Sysdate. ‘SCC-AD’ ) From Dual .’ ) .  D  Day of the Week ( 1 – 7 ) Sql > Select To_char ( Sysdate. or Roman numeral follows capitalization in the corresponding format element. ’DD-DAY’ ) From Emp Where To_char ( HireDate. Sql > Select To_char ( Sysdate.’DD-DAY’ ) From Emp . ‘A. ‘AD’) From Dual . ‘DAY’) From Emp Where To_char ( Hiredate.  AM or A.M.M. S prefixes BC date with – Sql > Select To_char ( Sysdate. Sql > Select Sal. Sql > Select To_char ( Sysdate. Sql > Select Sal. To_char ( Hiredate.’) . To_char ( Sysdate. ‘DAY’ ) From Dual .’ ) From Emp .’DD-DAY’) from Dual . 45 Oragle 10 g Material . Hiredate. To_char ( Hiredate. / PM or P.C. ‘D’ ) From Dual . periods and colons. To_char ( Hiredate.D.D.D. ‘SCC-AD’) From Emp . ‘PM’) From Dual . Sql > Select Hiredate.  Punctuation such as hyphens. ‘A. : o It indicates Meridian Indicator with or without periods. To_char ( Hiredate.  CC / SCC : o Indicates the century .  Day  Indicates spelled name of the Week Day. To_char ( Hiredate . / BC or B.M. ’DD-DAY’) = ’03-WEDNESDAY’ . ‘B. To_char ( Sysdate. commas. : o Indicates AD / BC with or Without periods. ‘D’ ) From Emp . Hiredate. Sql > Select Sal. Sql > Select Hiredate. abbreviation.C. ‘A. Hiredate. Sql > Select Hiredate. ‘DAY’) = ‘WEDNESDAY’ . To_char ( Hiredate. ‘AM’ ) From Emp . Hiredate.Naresh i Technologies  Capitalization in a spelled out word. Sql > Select Sal. Sql > Select To_char ( Sysdate.

 W  Specified the week of the Month ( 1 – 5 ). ‘I W’ ) From Dual . YYY / YY / Y Y . Sql > Select Ename. Sql > Select Sysdate . To_char ( Sysdate. Sql > Select Ename. Sql > Select Sysdate. To_char ( Sysdate. To_char ( Hiredate.  DDD It indicates the Day of the Year ( 1 – 366 ) Sql > Select Sysdate . IYY IY Sql > Select Sysdate.  YEAR / SYEAR  Returns the spelled out year. ‘DAY’ ) = ‘WEDNESDAY’ ) . 46 Oragle 10 g Material . Sql > Select Ename. 20 ) .YYY’ ) Comma From Dual .  IYYY  Specifies 4 Digit year based on the ISO Standard . Hiredate. Sql > Select Sysdate. Hiredate . ‘IYYY’ ) From Emp Where To_char ( Hiredate.  IW Specifies the week of the year ( 1 . To_char ( Hiredate. Hiredate.  DY It indicates the abbreviated name of the day. ‘YYYY’ ) Four. ’D-DY-DAY’ ) From Dual . ‘Y. Hiredate. *DAY Specifies in Initcap Casing. ‘IW’ ) From Dual . ‘YEAR’ ) From Dual . ‘YYY’ ) Three . To_char ( Hiredate. To_char(Sysdate. Hiredate.Naresh i Technologies *DAY Specifies in Upper Casing. ‘YYYY’ ) From Emp Where Deptno = 20 . Sql > Select Sysdate. To_char ( Sysdate. To_char ( Hiredate. To_char ( Sysdate. Sql > Select Ename. ’DDD’ ) From Dual . Week starts on the first day of the Month and ends on the seventh. ’DAY’ ) = ’WEDNESDAY’ . ’D-DY-DAY’ ) from Emp Where Deptno in( 10 . Hiredate. Sql > Select Ename. To_char ( Sysdate. *DAY Specifies in Lower Casing. YYY  Returns year with comma in this position. ‘IYYY’ ) From Dual . ’DDD’ ) From Emp Where To_char ( Hiredate. To_char (Sysdate. ‘S’ Prefixes BC dates with ‘ – ‘ . To_char ( Hiredate. To_char ( Hiredate. ‘YEAR’ ) From Emp . Sql > Select Ename. To_char ( Sysdate. Hiredate.  YYYY / SYYYY  Returns Four Digit year.52 or 1 – 53 )based on the ISO Standard.

ii. ‘W’) From Emp . Hiredate. To_char (Sysdate. Sql > Select Sysdate.  MONTH  Spells the Name of the Month. Sql > Select Ename. ‘WW’ ) From Emp .Naresh i Technologies Sql > Select Sysdate. Sql > Select Ename. To_char ( Hiredate. Sql > Select Sysdate. ‘HH12 : AM’ ) From Emp . ‘MM’ ) = 12 . ‘HH12. Hiredate. Week 1 Starts on the first day of the year and continues to the seventh day of the year. ‘MM-YYYY’ ) From Dual . Sql > Select Sysdate. 47 Oragle 10 g Material .  HH / HH12  Returns the Hour of the day in twelve hour clock mode. To_char ( Hiredate. It is the Number of days since January 1. To_char ( Sysdate. ( 0 – 23 ) Sql > Select Sysdate. ‘Q’ ) = 4 . To_char ( Sysdate.  Q  Returns the Quarter of the Year. YYYY’ ) From Emp . ‘Q’ ) From Dual . To_char ( Hiredate.  J  Returns the JULIAN DAY. padded to a length of 9 characters . Hiredate. ‘MONTH. Hiredate. Sql > Select Ename. ‘WW’ ) From Dual . Sql > Select Sysdate. Sql > Select Ename. ‘MM-MON’ ) From Dual . To_char ( Hiredate. ‘MON-MONTH’ ) From Dual . To_char (Sysdate. ‘Q’ ) From Emp Where To_char ( Hiredate. ‘J’ ) From Dual . Hiredate .  MON  Returns the Abbreviated Name of the Month. 4712 BC. Numbers specified with ‘J’ must be integers. To_char ( Sysdate. ‘J-DDD-DD-DD’ ) From Emp . To_char ( Sysdate. Sql > Select Ename. Sql > Select Sysdate.  MM  returns the digit numeric abbreviation of the Month. AM’ ) From Dual . Sql > Select Enbame. ‘W’ ) From Dual . ‘MM-YYYY’ ) From Emp Where To_char ( Hiredate . ‘HH24’ ) From Dual . Sql > Select Sysdate. i. ‘HH’ ). To_char ( Sysdate.  WW  Specifies the week of the Year ( 1 – 53 ) . To_char ( Sysdate. To_char ( Hiredate. To_char ( Sysdate.  HH24  Returns the Hour of the day in twenty four hour clock mode . Sql > Select Sysdate. Sql > Select Ename. To_char ( Sysdate. To_char ( Hiredate. Hiredate. to_char ( Hiredate.

: . Sal. To_char ( Hiredate. HH:MI:SS A. To_char ( Sysdate. Sql > Select Sysdate. ‘HH24:MI:SS’ ) From Emp Where Deptno In( 10. Sql > Select Ename. ‘HH:MI’ ) From Emp Where Job=‘CLERK’ . The return date is in the Current Century . ! . Hiredate. To_char ( Sysdaste. Sql > Select Sysdate. The RR date format element allows to store the date to the previous as well as the next Centuries .M. The RR format element provides additional flexibility for storing date values in other Centuries. ‘SSSS’ ) From Dual . ‘MI’ ). “RM” ) . If the Last 2 Digits of The Current Year are : 0 .. ‘DD-RM-YY’ ) From Emp .. HH:MI:SS.  SSSS  Display Seconds past Midnight ( 0 – 86399 ) .49 0 .Naresh i Technologies  MI  Returns the Minutes from the given date ( 0 – 53 ) . To_char ( Sysdate. To_char ( Sysdate. . Sql > Select Sysdate.  SS  Returns Seconds from the given date ( 0 – 59 ) Sql > Select Sysdate. ‘DD-RM-YY’ ) From Dual . The return date is in the next Century 50 . . Hiredate.49 50 . / . ‘DD-MM-YY. To_char ( Hiredate.99 Returns date is in the Current Century. ‘SS’ ). To_char ( Sysdate.  Date Format Element Suffixes : 48 Oragle 10 g Material . Sql > Select Ename.’ ) From Dual . To_char ( Hiredate. Sal. SSSS’ ) From Emp . To_char ( Hiredate. 30 ) .99 The return date is in the Preceding Century . Sql > Select Ename. Sql > Select Ename. ‘HH:MI’ ) From Dual. Sql > Select Sysdate. ‘HH:MI:SS’ ) From Dual . Sal. . To_char ( Sysdate.  RM  Returns the Roman Numeral Month ( I – XII ) . To_char ( Sysdate. ‘text’  RR Date Format Element : • • • • The RR date Format element is similar to the YY date format element. ‘DD-MONTH-YYYY. To_char ( Sysdate. • The Punctuation marks that can be used in Date formats are . .

YYYY’ ) From Emp . To_char ( Sysdate. MONTH. Sql > Select Sysdate. MONTH. Sql > Select Sysdate. MONTH. To_char ( Hiredate. Sal. o SP  Spells Numbers.  Format Model Modifiers : o o FM  “ Fill Mode “. To_char ( Sysdate. Hiredate. YYYY’ ) From Emp . ‘DDSPTH MONTH YYYYSP’ ) . ‘DDSP.  Date Format Elements Restrictions : o o The suffixes when added to date return value always in English. To_char ( Sysdate. It specifies exact matching for the character argument and date format model. MONTH. To_char ( Sysdate. YYYY’ ) From Emp . ‘DDSPTH MONTH YYYYSP’ ) From Dual . To_char ( Hiredate. YYYY’ ) From Dual .  TO_NUMBER Function : Syntax : To_Number ( Char. ‘DDTH.Naresh i Technologies o TH  Specifies the Ordinal Number Ex : DDTH  20TH Sql > Select Sysdate. Ex : ‘DDSP  TWENTY Sql > Select Sysdate. Sql > Select Ename. Ordinal Number Ex : DDSPTH  TWENTIETH Sql > Select Sysdate. ‘DDSPTH. ‘FMDDSPTH MONTH YYYYSP’ ) From Dual . ‘DDTH. FX  “ Format Exact “ . MONTH. Sal. ‘nlsparam’ ) 49 Oragle 10 g Material . Date suffixes are valid only on output. To_char ( Sysdate. Sql > Select Ename. ‘DDSP . hence cannot be used to insert a date into the database. MONTH. fmt. YYYY’ ) From Dual . To_char ( Sysdate. It suppresses blank padding in the return value of the To_char Function. YYYY’ ) From Dual . o Spelled. To_char ( Hiredate. Sal. Sql > Select Ename. ‘DDSPTH.

‘is a’). YYYY’ ) . 5 ). Sql > Select Ename.  Specificational Examples : Sql > Select To_char ( ADD_MONTHS ( Hiredate. Hiredate From Emp Where Deptno = 20 . To_Date ( ’01-01-1995’. ‘YYYY’ ) Year From Dual . The fmt is a date format specifying the format of char. o Assumption : Queries Issued between 1950 – 1999. ‘nlsparam’ ) o o Converts char of CHAR or VARCHAR2 datatype to a Value of DATE data type . 3 ) From Emp Where Hiredate = ’17-DEC-1980’ . Sql > Select Months_Between ( To_Date ( ’02-02-1995’ . NVL ( To_Char ( Comm) . ‘DD-MON-YYYY’ ) “NEXT MONTH” From Emp Where Ename = ‘SMITH’ . Sql > Select To_number ( ‘$1. Sql > Select To_number ( ‘$10. Job ) Designation From Emp Where Empno = 7900 . ADD_MONTHS ( To_char ( ’17-DEC-1980’. 50 Oragle 10 g Material .999. ‘TUESDAY’ ) “ Next Day “ From Dual . ‘DD-MON-RR’ ). Sql > Select To_char ( To_Date ( ’27-OCT-17’. ‘YYYY’ ) Year From Dual . ‘fm Month DD. 1 ). Sql > Select Concat ( Concat ( Ename. Sql > Select Next_Day ( ’15-MAR-98’. Sql > Select To_char ( ADD_MONTHS( LAST_DAY ( Hiredate ) .000. Hiredate. ‘DD-MON-YYYY’ ) “FIVE MONTHS” From Emp Where Ename = ‘MARTIN’ .Naresh i Technologies o It Converts a char.99’ ) From Dual . ‘ Not Applicable ‘ ) “ Commission ” From Emp Where Deptno = 30 . Sql > Select Ename. ‘L9. Sql > Select Trunc( To_Date ( ’27-OCT-92’ . Sql > Select Ename. ‘YEAR’ ) “ New Year “ From Dual . ‘MM-DD-YYYY’ ) ) MONTHS From Dual .00’. ‘DD-MON-RR’ ).000. ‘DD-MON-YY’ ) . fmt. To_char ( Hiredate. ‘DD-MON-YY’ ).00’. ‘MM-DD-YYYY’ ). Sql > Select Round ( To_Date ( ’27-OCT-92’ . Sql > Select To_char ( To_Date ( ’27-OCT-98’. 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 .  TO_DATE Function : Syntax : To_Date ( Char. ‘MONTH DD YYYY’ ) From Emp Where Ename = ‘BLAKE’ . ‘YEAR’ ) “NEW YEAR” From Dual . ‘L99.99’ ) + 500 From Dual . Sql > Select To_Char ( Hiredate .999.

‘fm DDTH’ ) || ‘ of ‘ || To_char ( Sysdate. AVG ( DISTINCT Sal ) From Emp . These functions can appear in SELECT lists and HAVING clauses. AVG ( DISTINCT AVG ) From Emp . ‘YYYY’ ) Year From Dual .Naresh i Technologies Sql > Select To_char ( To_Date ( ’27-OCT-98’. These functions operate on sets of rows to give one result per group. Sql > Select AVG ( Sal ) . Sql > Select To_char ( To_Date ( ’27-OCT-17’. other columns can be declared. ‘YYYY’ ) Idea From Dual .  Aggregate or Group Functions : o o o o These functions return a single row based on groups of rows.  Average Function : Syntax : AVG ( DISTINCT / ALL / n ) o o It returns the Average Value of n. no single row columns should be declared. ALL makes the function to consider every value including duplicates. ‘DD-MON-RR’ ). and all the non functional columns should be declared into a GROUP BY clause. To substitute a value for NULL values. ‘DD-MON-RR’ ) . ‘YYYY’ ) Year From Dual . NUMBER OR DATE.  Guidelines to use Group Functions : o o DISTINCT makes the function consider only non duplicate values. Sql > Select Ename. ‘Month’ ) ‘ . When a group function is declared in a SELECT list. All group functions except COUNT( * ) ignore NULL values. ‘ || To_char ( Sysdate. Sql > Select To_char ( Sysdate. Syntax : Group_Function_Name ( Distinct / ALL / n ) o o o o The data types for arguments may CHAR. It ignores NULL values. o Assumption : Queries Issued between 2000 – 2049 Sql > Select To_char ( Sysdate. VARCHAR. NVL ( To_char ( Mgr ). ‘ Supreme Authority ‘ ) “ Managers “ From Emp Order By Sal Desc . Sql > Select AVG ( Comm ) . ‘fmDay’ ) || ‘ “s Special ‘ ) “ MENU “ From Dual . but they should be grouped columns. When a group function is declared in a SELECT list . Job. The sets may be the whole table or the table split into groups.  SUM Function : Syntax : SUM ( DISTINCT / ALL / n ) 51 Oragle 10 g Material . use the NVL function.

Max ( DISTINCT Comm ) From Emp . Sql > Select Max ( Sal ). Sql > Select Max ( Comm ) . Stddev ( DISTINCT Comm ) From Emp . Sql > Select Min ( Comm ). Sum ( DISTINCT Sal ) From Emp . Sql > Select Min ( Sal ) . Sum ( DISTINCT Comm ) From Emp . Stddev ( DISTINCT Sal ) From Emp . It ignores NULL values. o Sql > Select Sum ( Sal ). It ignores NULL values.  MINimum Function : Syntax : MIN ( DISTINCT / ALL / n ) o o It returns the Minimum value of the n. Min ( DISTINCT Comm ) From Emp . 52 Oragle 10 g Material . Sql > Select Stddev ( Sal ) . o It ignores NULL values.  MAXimum Function : Syntax : MAX ( DISTINCT / ALL / n ) o o It ignores the Maximum value of n.Naresh i Technologies o It returns the Sum of the values of n. It ignores the NULL values. It ignores NULL Values.  Standard Deviation Function : Syntax : STDDEV ( DISTINCT / ALL / n ) o o It returns the Standard Deviation of the n. Sql > Select Sum ( Comm ) .  Variance Function : Syntax : VARIANCE ( DISTINCT / ALL / n ) o o It returns the Variance of N. Sql > Select Stddev ( Comm ). Max ( DISTINCT Sal ) From Emp . Min ( DISTINCT Sal ) From Emp .

Min ( Sal ) . Max ( Sal ) From Emp Group By Deptno . rows are sorted by ascending order of the columns included in the Group By List. rows can be pre excluded before dividing them into groups. Avg ( Sal ) From Emp Group By Deptno Order by Avg ( Sal ) . Syntax : Guidelines to Use Group By Clause : • • • • • • If the Group function is included in a SELECT clause.Naresh i Technologies Sql > Select Variance ( Sal ) . Job . Grp_Fun ( Column ) From Table Where Condition GROUP BY Grp_By_Expr Order By Column . It * is used returns all rows. The column applied upon GROUP BY Clause need not be part of SELECT list. Avg( Sal ) From Emp Group By Deptno . The Extra not group functional columns should be declared in the GROUP BY Clause. Variance ( DISTINCT Comm ) From Emp . N evaluates to something other than NULL.  Creating Groups of Data : o The Group By Clause is used to decide the rows in a table into groups. Sql > Select Deptno. It can be used to specify the count of all rows or only distinct values of n. Sum ( Sal ) From Emp Group By Deptno. Sql > Select Count ( Job ) . Sql > Select Count ( * ) From Emp .  COUNT Function : Syntax : COUNT ( * / DISTINCT / ALL / n ) o o o o It returns the number of rows in the query. Count ( Comm ) From Emp . Sql > Select Count ( Sal ) . Sql > Select Count ( Empno ) . Sql > Select Variance ( Comm ). we should not use individual results columns. By default. Variance ( Distinct Sal ) From Emp . Count ( DISTINCT Mgr ) From Emp . Sql > Select Deptno. Select Column. Sql > Select Deptno. Sql > Select Deptno. 53 Oragle 10 g Material . Count ( DISTINCT Job ) From Emp . Column Aliases cannot be used in Group By Clause. including duplicated and NULLs. USING WHERE Clause. Job.

without a Group Function in the SELECT list. Max ( Sal ). SELECT Column. Sql > Select Deptno. Sum ( Sal ). Avg ( Sal ) Sum ( Sal ) From Emp Group By Deptno Having Avg ( Sal ) > 2500 .  Nesting of Group Functions : 54 Oragle 10 g Material . Sql > Select Job. Sum ( Sal ) Payroll From Emp Where Job NOT LIKE ‘SALES%’ Group By Job Having Sum ( Sal ) > 5000 Order By Sum ( sal ) . But it is more logical to declare it before Group By. Avg ( Sal ) . Job. Avg ( Sal ) From Emp Where Job = ‘CLERK’ Group By Deptno . Max ( Sal ) From Emp Where Job = ‘CLERK’ Group By Deptno Having Min ( Sal ) < 1000 .  Excluding Groups of Results : o Having Clause :  It is used to specify which groups are to be displayed. Avg ( Sal )_From Emp Group By Deptno Having Max ( Sal ) > 2900 . Syntax : Steps Performs By Having Clause :    o o o Rows are Grouped The Group Function is applied to the group. Sql > Select Deptno. The Groups that match the criteria in the HAVING Clause are displayed. Avg ( Sal ) From Emp Group By Deptno. Sum ( Sal ). Sql > Select Deptno. Min ( Sal ). Group_Function From Table [ WHERE Condition ] [ GROUP BY Group_By_Expr ] [ HAVING Group_Condition ] [ ORDER BY Column_Name / Alias ] . we must have a Group By Clause as well as the Having Clause. Sum ( Sal ) . Sql > Select Deptno.Naresh i Technologies • The Above specification falls under the principle of Groups within Groups. Min ( Sal ) . Sql > Select Deptno. Job Having Avg ( Sal ) > 2500 . Sql > Select Deptno. Max ( Sal ) From Emp Where Job = ‘CLERK’ Group By Deptno . Group By Clause can be used. Sum ( Sal ) From Emp Group By Deptno Having Count ( Deptno ) > 3 . If rows are restricted based on the result of a group function. Min ( Sal ) From Emp Group By Deptno Having Count ( * ) > 3 . Sql > Select Deptno. The HAVING Clause can precede Group By Clause. Sql > Select Deptno.

Oracle compares the Exprs using Non padded comparison semantics. o UID Function : Syntax : UID 55 Oragle 10 g Material . ….  Miscellaneous Functions : o GREATEST Function : Syntax : GREATEST ( Expr1. Sql > Select Least ( ‘HARRY’ . ’20-JUL-05’ ) From Dual . Sql > Select Max ( Sum ( Sal ) ) . ‘HARRIOT’ ) From Dual . Sql > Select Max ( Avg ( Sal ) ) From Emp Group By Deptno . Sql > Select Max ( Sum ( Sal ) ) . before the comparison. 200 ) From Dual .. ‘HARRIOT’ ) From Dual . o USER Function : Syntax : USER  It returns the Current Oracle users within the VARCHAR2 data type. Sql > Select Greatest ( ’10-JUL-05’. Min ( Sum ( Sal ) ) From Emp Group By Deptno . Sql > Select Least ( ’10-JUL-05’. 200 ) From Dual . Expr2.)     Returns the greatest of the list of Expr. Character comparison is based on the value of the character in the data base character list. 2000. ……. Sql > Select Least ( 1000. Sql > Select Greatest ( ‘HARRY’ . Expr2. Sql > Select Greatest ( 1000. o LEAST Function : Syntax :   LEAST ( Expr1. ’20-JUL-05’ ) From Dual . All Exprs after the first are implicitly converted to the data type of the first Expr.  Sql > Select User From Dual .Naresh i Technologies o Group functions can be nested to a depth of two. All Exprs after the first are implicitly converted to the data type of the first expr before the comparison . Min ( Avg ( Sal ) ) From Emp Group By Job .  The function cannot be used in the condition of the CHECK Constraint . 2000.) It returns the Least of the List of Exprs.

Sql > Select Ename. ‘SESSIONID’  Returns the Auditing Session identifier. o VISIZE Function : Syntax : VSIZE ( Expr )  It returns the Number of bytes in the internal representation of Expr. It allows comparison of words that are spelled differently. Sql > Select Uid From Dual . Job From Emp Where Soundes ( Job ) = Soundex ( ‘CLERK’ ) . ‘ENTRYID’  Returns the available auditing entry identifier. 56 Oragle 10 g Material .Naresh i Technologies  It returns an integer that uniquely identifies the Current User. Uid From Dual . ‘LANGUAGE’  Returns the Language and territory used in Current Session . Sql > Select Ename. ‘CLIENT_INFO’  Returns upto 64 Bytes of User Session Information . Vsize ( Ename ) From Emp . o SOUNDEX Function : Syntax : SOUNDEX (CHAR ) • • It returns a character string containing the phonetic representation of char. Function returns NULL . Sql > Select User. but sound alike in enlish. o USERENV Function : Syntax :  o USERENV ( Option ) Returns information of VARCHAR2 data type above the current session .  If Expr is NULL. ‘INSTANCE’  Returns the instance identification number of the Current Instance. ‘TERMINAL’  Returns the OS identifier for the Current Session’s Terminal . The Values in Option are ‘ISDBA’  Returns ‘TRUE’ if DBA Role is Enabled. Sql > Select Ename From Emp Where Soundes ( Ename ) = Soundex ( ‘SMITH’) . ‘LANG’  Returns the ISD abbreviation for the language name. Sql > Select UserEnv ( ‘LANGUAGE’ ) From Dual .

It can enforced through. it prevents from ……. CONSTRAINTS : • • Constraints are used to define an Integrity Constraint. Restricting type ( Data Types ) By Format ( CHECK Constraint ) By Range of Possible Values ( FOREIGN KEY. CHECK. or the PRIMARY KEY of a table. * Changing values in a Primary Table that result in Orphaned records in a related table. It ensures that key values are consistent across tables. NOT NULL ) Referential Integrity : • • • It preserves the defined relationship between tables when records are entered or deleted. DEFAULT. * Deleting records from a Primary Table if there are matching related records. When referential integrity is enforced.Naresh i Technologies  DATA INTEGRITY IN DATA BASES : Data Integrity : • • It is a state in which all the date values stored in the data base are collect.. User_Defined Integrity : • It allows to define specific business rules that do not fall into any one of the other integrity categories.  CATEGORIES OF DATA INTIGRITY : Entity Integrity : • • It defines a row as a UNIQUE entity for a particular table Entity integrity enforces the integrity of the identifies columns. Enforcing Data Integrity ensures the quality of the data in the data base. As per Oracle these are Six Types of Constraints : 1) A NOT NULL Constraint 57 Oragle 10 g Material . * Adding records to a related table if there is no associated record in the Primary Table. as rule that restricts the values in a data base. Domain Integrity : • • Domain Integrity validates the entries for a given column.

and REF Constraints are supported on a column of type REF. NOT NULL Constraints : • • • A NOT NULL Constraint prohibits a column from containing NULLs . 1) 2) Column Level : They are declared as part of the definition of an individual column or attribute. NOT NULL. • The Constraint Clause can appear in ……. o o o o • CREATE Table ALTER Table CREATE View ALTER View Oracle does not support Constraints on Columns or attributes whose type is …. The style is called as OUT_OF_LINE specification. Table Level : They are declared as part of the table definition.. REF. 58 Oragle 10 g Material . LOB . NOT NULL should be defined using only INLINE specification or only at COLUMN Level The default if not specified is NULL . The style is called as INLINE specification. o o o o o USER_DEFINED OBJECT NESTED TABLES VARRAY REF LOB Exceptions : o o NOT NULL Constraint are supported for a column or attributes whose type is USER_DEFINED object VARRAY.Naresh i Technologies 2) 3) 4) 5) 6) • A UNIQUE Constraint A PRIMARY KEY Constraint A FOREIGN KEY Constraint A CHECK Constraint A REF Constraint In Oracle Constraints can be declared in two different styles. FOREIGN KEY. Note : NOT NULL Constraint should be declared as INLINE only.

59 Oragle 10 g Material .Naresh i Technologies • To satisfy a NOT NULL constraint. UNIQUE key cannot be implemented on columns having …… o o • • • • LOB * LONG * LONG RAW * VARRAY * NESTED TABLE OBJECT * BFILE * REF * TIMESTAMP WITH TIME ZONE . A composite UNIQUE key designates a combination of columns as the UNIQUE Key. Restrictions : • • A Table or View can have only one UNIQUE Key. JoinDate Date Constraint Jdate_NN NOT NULL ) . NULL or NOT NULL cannot be specified for an attribute of an object. Restrictions : • • NULL or NOT NULL Cannot be specified in a view constraint. Oracle creates an Index implicitly on the UNIQUE key column. UNIQUE key made up of a single column can contain NULLs. StudName Varchar2 ( 25 ) Constraint StudName_NN NOT NULL. The UNIQUE key can be specified only for the top level ( Root ) table or View. A composite UNIQUE key cannot have more than 32 columns Same column or combination of columns cannot be designated as both PRIMARY KEY and UNIQUE KEY. A composite UNIQUE key is always declared at the table level or out of line. Example : SQL > ( Create table Promotions1 Promo_ID Number ( 6 ) Constraint Promo_ID_UNQ UNIQUE . no two rows in the table can have the same value for the UNIQUE key. We cannot specify a UNIQUE key when creating a subtable or subview in an Inheritance hierarchy. To satisfy a UNIQUE constraint. UNIQUE Constraints : • • • • • • The UNIQUE Constraint designates a column as a UNIQUE Key. CourseName Varchar2( 25 ) Constraint CourseName_NN NOT NULL. every row in the table must contain a value for the column. Example : Sql > Create Table Students ( StudNo Number ( 6 ) Constraint Studno_NN NOT NULL.

Date . Varchar2( 100 ) . A COMPOSITE PRIMARY KEY designates a combination of columns as the PRIMARY KEY. Constraint Promo_ID_UNQ UNIQUE ( PromoID) Number ( 6 ) . 60 Oragle 10 g Material . Number ( 4 ) . Restrictions : • • A Table or View can have only one PRIMARY KEY . Number ( 4 ) . WaareHouseName ) ) . 2 ) . When the CONSTRAINT is declared at column level or inline only PRIMARY KEY Keyword is enough. Varchar2 ( 15 ) . Varchar2( 10 ) . Constraint WareHouse_UNQ UNIQUE ( WareHouseID. PRIMARY KEY Can not be implemented on Columns having……… o o • LOB * LONG * LONG RAW * VARRAY * NESTED TABLE OBJECT * BFILE * REF * TIMESTAMP WITH TIME ZONE . Date Number ( 6 ) Varchar2( 20 ) . Date . A Primary Key Constraint combines a NOT NULL and UNIQUE Constraint in one declaration. PRIMARY KEY Constraints : • • • • • A Primary Key constraint designates a column as the Primary Key of a table or View. 2 ) . Varchar2 ( 15 ) . Date . Number ( 10 . one Database Block . Varchar2( 10 ) . SQL > Create table Promotions2 ( Promo_ID PromoName PromoCategory PromoCost PromoBegDate PromoEndDate ) .Naresh i Technologies PromoName PromoCategory PromoCost PromoBegDate PromoEndDate ) . A Composite Primary Key is always defined at Table Level or Out of Line only. SQL > Create table WareHouse ( WareHouseID WareHouseName Area DockType WaterAccess RailAccess Parking Vclearance Varchar2( 20 ) . Number ( 10 . The size of a PRIMARY KEY cannot exceed approx. Varchar2( 30 ) . Varchar2( 10 ) .

StAddress Varchar2( 40 ) NOT NULL . FOREIGN KEY Constraint : • • • • • • • • • • It is also called as REFERENTIAL INTEGRITY CONSTRAINT. CustID ) 61 Oragle 10 g Material . A Composite Foreign Key Constraint. A Composite Foreign Key designates a combination of columns as the Foreign Key. The corresponding column or columns of the Foreign Key and the Referenced Key must match in order and data type. The PRIMARY KEY can be specified only for the top level( ROOT )Table or View Example : Sql > Create Table Locations ( LocationID Number ( 4 ) Constraint Loc_ID_PK PRIMARY KEY. City Varchar2 ( 30 ) Constraint City_NN NOT NULL ) . must refer to a Composite Unique Key or a Composite Primary Key in the Parent Table or View. City Varchar2 ( 30 ) Constraint City_NN NOT NULL . PostalCode Varchar2( 6 ) Constraint PC_NN NOT NULL . Constraint Loc_ID_PK PRIMARY KEY ( LocationID ) ) . Constraint Prod_Cust_IDPK ( ProdID .Naresh i Technologies • • • • A composite PRIMARY KEY cannot have more than 32 columns. PostalCode Varchar2( 6 ) Constraint PC_NN NOT NULL . Date NOT NULL . It designates a column as Foreign Key and establishes a relation between the Foreign Key and a specified Primary or Unique Key. PRIMARY KEY cannot be specified when creating a SubTable or SubView in an Inheritance Hierarchy. Number ( 6 ) . 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 Table or View containing the Foreign Key is called the Child Object. Sql > Create Table SalesInfo ( ProdID CustID SaleDate SaleDesc ) . Long NOT NULL . The same column or combination of columns cannot be designated both as PRIMARY KEY and UNIQUE KEY. Sql > Create Table Locations1 ( LocationID Number ( 4 ) . Number ( 6 ) . StAddress Varchar2( 40 ) NOT NULL . A Foreign Key Constraint can be defined on a single key column either inline or out of line. A Composite Foreign Key on attributes should be declared at table level or out of line style.

Location Varchar2( 20 ) Constraint Loc_NN NOT NULL ) . We can designate the same column or combination of columns as both a foreign key and a Primary or Unique Key. o o • • • • LOB * LONG * LONG RAW * VARRAY * NESTED TABLE OBJECT * BFILE * REF * TIMESTAMP WITH TIME ZONE . CASCADE option can be specified if we want ORACLE to remove Dependent FOREIGN KEY values. REFERENCES Clause : • • The References Clause Should be used when the Foreign Key Constraint is INLINE. To enable Referential Integrity across nodes of a distributed database Database Triggers are used. Specify SET NULL if we want Oracle to convert dependent FOREIGH KEY values to NULL. we must specify the Foreign Key . Step 2 : Create Detailed / Child Table 62 Oragle 10 g Material .Naresh i Technologies • • The same column or combination of columns can be designated as both a Foreign Key and a Primary or Unique Key. The Child and Parent Tables must be on the same database. ON DELETE Clause : • • • • The ON DELETE Clause determines how oracle automatically maintains REFERENTIAL INTEGRITY if the REFERENCED PRIMARY or UNIQUE KEY value is removed. A Composite Foreign Key cannot have more than 32 columns. ON DELETE Clause cannot be specified for a view constraint. Dname Varchar2( 20 ) Constraint Dname_NN NOT NULL. Steps to be Followed for Creating Foreign Key Constraint are as Follows : Step 1 : Create Primary Master’s / Pure Master’s • These are Tables which contains only Primary Key Columns. Restrictions : • The Foreign Key Columns cannot be applied on …. Sql > Create Table Dept ( Deptno Number( 2 ) Constraint Deptno_Pk PRIMARY KEY. The Referenced Unique / Primary Key Constraint on the Parent Table on View must already be deleted. Key words. When the Constraint is OUT OF LINE.

Sql > Create Table SampMaster2 ( SampleID2 Numer ( 4 ) Constraint Samp_ID2_PK PRIMARY KEY . Commission Number ( 7. ManagerID Number ( 6 ) Constraint Mgr_ID_FK_Self REFERENCES Employee ( EmployeeID ) ON DELETE SET NULL . Working With Composite PRIMARY KEY : Step 1 : Create Pure Maters Sql > Create Table SampleMaster1 ( SampleID1 Numer ( 4 ) Constraint Samp_ID_PK PRIMARY KEY . SampDate Date Constraint SampDate_NN NOT NULL ) . SampName2 Varchar2 ( 20 ) Constraint SampName2_NN NOT NULL . DeptID Number ( 2 ) Constraint DeptID_FK REFERENCES Dept( Deptno ) ON DELETE CASCADE ) . Sql > Create Table Employee ( EmployeeID Number ( 6 ) Constraint Emp_ID_PK PRIMARY KEY . HireDate Date Constraint HireDate_NN NOT NULL . SampName Varchar2 ( 20 ) Constraint SampName_NN NOT NULL . Ename Varchar2 ( 30 ) Constraint Ename_NN NOT NULL .Naresh i Technologies • • These are Tables which can contain Primary Key of their own as well as Foreign Key’s referring to other Primary Master’s or to them selves. Designation Varchar2 ( 30 ) Constraint Desig_NN NOT NULL . Step 2 : Create The Pure Details Sql > Create Table SampRef ( 63 Oragle 10 g Material . SampDate2 Date Constraint SampDate2_NN NOT NULL ) . These tables are also called as dependent tables or Referential tables. 2 ).

Constraint SampRef_Comp_PK PRIMARY KEY ( SampIDRef1. The pseudo Columns CURRVAL. but it cannot refer to columns of other tables. each row in the table must make the condition either TRUE or UNKNOWN. CHECK Constraint : • • • It defines a condition that each row must satisfy. SampNameRef Varchar2 ( 20 ) . SampIDRef2 Number ( 4 ) Constraint SampIDRef2_FK REFERENCES SampMaster2( SampID2 ) . Restrictions : • • The Condition of a CHECK Constraint can refer to any column in the table. ORACLE does not verify that CHECK conditions are not mutually exclusive.Naresh i Technologies SampIDRef1 Number ( 4 ) Constraint SampIDRef_FK REFERENCES SampMaster1( SampID1 ) . There is no limit to the number of CHECK constraints that can be defined on a column. The CHECK constrains can be defined at the column level or Table level. Loc Varchar2 ( 15 ) Constraint CHK_Loc CHECK( Loc IN( ‘DALLAS’. UID. o o o o • • • Queries to refer to values in other rows Calls to functions SYSDTE. ‘BOSTON’. Example : Sql > Create Table Dept ( Deptno Number ( 2 ) Constraint CHK_Deptno CHECK ( Deptno BETWEEN 10 AND 99 ) . SampIDRef2 ) ) . Date constant that are not fully specified. ‘NEW YORK’ . NESTVAL. USERENV. USER. Dname Varchar2( 15 ) Constraint CHK_Dname_up CHECK ( Dname = UPPER ( Dname ) ) DISABLE . A single column can have multiple CHECK constraint that reference the column in the definition. SampDateRef Date . ‘CHICAGO’ ) ) ) . To satisfy the constraint.. LEVEL or ROWNUM. The constructs that cannot be included are …. 64 Oragle 10 g Material .

The DEFAULT Expression must match the data type of the Column. Number ( 4 ) . Number ( 7. 2 ) . ENABLE. 65 Oragle 10 g Material . DROP . using ADD Clause. Constraint Tot_Sal_Chk CHECK ( Sal + Comm < = 100000 ) DEFAULT Option : • • • • The DEFAULT Option is given to maintain a default value in a column. The option prevents NULL Values from entering the Columns. but recommended. Guidelines : • We can ADD. 2 ) Constraint Sal_NN NOT NULL . The DEFAULT value can be a literal. Constraint CHK_Sal CHECK ( Sal BETWEEN 2000 AND 100000 ) ) .Naresh i Technologies Sql > Create Table Emp ( Empno Ename Job Mgr HireDate Sal Number ( 4 ) Constraint PR_Empno PRIMARY KEY . if a row is inserted without a value for a column. but modify the structure. Adding Constraints to a Table : • A constraint can be added to a table at any time after the table was created by using ALTER TABLE Statement. Syntax : Sql > ALTER TABLE < Table_Name > ADD [ Constraint < Constraint_Name > ] Cons_Type ( Column_Name ) . Varchar2( 25 ) NOT NULL Constraint CHK_Ename CHECK ( Ename = UPPER ( Ename ) ) . Number ( 2 ) . Date DEFAULT SYSDATE. Constraint CHK_Job CHECK ( Job = UPPER ( Job ) ) . • The Constraint Name syntax is optional. Comm Deptno ) . or DISABLE a Constraint . Number ( 7. Varchar2( 30 ) Constraint Job_NN NOT NULL . an expression or a SQL Function.

NOT NULL can be defined only when the table contains no rows. The CASCADE Option of the DROP Clause causes any dependent constraints also to be dropped. ALTER Table < Table_Name > DISABLE CONSTRAINT < Constraint_Name > [ CASCADE ] . the constraint is no longer enforced and is no longer available in the data dictionary. The ALTER TABLE Statement is used with the DISABLE Clause. DISABLING Constraints : • • The constraints can be disabled without dropping it or recreating it.Naresh i Technologies • • A NOT NULL can be added to existing column by using the MODIFY Clause of the ALTER TABLE Statement. The CASCADE clause disables dependent integrity constraints. Sql > ALTER Table Emp DROP CONSTRAINT Emp_Mgr_FK . When a constraint is dropped. ENABLING Constraints : • • The Constraints can be enabled without dropping it or re-creating it. Syntax : Guidelines : • • The DISABLE Clause can be used both in CREATE TABLE and the ALTER TABLE statement. The ALTER TABLE statement with the ENABLE Clause. 66 Oragle 10 g Material . Examples : Sql > ALTER Table Emp DISABLE CONSTRAINT Emp_Empno_PK CASCADE . Example : Sql > ALTER Table Emp ADD Constraint Emp_Mgr_FK FOREIGN KEY ( Mgr ) REFERENCES Emp ( Empno ) . Syntax : ALTER Table < Table_Name > DROP PRIMARY KEY / UNIQUE ( Column ) / CONSTRAINT Constraint_Name [ CASCADE ] . Example : Sql > ALTER Table Dept DROP PRIMARY KEY CASCADE . DROPPING Constraints : • • • • To Drop a constraint identify the constraint name from the USER_CONSTRAINTS and USER_CONS_COLUMNS Data dictionary views. The ALTER TABLE Statement is used with the DROP Clause.

When an UNIQUE or PRIMARY KEY Constraint is ENABLED. Examples : Sql > ALTER Table Emp ENABLE CONSTRAINT Emp_Empno_FK . views. COLUMN_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME = ‘EMP’ . The ENABLE Clause can be used both in CREATE TABLE as well as ALTER TABLE Statements. the UNIQUE or PRIMARY KEY Index is automatically created. VIEWING The Columns Associated With Constraints : • The Names of the columns that are involved in constraints can be known by querying the USER_CONS_COLUMNS Data Dictionary View. The Queries SELECT list can select any columns from any of these tables. ALTER Table < Table_Name > ENABLE CONSTRAINT < Constraint_Name > . SEARCH_CONDITION FROM USER_CONSTRAINTS WHERE TABLE_NAME = ‘EMP’ . A Join is performed whenever multiple tables appear in the queries FROM Clause. VIEWING Constraints : • • To View all Constraints on a table by Querying the USER_CONSTRAINTS table. The Codes that are revealed are …… o o o o C D R U     CHECK PRIMARY KEY REFERENTIAL INTEGRITY UNIQUE KEY Example : Sql > SELECT CONSTRAINT_NAME. or Materialized views. 67 Oragle 10 g Material . JOINS :     A Join is query that combines rows from two or more tables. CONSTRAINT_TYPE.Naresh i Technologies Syntax : Guidelines : • • • Enabling a Constraint applied to all the data in the table. The common column names within the tables should qualify all references to these columns. Example : Sql > SELECT CONSTRAINT_NAME.

we need a minimum of n -1 Join Conditions . each from a different table.Column2 .  The LOB Columns cannot be specified in the WHERE Clause. which compares two columns.  To execute a Join ……… Oracle combines pairs of rows.  If the same column name appears in more than one table. JOIN 1 TABLE 1 TABLE 2 JOIN 2 RESULT TABLE 3 RESULT  The Oracle Optimizer determines the older in which Oracle Joins tables based on the o o o JOIN Condition INDEXES on Tables STATISTICS for the Tables.  To Join n tables together.Column1 = Table2.  To Execute a Join of three or more tables o o Oracle first Joins two of the tables based on the Join Conditions comparing these columns and then Join’s the result to another. Guidelines :  When writing a SELECT statement that Join’s tables.  The Columns in the Join Conditions need not be part of the SELECT list.  The above rule does not apply . the column name must be prefixed with the table name.  The WHERE Clause of Join Query can also contain other conditions that refer to columns of only one table.  The applied condition is called a Join Condition. each containing one row from each table. EQUIJOINS / SIMPLE JOINS / INSER JOINS : 68 Oragle 10 g Material . if the table contains a concatenated Primary Key. for which the Join condition evaluated to TRUE. Syntax : Table1. When the WHERE Clause contains any JOINS. precede the Column Name with the Table Name for clarity and enhance database Access.Naresh i Technologies JOIN CONDTIONS :  Many Join Queries contain WHERE Clause.

Deptno .Deptno . Dept. E.Loc From Emp E. Example : Sql > Select Emp. E.Deptno = D. D. the qualification is not necessary. D.Deptno. USING TABLE ALIASES :      Tables Aliases can be used instead of table names. Emp. D. Ename. then that Table Alias must be substituted fro the Table Name through out the SELECT statement.Deptno = Dept. Example : Sql > Select Empno. Dept. Dept Where Emp.Job.Deptno. Qualifying Ambiguous Column Names :  The names of the column names should be qualified in the WHERE Clause. To specify a Table Alias.Deptno = D.Ename. ‘MANAGER’ ) .Deptno AND D. Sql > Select E. D. with the table name to avoid ambiguity.Ename. Examples : Sql > Select E. D.Deptno = Dept. D. SELF JIONS : 69 Oragle 10 g Material .  A Table Alias should be meaningful . Emp. Emp. The Table alias is specified in the FROM Clause.Deptno = D.Dname From Emp E.Deptno AND Job = UPPER ( ‘manager’ ) . Guidelines :  A table alias can be upto 30 character in length.Empno.Naresh i Technologies  An EQUIJOIN is a Join with a Join Condition containing an equality operator. Loc From Emp. Dept D Where E.Dname < > ‘BOSTON’ .Dname . Dept. Dept D Where E.  A Table Alias is valid only for the Current SELECT statement . D. Table Aliases help in keeping the SQL Code smaller. specify the Table Name in full followed by space and then the Table Alias. E.Deptno AND E.Deptno . hence using less Memory.Dname.Job.  The size of the data block is specified by the initialization parameter DB_BLOCK_SIZE .Ename.Deptno .  The total size of columns in the equi join condition in a single table may be limited to the size of a data block minus some overhead.Dname .Loc From Emp.Ename. Dept D Where E.Loc From Emp E . Dept Where Emp. Sql > Select E.  It combines rows that have equivalent values for the specified columns.  If a Table Alias is used for a particular Table Name in the From Clause. A table Alias gives an alternate name for the existing queried table.Deptno.Empno.  If there are no common column names between the two tables.Job IN(‘ANALYST’.

From Emp E1.HiSal ) AND S. SalGrade S Where ( E. Dname From Emp. E. Example : Sql > Select Ename.Sal < = S. E1.Sal > = S.Empno .Sal .Mgr = E2. E2. Job.Grade From Emp E.Ename || ‘Works Fir ‘ || E2. To perform a Self Join. Example : Sql > Select E.  The Data in the tables in directly not related but indirectly or logically related through proper values. Emp E2 Where E1.Ename “ Employees And Managers “ From Emp E1. that that no Join Condition.Losal AND S. Dept Where Job = ‘MANAGER’ .  It tends to generate a large number of rows and the result is rarely useful. Sql > Select E.Mgr = E2.Grade = 1 . Oracle combines and returns rows of the table that satisfy the Join Condition . Ename “ Managers Name “ . Dname From Emp. Sql > Select Sql > Select CARTESIAN PRODUCTS :  The CARTESIAN PRODUCT is a Join Query. The Table Aliases must qualify the Column names in the Join Condition.  During Cartesian Product Oracle Combines each row of one table with each row of the other. Dept .Job = ‘CLERK’ .Deptno ) AND E1.Ename . Example : Sql > Select E1. Emp E2 Where E1.Mgr = E2. SalGrade S Where E.Empno . S.Ename || ‘ “s Managers is ‘ || E2.Grade From Emp E. Sql > Select Ename. NON EQUI JOIN :  It is a Join Condition that is executed when no column is one table corresponds directly to a column in the other table. Job. S. E1.Sal.Hisal . The same table appears twice in the FROM Clause and is followed by table aliases. E.Ename “ Employee Name “ .Naresh i Technologies     It is a Join of a table to itself. Emp E2 Where ( E1.LoSal AND E.Ename “ Employees And Managers “ From Emp E1 .Ename.Sal BETWEEN S. OUTER JOINS :  An Outer Join extends the result of a simple Join. 70 Oragle 10 g Material .

D. D. D. Table 2 Where Table1.Ename. D. Syntax : Sql > Select Table1.  A condition cannot compare any column marked with the ( + ) operator with a sub query.Deptno AND E.Deptno Order By E. Sql > Select E. apply the outer join operator ( + ) to all columns of B.Deptno ( + ) = D. Oracle returns NULL for any select list expressions containing columns of B.  The Join is first executed upon the two most relevant tables and then the result is applied upon the third table.  To perform an OUT Join of tables A and B and returns all rows from A. 71 Oragle 10 g Material . Examples : Sql > Select E.Column From Table1.  For all rows in A that have no matching rows in B. and can be applied only to a column of a Table or View.Naresh i Technologies  An OUTER Join returns all rows that satisfy the Join Condition and also those rows from one table for which no rows from the other satisfy the Join Condition.Column .Deptno.Deptno .Deptno = D.  A condition containing the ( + ) operator cannot be combined with another condition using the OR Logical Operator.Column ( + ) . JOINING Data From More Than One Table :  JOINS can be established on more than two tables. Dept D Where E.Deptno .Dname From Emp E.Column From Table1. not to an arbitrary expressions.Deptno ( + ) = 10 Order By E.  The ( + ) operator can appear in the context of the left correlation in the From Clause.Column. D.Dname From Emp E. Dept D Where E. D. Dept D Where E.Deptno ( + ) And E. Sql > Select E.Column.Column ( + ) = Table2.  A condition cannot use the IN Comparison operator to compare a column marked with the ( + ) operator with an expression.  If A and B are joined by multiple join conditions.Deptno .Deptno ( + ) = D.Deptno. Table2.Column = Table2. Sql > Select Table1.Ename . we must use the ( + ) operator in all of these conditions.Dname From Emp E.  The ( + ) operator can be applied only to a column.Deptno ( + ) = 10 Order By E.Ename. Table2.Deptno . Rules And Restrictions :  The ( + ) operator can appear only in the WHERE Clause. Table 2 Where Table1.

< .  A Sub Query can be part of a Column.OldID. O. UPDATE.  To define one or more values to be assigned to existing rows in an UPDATE statement. O. START WITH Clause of SELECT .OldID AND C.  Within the WHERE Clause upto 255 Sub Queries can be Nested. < = ) Multiple row Operators ( IN .CustID = O.  To define the set of rows to be included in a view a materialized view in a CREATE VIEW or CREATE MATERIALIZED VIEW statement. placing one query inside the other query.CustID AND O. I. A Sub Query in the WHERE Clause of a SELECT statement is called as NESTED SUBQUERY..  The Expr . HAVING Clause. A Sub Query can contain another Sub Query.  To make the statements easier for readability. and DELETE statements. Sub Query Principle :  Solve a problem by combining the two queries.Total From Customer C. 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.OldID = I. SUB QUERIES / NESTED SELECT / SUB SELECT / INNER SELCT : A Sub Query answers multiple-part questions.Itemtot.  The provide values for conditions in a WHERE clause. = . A Sub Query in the From Clause of a SELECT statement is called as INILINE VIEW. Oracle imposes no limit on the number of Sub Query levels in the From Clause of the top-level query. Item I Where C. I.  To define a table to operated on by a containing query.  The inner query or the sub query returns a value that is used by the outer query on the main query.Naresh i Technologies Example : Sql > Selecgt C. qualify the columns in a Sub Query with the Table Name or Table Alias.Name = ‘TKB SPORT SHOP’ .ItemID. in the SELECT list. > = .      Purpose of A Sub Query :  To define the set of rows to be inserted into the target table of an INSERT or CREATE TABLE statement. Ord O. Syntax : Select Select_List From Table_Name Where Table_Name ( Select Select_List From Table_Name ) .Name. ALL ) 72 Oragle 10 g Material . Operator can be of o o Single row Operators ( > . ANY .

Job From Emp Where Sal > ( Select Sal From Emp Where Empno = 7566 ) .  Multiple Row Sub Query : o These Queries return more than one Row from the inner SELECT Statement. A Sub Query must appear on the right side of the comparison operator. the query passes through the success state.  It uses only single row operator.  Multiple Column Sub Query : o These Queries return more than one Column from the inner SELECT Statement. Job From Emp Where Deptno = ( Select Deptno From Dept Where Dname = ‘SALES’ ) . Only one ORDER BY Clause can be implemented for the total SELECT Statement. Ename. Sal. Sub Queries should not contain an ORDER BY Clause. Ename.  As a Group Function returns a single row. Job From Emp Where Job = ( Select Job From Emp Where Ename = Upper ( ‘smith’) ) Order By Sal . * Single Row Single Row Sub Queries :  They return only one row from the INNER SELECT Statement. Sal From Emp Where Hiredate > ( Select Hiredate From Emp Where Ename = UPPER ( ‘turnes’ ) ) Order By Sal . Sal + NVL( Comm. Two clauses of comparison operations can be used in sub queries. Comm. Sql > Select Ename. Sql > Select Empno. Sql > Select Empno. Guidelines To Follow ….Naresh i Technologies TYPES OF SUB QUERIES :  Single Row Sub Query : o These Queries return only one Row from the inner SELECT Statement. Examples : Sql > Select Ename. Sal. Sql > Select Empno. * Multiple Row 73 Oragle 10 g Material . Ename. Hiredate. Sal.      A Sub Query must be enclosed in parenthesis.. Sal. 0 ) From Emp Where Deptno = ( Select Deptno From Dept Where Loc = ‘DALLAS’ ) . APPLYING GROUP FUNCTIONS IN SUB QUERIES :  The data from the main query can be displayed by using a Group Function is a Sub Query.

Example : Sql > Select Deptno. Job . The multiple row operators expect one or more values.Naresh i Technologies  The inner sub query should not have a GROUP BY Clause in this scenario. Job. and the results are returned into the HAVING Clause of the Main Query. To_Char ( Avg ( Sal ) .  The Oracle Server executes the sub query. Examples : Sql > Select Ename. Sal From Emp Where Sal = ( Select Min ( Sal ) From Emp ) . Sal From Emp Where Sal < ( Select STDDEV( Sal ) From Emp ) . ANY. ‘L99. Job. In This case a multiple row operator should be used. Applying HAVING Clause With Sub Queries :  A Sub Query can be also applied in HAVING Clause. ALL. Avg ( Sal ) From Emp Group By Job Having Avg ( Sal ) < ( Select Max ( Avg ( Sal ) ) From Emp Group By Job ) . Avg ( Sal ) From Emp Group By Job Having Avg( Sal ) = ( Select Min ( Avg ( Sal ) ) From Emp Group By Job ) . o IN  EQUAL TO ANY MEMBER INDIA THE LIST . Sub Queries Returning More Than One Row :     The Sub Queries that return more than one row are called as MULTIPLE ROW SUB QUERIES. Sal From Emp Where Sal = ( Select Max( Sal ) From Emp ) . Job. Sql > Select Job. Sql > Select Job. Sql > Select Ename. Min ( Sal ) From Emp Group By Deptno Having Min( Sal ) > ( Select Min ( Sal ) From Emp Where Deptno = 20 ) . Sal From Emp Where Sal > ( Select Avg ( Sal ) From Emp ) . Avg ( Sal ) . The multiple row operator are IN . Sql > Select Ename. Sql > Select Ename. 74 Oragle 10 g Material .999. Sql > Select Job.99’ ) From Emp Group By Job Having Avg ( Sal ) < ( Select Max ( Sal ) ) From Emp Group By Deptno ) .

S Y N O N Y S ALL  Examples : Sql > Select Ename. Sal . Deptno . Ename. Note : = ANY  It is Equivalent to IN Operator . Deptno From Emp Where Sal In( Select Min ( Sal ) From Emp Group By Deptno ) . Sql > Select Empno. Sql > Select Empno. Job. Ename. Sal. Job From Emp Where Sal < Any( Select Sal From Emp Where Job = ‘CLERK’ ) . Sal. Example’s ALL Operator : Sql > Select Empno. Examples Any Operator : Sql > Select Empno. Job From Emp Where Sal = Any ( Select Sal From Emp Where Job = ‘CLERK’ ) .e Job. 75 Oragle 10 g Material . Job From Emp Where Sal > Any ( Select Sal From Emp Job = ‘CLERK’ ) . Sal From Emp Where Sal < All ( Select Avg( Sal ) From Emp Group By Deptno ) . Sakl From Emp Where Sal > ALL ( Select Avg ( Sal ) From Emp Group By Deptno ) . Sql > Select Ename. Job From Emp Where Sal In( Select Max ( Sal ) From Emp Group By Job ) . Note : > ALL  It means more than the Maximum . Sql > Select Empno.Naresh i Technologies o o ANY  COMPARES VALUE TO EACH VALUE RETURNED BY SUB QUERY . Ena. Note : > ANY  It means more than the Minimum. Sal From Emp Where Sal < Any ( Select Sal From Emp Where Deptno = 20 AND Job < > ‘CLERK’ . Deptno From Emp Where Sal In ( Select Max ( Sal ) From Emp Group By Deptno ) . Note : < ALL  It means less than the Minimum . Ename. Sql > Select Empno. COMPARES VALUE TO EVERY VALUE RETURNED BY THE SUB QUERY . Note : < It means less than the Maximum Value . Job. Sql > Select Ename. Ename. Ename.

……… From Table_Name Where ( Column a. Product_ID . Quantity ) IN ( Select Product_Id. Quantity From Item Where Order_ID = 605 AND Order_ID < > 605 . Syntax : Select Column1. Example : Sql > Select Order_ID. Quantity From Item Where Product_ID IN(Select Product_ID From Item Where Order_ID = 605 ) AND Quantity IN(Select Quantity From Item Where Order_ID = 605 AND Order_ID < > 605 . then the entire query returns No Rows.  Multiple Column sub queries enable us to combine the duplicate WHERE condition into a single WHERE Clause. Column2. Handling NULL Values in Sub Queries :  If one of the values returned by the inner query is NULL value. ……. 76 Oragle 10 g Material . ) From Table_Name Where Condition ) . by writing a Compound WHERE Clause using logical operators.) IN ( Select Column a. Product_ID.  In Non Pair Wise comparison. Column b ….Naresh i Technologies Sub Queries Returning Multiple Columns :  In Sun Queries multiple Columns can be compared in the WHERE Clause. we can use a WHERE Clause with multiple conditions.  The Non Pair Wise comparison also called cross product. the candidate row must match the multiple conditions in the WHERE Clause but the values are compared individually.  The Column comparisons in a multiple Column sub query can be o o 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. Quantity From Item Where ( Product_ID. Example : Sql > Select Order_ID. Column b .

Sql > Select A. Sql > Select Deptno. ( Select Min ( Sal ) From Emp ) “ Organization Minimum “ From Emp .Deptno AND E. Avg ( Sal ) SalAvg From Emp Group By Deptno ) E1 Where E. Sql > Select T1. Tot_Sal . ( Select Sum ( Sal ) Tot_Sal From Emp ) Group By Deptno. it is better not to use NOT IN Operator As it is equivalent to ! = NULL . Count( * ) Num_Emp. Staff From Dept T1. Sql > Select Ename.Emp_Count.Num_Emp / B. Examples in Queries : Sql > Select E.Sal . Hiredate From Emp Order By Hiredate Desc ) .Sal_Sum / B.Dept_Count From ( Select Count ( * ) Emp_Count From Emp ) E.Deptno AND Staff > = 5 .Deptno “ Department Number” . Sum( Sal ) Total_Sal From Emp ) B . Sum ( Sal ) / Tot_Sal * 100 “Salary Percentage “ From Emp. E.Total_Count ) * 100 “ %Employees” . Sql > Select * From ( Select Empno. Example : Sql > Select E.Ename From Emp E Where E. Applying Sub Query in From Clause :  A Sub Query in the From Clause is equivalent to a view.Mgr From Emp M ) . Sal. Sal. Ename. Sql > Select E. Sql > Select Ename.  The Sub Query in the From Clause defines a data source for that particular SELECT statement and only that SELECT statement.Naresh i Technologies  All Conditions that compare a NULL Value result is a NULL . ( A.Ename. ( A. E. E1.Deptno.Sal > E1. Dname.Deptno = T2. Count( * ) As Staff From Emp Group By Deptno ) T2 Where T1.Deptno = E1.SalAvg . Sum ( Sal ) . ( Select Deptno. D. ( Select Deptno.  Whenever a NULL could be part of a Sub Query. ( Select Max( Sal ) From Emp ) “ Organization Maximum “ . ( Select Avg( Sal ) From Emp ) “ Organization Average” From Emp .Deptno. 77 Oragle 10 g Material .Empno IN( Select M.SalAvg From Emp E.Total_Sal ) * 100 “ %Salary “ From ( Select Deptno. ( Select Count ( * ) Total_Count. Sum ( Sal ) Sal_Sum From Emp Group By Deptno ) A . ( Select Count( * ) Dept_Count From Dept ) D .

Sql > Select Deptno.Deptno ) . Syntax : Select Select_List From Table1 F_Alias1 Where Expr.Column ) .Mgr ) . Dname From Dept D Where EXISTS ( Select * From Emp E Where D. EXISTS Operator in Correlated Sub Queries :  The EXISTS Operator tests for existence of rows in a subquery.Empno = E.Ename From Emp E Where NOT EXISTS ( Select * From Emp E1 Where E1.Deptno = Deptno ) Order By Deptno . Sql > Select E. Dname From Dept D Where NOT EXISTS ( Select * From Emp E Where D.  In this the information from the outer SELECT statement participates as a condition in the INNER SELECT statement.  Passes the qualified column value to the inner gueries WHERE Clause.Naresh i Technologies CORRELATED SUB QUERIES :  It is another way of performing Queries upon the data with a simulation of Joins.Ename From Emp E 78 Oragle 10 g Material .Deptno = E.  Depending on the supplied value the condition is qualified for the specific record. Sal From Emp X Where Sal > ( Select Avg( Sal ) From Emp Where x. Sql > Select E.. Sql > Select E.Empno = E.Deptno ) . Steps Performed :  First the Outer Query is executed.  It returns TRUE if a subquery returns at least one row. Example : Sql > Select Deptno. Sql > Select E.  Then the inner query or candidate query is executed. and the result is passed to the outer queries WHERE Clause.Ename From Emp E Where EXISTS ( Select * From Emp E1 Where E1.Empno ) .Ename From Emp E Where EXISTS ( Select * From Emp E1 Where E1. Example : Sql > Select Deptno.Mgr = E.Deptno = E. Ename. Operator ( Select Column_List From Table2 F_Alias2 Where F_Alias1.Column Operator F_Alias2.Mgr ) .

ORACLE removed all rows from the hierarchy that do not satisfy the condition of the WHERE Clause .  To execute the hierarchical queries.Mgr = E.  ORACLE selects the child rows of each root row. then the rows are returned as per the specification in the ORDER BY Clause. we need the following queries. CONNECT BY : It is used to specify the relationship between parent rows and child rows of the hierarchy. with respect to one of the root rows. Each child row must satisfy the condition of the CONNECT BY Clause. o o o START WITH : It specifies the root rows of the hierarchy. WHERE : It is used to restrict the rows returned by the Query without affecting other rows of the hierarchy. Whose Query lperforms a Join.  The General Hirarchy of Emp Data : 79 Oragle 10 g Material . If ORDER BY Clause is used. They cannot select data from a View.Empno ) .Naresh i Technologies Where NOT EXISTS ( Select * From Emp E1 Where E1.  General Representation : Root 1 2 1 3 4 9 7 8 1 0 1 1 Child 1 2 Leafs 5  Restrictions : o o o 6 They cannot be used to perform Joins. Steps Folowed :  ORACLE selects the root row ( s ) of the hierarchy. which satisfy the condition of the START WITH Clause.  ORACLE selects children by evaluating the CONNECT BY condition with respect to a current parent row. HIERARCHICAL QUERIES :  These are queries that are executed upon tables that contain hierarchical data.  ORACLE selects successive generations of child rows.  If the query contains a WHERE Clause.

Naresh i Technologies KING 7839 JONES 7566 BLAKE 7698 CLARK 7782 SCOTT 7788 FORD 7902 ALLEN 7499 MILLER 7934 ADAMS 7876 SMITH 7369 WARD 7521 MARTIN 7654 TURNER 7844 JAMES 7900  General Structure of Hierarchical Tree : LEVEL 1 : Root / Parent Level 2 : Level 3 : Root / Parent Root / Parent Child / Leaf Parent / Child Parent / Child Level 4 : Child / Leaf Child / Leaf Child / Leaf Note : To Define Hierarchical Queries Properly we must use the following Clauses. It specifies a condition that the roots must specify. Oracle uses all rows in the table as ROOT rows. 80 Oragle 10 g Material . o o START WITH CONNECT BY START WITH Clause : o o o It identifies the row(s) to be used as the Root ( s ) of a hierarchical Query. If START WITH is omitted.

Job From Emp START WITH Job = ‘PRESIDENT’ CONNECT BY PRIOR Empno = Mgr . Empno. UPDATE or DELETE Cannot be implemented.  Upon Pseudo columns only SELECT’s can be implemented. but is not actually stored in a table. Mgr. in a hierarchical query. PSEUDO Columns :  Pseudo columns behave like a table column.  The Available Pseudo Columns are …… o CURRVAL o NEXTVAL o LEVEL o ROWID o ROWNUM CURRVAL And NEXTVAL :  These Pseudo columns are applied upon the SEQUENCE SchemaObject. Sal From Emp START WITH Sal = 5000 CONNECT BY PRIOR Empno = Mgr . 81 Oragle 10 g Material . Empno. Expr Comparison – operaor Expr. Mgr . The forms of PRIOR operators is   o o PRIOR Expr Comparison – operator Expr. which refers to the Parent row. some part of the condition must use the PRIOR operator. Job From Emp START WITH Ename = ‘KING’ CONNECT BY PRIOR Empno = Mgr . Example : Sql > Select Ename. Job. The Clause can contain other conditions to further filter the rows selected by the query. CONNECT BY Clause : o o o o o This clause specifies the Relationship between Parent and Child Rows. Mgr.Naresh i Technologies o A START WITH Condition can contain a Subquery. Within the condition. Mgr. It cannot contain a Sub Query. Sql > Select Ename. Job From Emp CONNECT BY PRIOR Empno = Mgr . Sql > Select Ename. But INSERT. Empno. This caluse contains a condition that defines a relationship This condition can be any condition as defined by the syntax decription. Sql > Select Ename. Empno.

Naresh i Technologies  CURRVAL returns the Curent Value of a Sequence. LONG Columns. INERSECT.  WHEN a SEQUENCE IS Created.NEXTVAL  Increments the Sequence Value by the Declar Specification. must be located on the same database.  In a single SELECT Statement . first the SEQUENCE should be incremented with NEXTVAL.CURRVAL  Returns the Current Value of the Sequence.  The First refrence to the NEXTVAL returns the SEQUENCES Initial Value.  The SEQUENCE Values are often user for PRIMARY KEY’S and UNIQUE KEY’s. o o o o o o o o A Sub Query A View’s Query or SNAPSHOT’s Query. and locked tables.  The CURRVAL And NEXTVAL can be used only in …… o o o Restrictions :  The CURRVAL and NEXTVAL cannot be used in ….  CURRVAL and NEXTVAL should be qualified with the name of the Sequence. A SELECT Statement that is combined with another SELECT Statement with UNION. Updated tables. A SELECT Statement with the DISTINCT operator A SELECT Statement with a GROUP BY or ORDER BY Clause. Syntax : SEQUENCENAME. The WHERE Clause of a SELECT Statement The DEFAULT Value of Column in a CREATE TABLE or ALTER TABLE Statement The Condition of a CHECK Constraint. SEQUENCENAME. The following privileges should be available o o SELECT OBJECT PRIVILAGE SELECT ANY SEQUENCE  For SEQUENCES in other Schema the Qualifying Syntax is 82 Oragle 10 g Material .  Before the CURRVAL can be used for a SEQUENCE is a session. SEQUENCE :  A SEQUENCE is a schema object that cn generate unique sequential Values. all referenced sequences. we can define its INITIAL VALUE and the INCREMENT between its values.  To refer to the Current or Next Value of a SEQUENCE in the Schema of another used..  NEXTVAL Increments the sequence and returns the Next Value. The SELECT list of a SELECT Statement The VALUES Clause of an INSERT Statement The SET Clause of an UPDATE Statement.  A SEQUENCE can be accessed by many users concurrently with no WAITING or LOCKING.  A SEQUENCE can be incremented only once in a single SQL Statement. MINUS SET Operator.

Syntax : CREATE SEQUENCE SequenceName INCREMENT BY Integer START WITH Integer MAXVAL Interger / NOMAX VALUE MINVAL Integer / NOMIN VALUE CYCLE / NOCYCLE CACHE Integer / NOCACHE ORDER / NOORDER . o o SCHEMANAME.CURRVAL@DBLINK SCHEMANAME.SEQUENCENAME.  INCREMENT BY : o o o o Specifies the interval between the Sequence Numbers. If omitted defaults to incrementation of 1.  MAXVALUE : o Specifies the Maximum vaue that can be generated.  MINVALUE : o Specifies the Sequences’s Minimum Vaule. but can not be 0.NEXTVAL@DBLINK CREATING SEQUENCES : Purpose :  An object from which multiple users may generate Unique Integers.SEQUENCENAME. The SEQUENCE should be qualified with a complete or partial name of the Database Link. If the value is positive it is Incrementeal Sequence else it Decremental Sequence.SEQUENCENAME.CURRVAL SCHEMANAME.Naresh i Technologies o o SCHEMANAME.  NOMINVALUE : o Specigfies a minimum value of 1 for an ascending sequence or – ( 10 ) 26 For decending sequence.SEQUENCENAME.NEXTVAL  To refer to the value of a SEQUENCE on a Remote Database. Vaule can be Positive or Negetive.  NOMAXVAULE : 83 Oragle 10 g Material .  Can be used to generate PRIMARY KEY values automatically.

Creation of Incremental Sequence with NoCycle : Sql > Create SEQUENCE SampleSeq INCREMENT By 1 START WITH 0 MAXVALUE 5 NOCACHE NOCYCLE . Varchar2( 25 ) .  NOCYCLE : o Specifies the SEQUENCE cannot genral more values after the targeted limit. Sample Table : Sql > Create Table Sample ( SampID SampName SampDate ) .  NOORDER : o Doesnot guarantee the sequence Number without Pre order Default .  CACHE : o Specifies the Preallocation of SEQUENCE Numbers.  NOCACHE : o Specifies the values of a SEQUENCE are not Preallocated.  CYCLE : o Specifies the sequence will continue to generate values after reaching either maximum or minimum value. Vice Versa.  ORDER : o Guarantees the sequence numbers to be generated in the order of request.Naresh i Technologies o Specifies a maximum value of 10 27 for ascending sequece or –1 for Descending Sequence. For Ascending sequences the default value is SEQUENCES’s MINIMUM v alue.  If the above parameters are not specified by default 20 values are cached. 84 Oragle 10 g Material . The minimum is 2.  STARTWITH : o o Specifies the first sequence Number to be generated. Activating and Attaching the Sequence to a Table : Number ( 4 ) Constraint SampID_PK Primary Key.

Create the sample table again without PRIMARY KEY. Some validation performed. SampDate ) Values ( SampleSeq.     Child  Any Non_Root Node.  Guidelines For Altering A Sequence : o o o o o The ALTER previlege should be available. ’31-AUG-05’ ) . drop the SEQUENCE and then recreate the SEQUENCE.NextVal. Note : o o For every example DROP TABLE and DROP SEQUENCE ..  Level Pseudocolumn : o This Pseudocolumn return 1 for ROOT Node.e. Root  Highest Node within an Inverted Tree. Creating A Sequence With CYCLE : Sql > Create Sequence SampleSeq INCREMENT BY 1 START WITH 0 MAXVALUE 5 NOCACHE CYCLE . To change the START WITH. SampName. o Follow the Insert statement as previous and check the Inserted Values by executing the SELECT statement on Sample Table. Leaf  Any Node without Children.Naresh i Technologies Sql > Insert into Sample ( SampID. The START WITH option cannot by changed using ALTER SEQUENCE. Option. Parent  Any Node / Row that has children. 85 Oragle 10 g Material . A NRE MAXVALUE cannot be imposed that is less than the current SEQUENCE number. ‘Sample’. Only the future sequence numbers are affected by the ALTER SEQUENCE Statement. i. Creation of Decremental Sequence : Sql > Create Sequence SampleSeq INCREMENT BY –1 START WITH 5 MAXVALUE 5 MINVALUE 0 NOCACHE NOCYCLE . 2 for a child of a ROOT and so on.

Sqll > Select Sequence_Name. Dropping An Existing Sequence :  A SEQUENCE can be DROPPED at any time.  Once removed. Max_Value. Increment Value Maximum Value. o o START WITH CONNECY BY 86 Oragle 10 g Material . Min_Value.CURRVAL From Dual . Last_Number From User_Sequences . the SEQUENCE can no longer be referenced. Minimum Value Cycle Option Cache Option Viewing the Current Value of a Sequence : Sql > Select SampleSeq. Confirming Sequences :  All SEQUENCES that have been created are documted in the dta dictionary. Sql > DROP SEQUENCE SampleSeq .  To establish the Hierarchical relationship with LEVEL we need. Example : Sql > ALTER SEQUENCE SampleSeq MAXVALUE 10 CACHE NOCYCLE .. Increment By.  The data dictionary in which the information of SEQUENCES are stored is USER_OBJECTS.Naresh i Technologies  Modifying a Sequence : o o The ALTER Command can be used to change the present status of a SEQUENCE.  The sttings of the SEQUENCE can be confirmed by SELECTING on USER_SEQUENCES. The ALTER SEQUENCE Command can be used to change ….      Syntax : ALTER SEQUENCE SequenceName [ INCREMENT BY n ] [ { MAXVALUE n / NOMAXVALUE } ] [ { MINVALUE n / NOMINVALUE } ] [ { CYCLY / NOCYCLE } ] [ { CACHE n / NOCACHE } ] .

Level From Emp . MIN ( ColName ) FROM TableName WHERE Level = & LEVELNO CONNECT BY PRIOR ColName < ColName GROUP BY LEVEL . Sql > Select Lpad ( ‘ ‘ . Selecting Nth Highest Value From Table : Syntax : SELECT LEVEL. 2 * ( LEVEL – 1 ) ) || Ename Org_Chart . Job. Mgr. Mgr. MAX ( SAL ) FROM EMP WHERE LEVEL = & LEVELNO CONNECT BY PRIOR SAL > SAL GROUP BY LEVEL . 2 * ( LEVEL – 1 ) ) Org_Level. Example : Sql > SELECT LEVEL. Job . Sql > Select Lpad ( ‘ ‘ . Sql > Select Lpad ( ‘ ‘ . Mgr. 87 Oragle 10 g Material . Empno. 2 * ( LEVEL – 1 ) ) || Ename Org_Chart . Empno. Mgr. MIN ( SAL ) FROM EMP WHERE LEVEL = & LEVELNO CONNECT BY PRIOR SAL < SAL GROUP BY LEVEL . Sal From Emp WHERE Job ! = ‘ANALYST’ START WITH Job = ‘PRESIDENT’ CONNECT BY PRIOR Empno = Mgr . Example : Sql > SELECT LEVEL. Sal From Emp START WITH Job = ‘PRESIDENT’ CONNECT BY PRIOR Empno = Mgr AND LEVEL < = 2 . Sql > Select Lpad ( ‘ ‘ .Naresh i Technologies Sql > Select Ename. Selecting Nth Lowest Value From Table : Syntax : SELECT LEVEL. Mgr. 2 * ( LEVEL – 1 ) ) || Ename Org_Chart . Job From Emp START WITH Job = ‘PRESIDENT’ CONNECT BY PRIOR Empno = Mgr . Ename. Empno. Job. Job From Emp START WITH Job = ‘PRESIDENT’ CONNECT BY PRIOR Empno = Mgr . Empno. MAX ( ColName ) FROM TableName WHERE Level = & LEVELNO CONNECT BY PRIOR ColName > ColName GROUP BY LEVEL .

RowID’s should bnot be assigned as PRIMARY KEY’s as there is a chance of ROWID to change when the database is Exported or Imported. the ROWNUM pseudocolumn returns a number indicated the order in which Oracle selects the rwo from a set of Joined rows. RowNum. 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. /* Wrong Way */ Sql > Select * From ( Select * From Emp ORDER BY Sal DESC ) Where RowNum < 6 . Ename. Sal From Emp Where RowNum < 6 ORDER BY Sal Desc .  From Oracle 8i . Uses of ROWID Values :      ROWID is the fastest means of accessing a single row. ORDER BY can be used in VIEWS and INLINE VIEWS.  ROWID Values copntain information necessary to locate a row o o o The Row belongs to which data block in the data file. ROWID can show how a tables Row’s are stored.Naresh i Technologies ROWNUM Pseudo Column :  For each Row returned by a query. then the Rownyum condition can be forced to applied after the ordering of the rows. 88 Oragle 10 g Material . A RowID can never change during the life time of its Row. Querying for Top ‘ N ‘ Records :  We can Ask for Nth largest or smallest values of a column.  If ORDER BY Clause is embedded in a Sub Query and Rownum condition is palced in the top_level query. and so on…  The Rownum can be used to limit the Number of rows returned by the Query. Ename.  Never use Rownum and ORDER BY together as Oracle first fetches the rows according to ROWNUM and then SORT the found rows. Sal From Emp .  The Date type of the Values belonging to the RowID are of ROWID Data type. Sql > Select RowNum.  The First Row selected has a Rownum of 1. Sql > Select RowNum. RowID’s are Unique identifiers for a Row in a Table. the rows will be recordered by ORDER By Clause . Sql > Select Lpad ( ‘ ‘ .  Conditions testing for Rownum values greater than a positive integer are always False.  When ORDER BY Clause follows a Rownu. the second has 2. /* Proper Way */ ROWID PseudoColumn :  This Pseudo Column returns a Rwo’s Address for each row in the database. * ) From Emp .

 The ORDER BY Caluse when iomplemented should be applied only upon the column Numbers in the SELECT list. Job From Emp Where Empno = 20 .  Only final query ends with a semicolon.Sal ) “ Cumulative Salary “ From Emp A.ROWID Group By B.Sal . Job From Emp Where Rowid < ‘AACQQAACAAAAEHAAA’ . Sql > Select RowID. SET OPERATORS :  These operators are used to Combine information of similar date type from one or more than one table.Naresh i Technologies  When a Row is DELETED. Sql > Select Ename. UNION Operator :  The UNION Operator merges the outputs of two or more queries into a single set of rows and columns.ROWID < = B. B. Sal.  The ROWID Pseudo Column can be used in SELECT and WHERE Clauses. Job From Emp Where Rowid = ‘AACQQAACAAAAEHAAA’ . Examples : Sql > Select Job From Emp Where Deptno = 20 UNION 89 Oragle 10 g Material . Calculating the Cumulative Salary : Sql > Select B. Sum ( A.  The ROWID can never be INSERTED.ROWID.Sal. ORACLE may reassign its Rowid to a new Row that is inserted. Syntax : Select Statement 1 UNION Select Statement 2 [ ORDER BY Clause ]  The Queries are all executed independently but their output is merge. UPDATED and DELETED. Sal. Ename.  The different types of SET Opeators are o o UNION MINUS * INTERSECT * UNION ALL  SET operatiors can copmbine two or more queries into one result. Emp B Where A. Sql > Select Ename.  Data type of the corresponding columns in all the SELECT statement should be same.

Ename From Emp Where Deptno = 10 UNION ALL Select Empno.  The columns used for ordering must be defined through a number. INTERSECT Operator :  This operator returns the rows that are common between two sets of rows. Sql > Select Empno. Points to Ponder :  The two select statement may not contain an ORDER BY Clause. Ename From Emp Where Deptno = 30 ORDER BY 1 . Ename From Emp Where Deptno = 10 . UNION ALL :  It is similar to UNION. Job From Emp Where Deptno = ( Select Deptno From Dept Where Dname = ‘ACCOUNTING’ ) ORDER BY 1 . Syntax : Select Statement 1 INTERSECT Select Statement 2 [ ORDER BY Clause ] . Ename.  If the duplicate records have also to be displayed then UNION ALL is used. Job From Emp Where Deptno = ( Select Deptno From Dept Where Dname = ‘SALES’ ) UNION Select Empno. the final result of the entire UNION operation can be ordered. where UNION suppresses the deplicates. Sql > Select Empno. and Data types must match.  The number of columns retrieved by the first SELECT statement must be equal to the number of columns retrieved by the second SELECT. UNION : Sql > Select Empno. Ename From Emp Where Deptno = 30 ORDER BY 1 . Ename.Naresh i Technologies Select Job From Emp Where Deptno = 30 . Example : Sql > Select Job From Emp 90 Oragle 10 g Material . Sql > Select Empno.

Naresh i Technologies Where Deptno = 20 INTERSECT Select Job From Emp Where Deptno = 30 . Example : Sql > Select Job From Emp Where Deptno = 20 MINUS Select Job From Emp Where Deptno = 10 . Views can be created as Object Views or Relational Views. A View in practicality contains no data by itself The tables upon which a view is based are called as BASE TABLES. Syntax : Select Statement 1 MINUS Select Statement 2 [ ORDER BY Clause ] . The Object Views support o o LOB’s Nested Tables * Object Types * Varrays * REF’s  Object View is a view of a user defined type. 91 Oragle 10 g Material .  To create a subview. MINUS Operator :  This operators returns the rows Unique to the first query. we need UNER ANY VIEW system privilege or UNDER OBJECT privilege on the SUPERVIEW. where each row contains objects. PREREQUISITES :  Should have CREATE VIEW or CREATE ANY VIEW System privilege. Sql > Select Job From Emp Where Deptno = 20 INTERSECT Select Job From Emp Where Deptno = 30 . VIEWS IN ORACLE : VIEW :      It is a logical table based on one or more tables or Views. Sql > Select RowNum. and each object with a object Identifier. Ename From Emp Where RowNum < 6 . Ename From Emp Where RowNum < 7 MINUS Select RowNum.

 NOFORCE : o Specifies the View Should not be created if the base table does not Exist.  WITH READ ONLY : o Specifies that rows my only read from the base tables.  Alias_Name : o Specifies the Name of an alias for an expression in the SubQuery.  An Alias cannot be specified when creating an OBJECT View. even if the Views are Inherantly Updatable.  WITH CHECK OPTION : o Specifies that only rows that would be retrieved by the SubQuery can be INSERTED.  The above privileges must be granted the privileges directly. AliasName …. UPDATED or DELETED. UPDATE or DELETE Rows from all tables or Views on which the VIEW is based. rather than a role.  FORCE : o Specifies the VIEW has to be created even if the base tables dows not exist.  OR REPLACE : o Specifies the view has to be replaced if already Existing. RESTRICTIONS :  If a View has INSERTED of Triggers. which is default. TYPES OF VIEWS : 92 Oragle 10 g Material . INSERT.] ) ] As SubQuery [ WITH { CHECK OPTION / READ ONLY } CONSTRAINT ConstraintName ] ..  CONSTRAINT : o Constraint_Name specifies the name of the WITH CHECK Option or READ ONLY Constraint. Syntax : Create [ OR REPLACE ] VIEW [ { FORCE / NOFORCE } ] VIEW ViewName [ ( AliasName [ . then only View created on it must have INSTEAD OF Triggers.Naresh i Technologies  The OWNER of the Schema should have SELECT.

Contains a function call. To_Char ( “ Basic Salary “ .. Ename Name . Sql > Select “ ID Number “. Simple Views : o These Views access one Base Table. 93 Oragle 10 g Material .  Complex Views : o o o o Contain a SubQuery that can perform any of these actions. Sal “ Basic Salary “ . Containg a Functional Call . Complex Views : o o Complex Views can contain SubQueries.Empno E. Groups rows using a GROUP BY or DISTINCT Clause. Queries    That Retrieve from multiple Base Tables Group Rows using a GROUP BY or DISTINCT Clause. Selecting Data From A View : Sql > Select Name. Ename.99’ ) Monthly “ Basic Salary “ * 12 Annual From Employees Where “ Basic Salary “ > 2500 .Naresh i Technologies  Simple Views : o Which contains a SubQuery that retrieves from one base table. Job From Employees .Ename EmployeeID. Sql > Select “ ID Number “ . ’99. “ Basic Salary “ * 12 From Employees . Job Designation From Emp .999.99. Name . Name . Retrieving from multiple base tables. Example : Sql > Create VIEW Employees As SELECT Empno “ ID Number “ . The SubQuery can contain. Example : Sql > Create VIEW EmpInfo As Select E.

Mgr = M.Naresh i Technologies D.Sal Basic .Grade .Dname DeparatmentName From Emp E. D.RowID .Deptno .Grade Grade From Emp E .HiSal ORDER BY S.Sal . B.Sal BETWEEN S.Sal ) As Cum_Sal From Emp A.LoSal AND S. Sal Monthly .Deptno = E.Deptno ORDER BY D. VIEWS in Data Dictionary :  Once the View has been created. Sql > Create VIEW EmpGrades As Select E. we can query upon the DATA DICTIONARY table called USER_VIEWS to see the Name and definiton of the View. Emp B Where A. Initcap ( E. Emp M Where E. Sal * 12 Annual From Emp Where Deptno = ( Select Deptno From Dept Where Dname = ‘ACCOUNTING’ ) ORDER BY Annual .RowID < = B.Ename ) || ‘ Works Under ‘ || M. Sql > Create or Replace VIEW EmpManagers AS Select RowNum SerialNo .RowID GROUP BY B. S. Deptno . Sql > Create or Replace VIEW OrgDesignations As Select Job From Emp Where Deptno = 10 UNION Select Job From Emp Where Deptno IN( 20.Ename “ Employee And Managers “ From Emp E.Empno .Ename Name .  The text of the SELECT statement that constitures the VIEW is stroed in a LONG Column 94 Oragle 10 g Material . 30 ) . Sql > Create or Replace VIEW CumSum As Select B. Salgrade S Where E. E. Dept D Where D. Sum ( A.Deptno DepartmentID .Sal . Sql > Create or Replace VIEW EmpAccounts As Select Ename.

Sal ) From Emp E.Sal ) . AverageSalary. Creating Views with Columns Declarations :  When a VIEW is being crated. MaxSalary . and regranting object privileges. Max ( E. Designation . Sum ( E.  A VIEW can be altered without Dropping. Grade ) As Select Ename. that it can project. Inserting The Total Data of Employees From Department 10 Using View : Sql > Create Table Dept10 As Select * From InsertDept10 . when data is accessed using a VIEW are o o o Retrieves the VIEW definition from the Data Dictionary table USER_VIEWS.Sal BETWEEN S.Dname . BasicSalary .Naresh i Technologies Data Access Using Views :  The Steps or operations performed by the Oracle Server.Deptno Group By D.Deptno = D.HiSal . SalGrade S Where E.Sal ) . along with the VIEW’s definition. Example : Sql > Create VIEW DeptSalSummary ( DepartmentName . are listed in the same order as the columns in the SubQuery. recreating. Converts the view query into an equivalent opration on the underlying base table or tables.  The assigned column Aliases in the CREATE VIEW Clause.Sal ) . Sal. SalarySum ) As Select D. Min (E. Avg ( E. we can specify the Names of the Columns.LoSal AND S. Job. MinimumSalary . Sql > Create VIEW InsertDept10 As Select * From Emp Where Deptno = 10 .Dname. Modifying A View :  OR REPLACE Option is used to Modify an existing VIEW with a new definition. Sql > Create Table EmpGrades ( Employee . Grade From Emp E. Dept D Where E. 95 Oragle 10 g Material . Checks the Access privileges for the view base table.

 An INLINE VIEWE is not a Schema Object. Dropping a View has no affect on the tables upon which the View is created. E1. E2. Example : Sql > Create View InsertDept ( DeptID. E1.MaxSal .  A row can be removed from a VIEW unless it contains.Ename . Max ( Sal ) MaxSal From Emp GROUP BY Deptno ) E2 Where E1. VIEWS or APPLICATIONS based on deleted Views become invalid. INLINE VIEWS :  An INLINE VIEW is a SubQuery with an ALIAS ( Called as CORRELATION NAME ).MaxSal From Emp E1 . o o o o o GROUP Function A GROUP By Clause The ROWNUM PESUDO 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 are NOT NULL Columns. We need DROP ANY VIEW privilege to remove the VIEWS.  An INLINE VIEW in the FROM Clause of a SELECT statement defining Data Source for the SELECT statement. Rules for Performing DML Operations On A View :  DML operatons can be perfomed upon a table through VIEW. Example : DROP VIEW InsertDept .Deptno.Sal .Deptno AND E1.Naresh i Technologies DROPPING A VIEW :     The DROP VIEW statement is used to Remove a View permanently.  An INLINE VIEW is similar to using a named SubQuery in the FROM Clause of the Main Query. ( Select Deptno. 96 Oragle 10 g Material .Deptno = E2. Syntax : DROP VIEW ViewName . and without DEFAULT Value.Sal < E2. Examples : Sql > Select E1. that can be used within a SQL Statement.

Naresh i Technologies DeptName . Job From Emp Where Deptno = 20 WITH READ ONLY . Ename.  CONSTRAINTS on VIEWS can be enforced through CONSTRAINTS n base tables. But the use is very limited. Loc From Dept . Dname. Applying With READ ONLY OPTION :  By Adding the WITH READ ONLY option we can ensure that no DML operations are executed.  VIEWS allow Integrity Constraits and data validation check to be enforced on data being Inserted or Updated.  The WITH CHECK Option Clause specifies that INSERTS. Example : Sql > Create Or Replace View EdpetRead ( EmpId. & UPDATES performed through the V?IEW are not allowed to create rows.  VIEWS make it possible to perform Referential Integrity Checks. that the VIEW cannot SELECT. Place ) AS Select Deptno. Designation ) AS Select Empno. Restrictions On View Constaints :  The VIEW Constraints area subset of TABLE CONSTAINTS.  An attempt to perform a DML operation results in ORACLE SERVER ERROR. Using with CHECK Option Clause :  To ensure that DML on the view stays within the domain of the VIEW by using the WITH CHECK option Clause.  Using VIEWS we can enforece constraints at database level. VIEW CONSTRAINT :  In practicality Oracle does not enforce View constrains. Sql > Create Or Replace VIEW Emanager AS Select * From Emp Where Job = ‘MANAGER’ WITH CHECK OPTION CONSTRAINT EmanagerView . but operations on VIEWS are subject to the INTEGRITY CONSTRAINTS defined on the underlying base tables. 97 Oragle 10 g Material .  Using VIEWS we can protect the DATA INTEGRITY. Name. Example : Sql > Create Or Replace VIEW EDept30 AS Select * From Emp Where Deptno = 30 WITH CHECK OPTION CONSTRAINT EDept30ChkView .

RELY CLAUSE :  RELY and NORELY are valid only when we are modifying an existing CONSTRINT. VALIDATE / NOTVALIDATE :  The Behavior of VALIDATE and NOVALIDATE always depends on whether the CONSTRAINT is ENABLED / DISABLED. DEFERRABLE :  It indicated that in subsequent transctions we can use the SET CONSTRAINT(s) Clause to defer checking the CONSTRAINT until after the transaction is committed.  The CHECK CONSTRAINT is imposed using WITH CHECK OPTION. PRIMARY KEY And FOREIGN KEY CONSTRAINTS can be specified on VIEWES. DEFERRABLE Clause :  The DEFERRABLE and NOTDEFERRABLE parameters indicate whether or not.  The default is NOT DEFERRABLE. in an unenforced query rewrite Integrity mode. in the subsequent transaction. wee cannot use the SET CONSTRAINT(s) Clause to defer checking the CONSTRAINT UNTIL the transaction is committed. RELY : It activates an existing CONSTRAINT is NOVALIDATE mode for query rewrite.  VIEW CONTRAINTS are supported only in DISABLE NOVALIDATE mode. NOTDEFERRABLE :  It indicates that in subsequent transctions.Naresh i Technologies  Only UNIQUE. either EXPLICITLY or by DEFAULT.  As VIEW CONSTRAINTS are not enforced directly.  The checking of a NOTDEFERRABLE CONSTRAINT can Never be DEFERRED to the end of the transactions. 98 Oragle 10 g Material . we cannot specify INTIALLY DEFERRED or DEFREEABLE. Note :  INTIALLY DEFERRED is not valied if the CONSTRAINT is declared to be NOTDEFERRABLE  NOT DEFREEABLE CONSTRAINT is AUTOMATICALLY INITIALLY IMMEDIATE and can never be INITIALLY DEFERRED. INITIALLY DEFERRED :  It Indicated that Oracle should check this CONSTRAINT at the end of SUBSEQUENT transactions. constraint checking can be deferred until the end of the transction using the SET CONSTRAINT statement.

INITIALLY Clause :  It established the default checking behavior for CONSTRAINTS that are DEFERRABLE.  The INITIALLY setting can be overridden by a SET CONSTRAINT(s) statement in a subsequent Transaction. Email UNIQUE RELY DISABLE NOVALIDATE . Ename. Note : In the above case the default constraint is NOT DEFERRABLE INTITALLY IMMEDIATE constraint CHECK. Email From Emp .  To alter the CONSTRAINTS Deferability. Restriction On The DEFERRABLE Clause :  The parameters cannot be specified for a VIEW CONSTRAINT.Naresh i Technologies  The setting is effect lets the user to disable the CONSTRAINT temporarily while making changes to the database that might violate the CONSTRAINT until all the changes are complete. Sql > Create View EmpSalary ( EmpID.  VIEW CONSTRAINTS cannot be defined on attribute of an object column. Example : Sql > Create Table Games ( Scores Number Check ( Scores > = 0 ) ) . Restriction on RELY Clause : We cannot set a NOT NULL CONSTRAINT to RELY.  The constraint state clauses can be specified in any order. but each state can be specified only once.  It is the default setting.  We cannot specify the Using_Indes_Clause the Exceptions_Clause or the ON DELETE Clause of the Reference_Clause. Ename. Initially Immediate :  It indicated that Oracle should check this CONSTRAINT at the end of each subsequent SQL statement . we must DROP the CONSTRAINT and recereate it. Constraint Sco_Num_Unq UNIQUE ( Scores ) INITIALLY DEFERRED DEFERRABLE ) . Sql > Create Table Games1 ( Scores Number . WORKING WITH INDEXES : 99 Oragle 10 g Material . Constraint ID_PK PRIMARY KEY ( EmpID ) RELY DISABLE NOVALIDATE ) AS Select Empno.  Constraint State specifies how and when ORACLE should enforce the CONSTRAINT.

UNLIMITED TABLESPACE system privilege or SPACE QUOTA on TABLE SPACES must be available. Fast Access to Rows. Enable query to evaluate value retuned by an expression. PRE REQUISITES : The table or CLUSTER to be INDEXED must be in the Own Schema. Types of INDEXES :  NORMAL INDEXES : o o They are default Indexes.  It provides Direct.  BITMAP INDEXES : o They store RowID’s associated with a key value as a Bitmap.  For FUCTION BASED INDEXES. then a SECONDARY INDEX is created.     RESTRICTIONS :  If INDEX is locally partitioned then the TABLE msut be partitioned. as that of the TABLE. Restriction On INDEX Columns :  An INDEX cannot be created on Columns or ATTRIBUTES whose type is …. Cerate any index SYSTEM privilege must be available.  If TABLE is TEMPORARY TABLE. INDEX object parivilege should be available on the table to INDEXED.Naresh i Technologies 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. the FUNCTION used for Indexing must be marked as DETERMINISTIC.  For DOMAIN INDEXES. They are created with B-Tree principle.  PARTITIONED INDEXES : o They contain partitions containing an entry for each value that appears in the Indexed columns of the table. EXECUTE object privilege on the INDEXTYPE should be available.  FUNCTION BASED INDEXES : o o They are based on expressions.  If the TABLE is INDEX ORAGANIZED. then INDEX is also TEMPORARY with the same scope.  DOMAIN INDEXES : o They are INDEXES which are instances of an application specific index of type Indextype. 100 Oragle 10 g Material .

 We cannot specify both UNIQUE and BITMAP. Syntax : Create [ UNIQUE ] INDEX IndexName or [ BITMAP ] ON TableName ( Column_name [ . Simple Index Example : Sql > Create INDEX EmpEmpnoIDx On Emp ( Empno ) .Naresh i Technologies o o o o o USER DEFINED LONG LONG RAW LOB REF  An INDEX on REF tyhpe columns Or attributes have to be declared with a SCOPE Clause.] ) TABLESPACE TableSpaceName . 101 Oragle 10 g Material . ColumnName ….  BITMAP cannot be specified for a DOMAIN INDEX. Sql > Create INDEX DeptDeptnoIDx On Dept ( Deptno ) . * UNIQUE Cannot be specified for a domain Index. Unique : * Specify UNIQUE to indicate that the value of the column or columns upon which the Index is based must be UNIQUE. CLUTER – INDEX – CLAUSE :  It identifies the CLUSTER for which a CLUSTER INDEX has to be created.  Each BIT in the BITMAP corresponds to a possible RowID.  BITMAP Indexes store the RowID’s associated with a key value as a BITMAP. Restrictions : * We cannot specify both UNIQUEand BITMAP. Restrictions :  BITMAP cannot be specified when creating a global partitioned Index. BITMAP :  Specify BITMAP to indicate that INDEX has to be careated with a BITMAP for each DISTINCT KEY.  BITMAP SECONDARY INDEX canot be created on an INDEX ORGANIZED TABLE unless the INDEX ORGANIZED table has a mapping table Associated with it.

Lname ) . StreetName ) . Examples : 102 Oragle 10 g Material .  An INDEX on a NESTED TABLE COLUMN can be created by creating the INDEX on the NESTED storage Table. CREATING FUNCTION BASED INDEXES :  These are indexes based on expressions.  The Index Expresions are Built from table columns. we shoul. Sql > Create UNIQUE INDEX StuPhnoIDxUNQ ON Student ( PhoneNo ) . Sql > Create INDEX Emp_Name_Place_IDX ON Emp ( Ename . Sql > Create INDEX Stud_Fname_Lname_Idx On Student ( Fname.  The ORACLE OPTIMIZER can dynamically convert BITMAP INDEXES entries to ROWID’s during the query processing.d be sure that the value of the Functins is not NOT NULL in subsequent Queries. CRATING COMPOSITE INDEXES :  COMPOSITE INDEX is an INDEX on multiple Columns. contancts SQL Functions and User Defined Function.Naresh i Technologies  CLUSTER INDEX Cannot be created for a HASH CLUSTER. Example : Sql > Create INDEX EmpUpperCaseIDx ON Emp ( UPPER ( Ename ) ) . CREATING UNIQUE INDEXES : Sql > Create UNIQUE INDEX EmpEmailIDxUNQ ON Emp ( Email ) . Note : The Function Based Indexes are used only when the Query Statement is executed through the specified function.  Functin based Indexes defined with the UPPER ( Column_Name ) or LOWER ( Column_Name ) allow case Insensitive Searches.  To ensure that Oracle uses the Index rather than performing a full table scan. BITMAP INDEXING :  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 inferequently updated. TABLE – INDEX – CLAUSE :  It identifies the TABLE upon which the INDEX is being defined.  Oracle treats INDEXES with columns marked DESC as Functins Based Indexes.  BITMPAT INDEXES add to the cost of all data manipulation transaction against the tables they INDEX.

The column contains a large number of NULL values. 103 Oragle 10 g Material . the Corresponding INDEXES are also dropped.  When a table is droopped. The Column that are involved in an INDEX by querying USER_IND_COLUMNS. both logically and physically. INDEXE’s can be created or Dropped at any time and have no effect on the base tables or other INDEXES. more the Indexes lead to more faster performance. INDEX Reduces the Disk I / O by using rapid path Access method to locate the data quickly. The Column contains a wide range of values. 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 morethan 2 – 4 % of the rows. DATABASE SECURITY :  The SECURITY upon databases is applied by defining and describing separate SCHEMA OBJECTS and GRANTING required PRIVILEGES upon them. Limitations :  BITMAP INDEXES should not be used for tables involved in ONLINE TRANSACTION PROCESSING applications due to the Internal Mechanisms Oracle user to maintain them. INDEX is used by the ORACLE SERVER to speed up Retrieval of rows by using a Poiter. The table is updated frequently The indexes can be confirmed form the USER_INDEXES Data Dictionarly. Specification of An INDEX : INDEX IS A Schema Object. To DROP an INDEX DROP command is used DROP INDEX INDEX_NAME .        INDEX Creation is of Two Types : 1 ) Automatic 2 ) Manual  One Table more than one Index can be created. Two or more columns are frequently used together in a WHERE clause or Join Condition. WHEN TO CREATE AN INDEX :      The Column is used frequently in the WHERE Clause or ina Join Condition.  Restricted with usage to tables involved in Batch transactions. The table is large and most queries are expected to retrieve less than 2 – 4 % of the rows.  Each DML operations that is committed on a table with Indexes means that the Indexes must be updated. INDEX is used and maintained automatically by the ORACLE SERVER. But this does not mean that.Naresh i Technologies Sql > Create BITMAP INDEX EmpBitMapJob ON Emp ( Job ) . INDEXE’s are Independent of the table it INDEXES.

. Types of Privileges :  System Privileges : o They allow a user to perform certain actions within the database. ON < Object_Name > To < User Name >  GRANT command is used when we waqnt the database to be shared with other users. …. Checking the Object Privileges Granted :  The schema object that stores the information about the privileges is o USER_TAB_PRIV_MADE  The Column of USER_TAB_PRIV_MADE 104 Oragle 10 g Material . but also on VIEWS.. SELECT.  REVOKE is usede when we want one database to stop sharing the information with other users.  REVOKE privileges is assigned not only on table onject. INDEXES.… Example : Sql > GRANT SELECT ON EMP TO ENDUSERS . Synonyms.  GRABT cinnabd cab be issued not only on TABLE OBJECT.. ON < OBJECT NAME . Job ) ON Emp To EndUsers . Example : Sql > REVOKE INSERT . SEQUENCES etc. Ename.. GRANT COMMAND : Syntax : GRANT < PRIVILAGES NAME > ...  Object Privileges : o An Object Privilege allows a user to perform cetain actions on database objects.Naresh i Technologies  In ORACLE the Privileges can be ranted as well as Revolved. but also Views. Sql > GRANT INSERT ( Empno.. SYNONYMS.  The other users are GRANTED with certain type of rights. TO < USER NAME . DELETE ON EMP TO OPERATORS . Indexes etc…. . DELETE ON EMP FROM Operators . REVOKE COMMAND : Syntax : REVOKE < PRIVILEGE NAME > .. Sql > GRANT INSERT.

Naresh i Technologies o o o GRANTEE GRANTOR GRANTABLE TABLE_NAME PRIVILEGE HIERARCHY Checking Obect Privileges Received :  The schema object that stores the information about the PRIVILEGES received are… o USER_TAB_PRIVS_RECD  The column of USER_TAB_PRIVS_RECD are …. assign PRIVILEGES to that ROLE. ROLE’s CREATION : 105 Oragle 10 g Material .  A ROLE can be assigned with a Password. WORKING WITH ROLES :  A ROLE is a group of PRIVILEGES that can be assigned to a USER or another ROLE. the specific USER can perform the Tasks. we can CREATE a ROLE. Advantages :  Rather than assigning Privileges one at a time directly to a USER. all USERS and ROLES assigned that automatically receive or lose that PRIVILEGE  We can Assign multiple roles to a USER or ROLE. o o o OWNER GRANTOR GRANTABLE TABLE_NAME PRIVILEGE HIERARCHY MAKING USE OF OBJECT PRIVILEGES :  Once a particular USER has benn granted an object privilege. and then GRANT that ROLE to multiple USERS and ROLES. Example : Sql > CONNECT SATISH / YELLANKI Sql > SELECT * From SCOTT.  Steps to be performed o o Connect to the required user..EMP . Execute the require SQL Statement using the object Hierarchy.  When you ADD or DELETE a PRIVILEGE from a ROLE.

…. USERNAME ADMIN_OPTION OS_GRANTED Checking System Privileges Granted to A ROLE :  The Schema Object ROLE_SYS-PRIVS specifies the SYSTEM PRIVILEGES Granted to a ROLE. Granting Privileges to ROLE :  The ROLES are granted privileges using the GRANT statement. INSERT. * ROLE * PRIVILEGE Checking Object Privileges Granted to a Role : * ADMIN_OPTION GRANTED_ROLE DEFAULT_ROLE 106 Oragle 10 g Material ..  A ROLE can be granted both SYSTEM as well as OBJECT privileges Example : Sql > GRANT SELECT. Checking ROLES Granted to a USER :  The SCHEMA OBJECT USER_ROLE_PRIVS specifies the roles granted to a USER. ROLE2 . DELETE ON EMP TO Sales_Manager . Granting A ROLE To a USER : Sql > GRANT Sales_Manager to Scott .  The Steps in Implementing the ROLES o o o ROLE CREATION GRANTING PRIVILEGES TO ROLES GRANTING ROLES TO USERS or OBJECTS Syntax : CREATE ROLE < Role Name > IDENTIFIED BY < Password > ] . Granting Multiple ROLES to Another Role : Sql > GRANT ROLE1.Naresh i Technologies  To CREATE a ROLE we should have the CREATE ROLE SYSTEM privilege.  The SCHEMA OBJECT USER_ROLE_PRIVS contains the following columns. UPDATE.  The columns present are…. TO < TARGET_ROLE_NAME > . Example : Sql > CREATE ROLE Sales_Mangers IDENTIFIED BY SalesAudit .

Example : Create Synonym EmpInfo FOR SCOTT.  The columns present are …… ROLE PRIVILEGE Revoking a ROLE : Sql > REVOKE Sales_Managers From Scott .Emp . Dropping A Role : Syntax : Example : DROP ROLE < Role_Name > DROP ROLE Sales_Managers . Example : Sql > Create PUBLIC SYNONYM EmpInfo FOR SCOTT. we can avoid the entry of the schema Name. Revoking Privileges From A ROLE : Sql > REVOKE ALL ON Emp From Sales_Managers . < ObjectName > . which acts as an alternate name for an existing object. and it can be accessed by all USERS. Synonym Types :  The Synonyms are practically of two types PRIVATE SYNONYM PUBLIC SYNONYM  We should have CREATE PUBLIC SYNONYM privilege. OWNER GRANTABLE TABLE_NAME COLUMN_NAME WORKING WITH SYNONYMS :  A Synonym is schema object.  By using a Synonym.EMP . when referencing upon objects that belong to other schema.  The CREATE Synonym Privileges is necessary to execute the creation of a Synonym. Syntax : Create Synonym < Synonym Name > FOR < SchemaName >.Naresh i Technologies  The Schema Object . 107 Oragle 10 g Material . ROLE_TAB_PRIVS specifies the OBJECT PRIVILEGES granted to a ROLE.

Naresh i Technologies OLAP FEATURES IN ORACLE :  Some features for Query processing is ORACLE include the use of ONLINE ANALYTICAL PROCESSING ( OLAP ) upon the Data base. 108 Oragle 10 g Material .  OLAP features are useful for DATA WAREHOUSING and DATA MART applications. Job. Sql > Select Job. Deptno. Passing Multiple Columns To RollUp :  When multiple columns are passed to ROLLUP.  The generated substotals “ ROLL UP “ to produce grant total . Avg ( Sal ) Average From Emp Group By RollUp ( Job. TOP_N QUERIES GROUP BY CUBE ROLL UP ROLL UP :  It is a GROUP BY operation and is used to produce subtotals at any level of the Aggregation.  The OLAP operations are performance enhancements. Job ) . Deptno ) . Sum ( Sal ) From Emp Group By RollUp ( Deptno ) . Deptno ) . Use the Nvl ( ) Function for proper meaning. Deptno. Sum ( Sal ) Salary From Emp Group By RollUp ( Deptno. Sql > Select Job. Example : Sql > Select Deptno.) General Implementation : Example : Sql > Select Deptno. Sum ( Sal ) From Emp Group By RollUp ( Job ) .  The totaling is based on a one dimensional Data Hierarchy of grouped Information. Syntax : GROUP BY ROLLUP ( Column1. the ROLL UP . Column2 …. Sql > Select Job. Note : o o CUBE : NULL Values in the output of ROLLUP operations typically mean that the row contains subtotal or grant total information. Sum ( Sal ) Salary From Emp Group By RollUp ( Job. groups the rows into blocks with the same column values.

Sql > Job. 109 Oragle 10 g Material . Sum ( Sal ) From Emp Group By RollUp ( Job ) . Sum ( Sal ) Salary From Emp Group By CUBE ( Deptno. The first item is always the name of the column that need to be DECODED. ……. The function works on the same principle as the if – then – else. Example : Sql > Deptno.Naresh i Technologies  It is an extension similar to ROLLUP.  GROUPING ( ) Function is used only upon queries that use ROLLUP or CUBE. and returns 0 when the column value is NOT NULL. Return Default ) From TableName .  GROUPING ( ) Function returns 1 when the column value is NULL. Deptno ) . Substitute1. Value 1.  GROUPING ( ) Function is useful when we want to display a value when a NULL would otherwise be returned. Job . DECODE ( Deptno. Example : Sql > Select Ename. ‘ACCOUNTING’ . Deptno . Syntax : Select DECODE ( ColumnName. Sum ( Sal ) From Emp Group By RollUp ( Deptno ) .  The implementation of CUBE is also called as n-dimensional CROSS_TABULATION. we can optionally specify a DEFAULT Value. DECODE Function :      It is a single row function. Substitute2. Job. Once all value-substitute paris have been defined. Sql > Select GROUPING ( Job ) . Job ) . Value 2.  The result of CUBE is a summary that shows subtotals for every cominiation of columns or expressions in the GROUP BY clause . Example : Sql > Select GROUPING ( Deptno ) .  The function has no restrictuon on the input and output data type. Sum ( Sal ) Salary From Emp Group By CUBE ( Job. Deptno . We can pass a variable number of values into the call of the DECODE( ) function. Applying Grouping ( ) Function :  The GROUPING ( ) Function accepts a column and returns 0 or 1. 10 .  CUBE allows to take a specified set of grouping columns and crate sub totals for all possible cominatins of them.

Naresh i Technologies 20 , ‘RESEARCH’ , 30 , ‘SALES’ , 40 , ‘OPERATIONS’ , ‘OTHER’ ) Departments From Emp ORDER BY Departments ; Sql > Select Ename || ‘ Takes Care of ‘ || DECODE ( Job, ‘ANALYST’ , ‘ANALYSIS’ , ‘CLERK’ , ‘FIRING’ , ‘MANAGER’ , ‘MANAGING’ , ‘PRESIDENT’ , ‘ADMINISTRATION’ , ‘SALESMAN’ , ‘SALES’ ) Responsibilities From Emp ; Sql > Select Ename, Job, DECODE ( Job , ‘CLERK’ , ‘E’ , ‘SALESMAN’ , ‘D’ , ‘ANALYST’ , ‘C’ , ‘MANAGER’ , ‘B’ , ‘PRESIDENT’ , ‘A’ , ‘O’ ) GRADES FROM EMP ORDER BY JOB ; Sql > Select Count ( * ) Total , Sum ( DECODE ( To_Char ( Hiredate, ‘YYYY’ ) , 1980,1,0 ) ) Sum ( DECODE ( To_Char ( Hiredate, ‘YYYY’ ) , 1981,1,0 ) ) Sum ( DECODE ( To_Char ( Hiredate, ‘YYYY’ ) , 1982,1,0 ) ) Sum ( DECODE ( To_Char ( Hiredate, ‘YYYY’ ) , 1983,1,0 ) ) From Emp ; Sql > Select Job, Sal, DECODE ( Job, ‘ANALYST’ , Sal * 1.1 , ‘CLERK’ , Sal * 1.15 , ‘MANAGER’ , Sal * 1.2 , Sal ) “REVISED SALARY “ From Emp ; Sql > Select Count ( DECODE ( Deptno, 10 , ‘ * ‘ , NULL ) ) D10_COUNT , Sum( DECODE ( Deptno, 10 , Sal , NULL ) ) D10_Sal , Count ( DECODE ( Deptno, 20 , ‘ * ‘ , NULL ) ) D20_COUNT , Sum( DECODE ( Deptno, 20 , Sal , NULL ) ) D20_Sal , Count ( DECODE ( Deptno, 30 , ‘ * ‘ , NULL ) ) D30_COUNT , Sum( DECODE ( Deptno, 30 , Sal , NULL ) ) D30_Sal From Emp ; “1980” , “1981” , “1982” , “1983”

Sql > Select Job, Sum ( DECODE ( Deptno , 10 , Sal ) ) “ Deptno 10 “ , Sum ( DECODE ( Deptno , 20 , Sal ) ) “ Deptno 20 “ , Sum ( DECODE ( Deptno , 30 , Sal ) ) “ Deptno 30 “ , Sum ( Sal ) “Total “ From Emp GROUP BY Job ; Grouping With DECODE ( ) :

110

Oragle 10 g Material

Naresh i Technologies  The DECODE ( ) Function can be used to convert 1 and 0 returned through GROUPING ( ) into a meaningful outpout. Examples : Sql > Select DECODE ( GROUPING ( Deptno ) , 1, ‘All Departments’ , Deptno ) Departments , Sum ( Sal ) From Emp Group By RollUp ( Deptno ) ; Sql > Select DECODE ( GROUPING ( Job ) , 1, ‘All Designations’ , Job ) Designations , Sum ( Sal ) From Emp Group By RollUp ( Job ) ; DECODE ( ) and GROUPING ( ) for Converting Multiple Column Values : Example : Sql > Select DECODE ( GROUPING ( Deptno ) , 1 , ‘All Departments’ , Deptno ) Departments , DECODE ( GROUPING ( Job ) , 1, ‘All Designations ‘ , Job ) Designations , Sum ( Sal ) From Emp Group By RollUp ( Deptno , Job ) ;

GROUPING ( ) With DECODE ( ) and CUBE : Example : Sql > Select DECODE ( GROUPING ( Deptno ) , 1 , ‘All Departments’ , Deptno ) Departments , DECODE ( GROUPING ( Job ) , 1, ‘All Designations ‘ , Job ) Designations , Sum ( Sal ) From Emp Group By CUBE ( Deptno , Job ) ; Applying Grouping SETs Clause :  The GROUPING SETS Clause is used to get the Subtotal rows. Example : Sql > Select Deptno, Job, Sum ( Sal ) From Emp Group By GROUPING SETS ( Deptno, Job ) ; Working with CASE Expression :  The CASE Expression can be used to perform if – then – else logic in SQL.  CASE is similar to DECODE byut is ANSI – Compliant.  CASE Expressions are of two types

111

Oragle 10 g Material

Naresh i Technologies

o o

Simple CASE Expressions Searched CASE Expressions.

Simple CASE Expressions :  These Expressions are used to determine the retuned value. Syntax : CASE Search_Expr WHEN Expr 1 THEN Result 1 WHEN Expr 2 THEN Result 2 . . ELSE Default_Result END ; Example : Sql > Select Ename, Deptno CASE Deptno WHEN 10 THEN ‘ACCOUNTS’ WHEN 20 THEN ‘RESEARCH’ WHEN 30 THEN ‘SALES’ WHEN 40 THEN ‘OPERATIONS’ ELSE ‘NOT FOUND‘ END From Emp ; SEARCHED CASE Expressions :  They use conditions to determine the returned value. Syntax : CASE WHEN Condition 1 THEN Result 1 WHEN Condition 2 THEN Result 2 : WHEN Condition n THEN Result n ELSE Default_Result END Example : Sql > Select Ename, Deptno , CASE WHEN Deptno = 10 THEN ‘ ACCOUNTING’ WHEN Deptno = 20 THEN ‘ RESEARCH’ WHEN Deptno = 30 THEN ‘ SALES’ WHEN Deptno = 40 THEN ‘ OPERATIONS’

112

Oragle 10 g Material

 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.ORA File :      OPTIMIZER_MODE = CHOOSE JOB_QUEUE_INTERVAL = 3600 JOB_QUEUE_PROCESSES = 1 QUERY_REWRITE_ENABLED = TRUE QUERY_REWRITE_INTEGRITY = ENFORCED 113 Oragle 10 g Material . Views :  AGGREGATION on a Single Table. Sal.  They are used to increase the speed of queries on Very large databases Queries Making Use of M.  REWRITING QUERIES to yuse MATERIALIZED VIEWS rather than detail relations. results in a significant performance gain.  AGGREGATIONS and JOINS.  PRIOR to Materialized Views. Sql > Ename. Sql > GRANT CREATE MATERIALIZED VIEW TO SCOTT .  JOINS Between Tables. the Concept of SNAPSHOT was Implemented.  QUERIES are then directed to the MATERIALIZED VIEW and not to the underlying DETAIL TABLES or VIEWS. MATERIALIZED VIEWS :  Materialized Views are used in DATA WAREHOUSES.  Materialized Views can be used to replicate data.Naresh i Technologies ELSE ‘ Not Specified ‘ END From Emp . CASE WHEN Sal > = 800 AND Sal < = 2000 THEN ‘ LOWEST PAY ‘ WHEN Sal > = 2000 AND Sal < = 4000 THEN ‘ MODERATE PAY ‘ ELSE ‘ HIGH PAY ‘ END From Emp . Set the InitSid.  After above process is completed then the QUERY OPTIMIZER transparently rewrites the request to use the MATERIALIZED VIEW. Query Rewrite :  Materialized Views improve query performance by PRECALCULATING Expensive JOIN and AGGREGATION operations on the DATABASE PRIOR to Execution time and stores the results in the DATABASE. PREREQUISITES FOR MATERIALIZED VIEWS PRIVILEGES : Sql > GRANT QUERY REWRITE TO SCOTT . Sql > ALTER SESSION SET QUERY_REWRITE_ENABLED = TRUE .

‘ESTIMATE’ ) .Deptno = D. Sum ( Sal ) From Emp E. Creating Optimizer Statistics and Refreshing Materialized View : Sql > EXECUTE DBMS_UTILITY. Sql > SELECT Deptno. Job . Sql > EXECUTE DBMS_MVIEW.REFRESH ( ‘Emp_Dept_Sum’ ) . Count ( * ) . Job . 114 Oragle 10 g Material . Job ) . Job .Deptno Group By Dname. Creating Optimizer Statistics and Refreshing Materialized Views : Sql > EXECUTE DBMS_UTILITY. Job.Deptno Group By Dname. Sum ( Sal ) From Emp Group By Deptno.Deptno = D. Examples of Materialized View with Join / Aggregation : Sql > CREATE MATERIALIZED VIEW Emp_Dept_Sum ENABLE QUERY REWRITE AS SELECT Dname.ANALYZE_SCHEMA ( ‘SCOTT’ . Job . Sum ( Sal ) From Emp Group By RollUp ( Deptno. Sum ( Sal ) From Emp E .Naresh i Technologies Example of Materialized View With Aggregation : Sql > Create MATERIALIZED VIEW Emp_Sum ENABLED QUERY REWRITE AS SELECT Deptno . Dept D Where E.ANALYSE_SCHEMA ( ‘SCOTT’ . Job. Dept D Where E. Testing the Materialized Views : Sql > SET AUTOTRACE ON EXPLAIN Sql > SELECT Dname.REFRESH ( ‘Emp_Sum’ ) . Jon. Testing Materialized View : Sql > SET AUTOTRACE ON EXPLAIN . Putting the Things with RollUp : Sql > Create Materialized View Emp_Dept_Agg ENABLE QUERY REWRITE AS SELECT Deptno. Sum ( Sal ) From Emp Group By Deptno . ‘ESTIMATE‘ ) . Job. Sql > EXECUTE DBMS_MVIEW.

Grouping (Job ) GJOB . Job ) Having Grouping_ID ( Deptno. Job . Sum ( Sal ) From Emp Group Deptno .  The GROUPING bit vector is computed by combining the results of a call to the GROUPING( ) function for each column in order. Sql > Select Deptno . RollUp ( Deptno. if Deptno is NULL and Job is NULL. Sum ( Sal ) From Emp Group By Cube ( Deptno . else returns 0 … Based on this. Applying GROUP_ID Function :  The GROUP_ID ( ) Function is used to remove the deplicate rows returned by GROUP BY Clause. if Deptno is NOT NULL and Job is NULL. Grouping_ID ( Deptno. Job ) . COMPUTING THE GROUPING BIT VECTORS :  GROUPING ( ) Function returns 1 when the column value is NULL. Job ) > 0 . Sum ( Sal ) From Emp Group By Cube ( Deptno . Representing Column Multiple Times in a Group By Clause :  A Column can be represented multiple times in a Group By Clause . Job Grouping_ID ( Deptno.  GROUPING_ID ( ) returns 0 . Sql > Select Deptno . Job ) GRPID. Job Grouping(Deptno) GDPT. 115 Oragle 10 g Material .  GROUPING_ID ( ) returns 2 . Job ) GRPID. when Deptno and Job are NOT NULL’s  GROUPING_ID ( ) returns 1 . Job ) .Naresh i Technologies GROUPING_ID ( ) FUNCTION :  The function is used to FILTER ROWS using a HAVING Clause to exclude rows that do not contain a subtotal n total .  The Function accepts one or more columns and returns the decimal equivalent of the GROUPING bit vertor. GROUPING_ID ( ) and HAVING Clause : Sql > Select Deptno. if Deptno is NULL and Job is NOT NULL  GROUPING_ID ( ) returns 3 .

Job ) Having GROUP_ID ( ) = 0 . Job. ANALYTIC FUNCTIONS :  The Built in Analytic Functions enable to perform complex calculations. o Reporting Functions : • Enable to Calcuate area like market Shares. Percentiles and n-tiles . Job.Naresh i Technologies  The GROUP_ID ( ) does not accept any parameters. GROUP_ID ( ) . o Window Functions : • Enable to calculate cumulative and Moving Aggregates. GROUP_ID ( ) returns numbers in the range 0 to n – 1. RollUp ( Deptno. Job ) . Sum ( Sal ) From Emp Group By Deptno. o Linear Regression Functions : • Enable to fit an ordinary – least – squares regression line to a set of number pairs. RollUp ( Deptno. GROUP_ID( ) . o Hypothetical Rank and Distribution Functions : • Enable to calculate the rank and percentile that a new row would have if a value is inserted into a table. o LAG and LEAD Functions : • Enable to get a value in a row where that row is a cetain number of rows away from the current row. o First and Last Functions : • Enable to get the first and last values in an ordered group.  If ‘ n ‘ duplicate exist for a particular grouping. Inverser Percentile Functions : • Enable to calculate the value corresponding to a Percentile. Sum ( Sal ) From Emp Group By Deptno. TEST TABLES : 116 Oragle 10 g Material .  Analytic Functions Categories : o Ranking Functions : • o They Enable to calculate Ranks. Sql > Select Deptno. Sql > Select Deptno.

Sql > Create Table ItemTypes ( ItemTypeID INTEGER Constraint ItemTypePK PRIMARY KEY. Sql > Create Table Jobs ( JobID Char ( 3 ) Constraint JobIDPK PRIMARY KEY. DIVISIONS TABLE :  Used to store different divisions existing. JobName Varchar2 ( 20 ) Constraint JobNameNN NOT NULL 117 Oragle 10 g Material . Sql > Create Table Division ( Divid Char ( 3 ) Constraint DividPK PRIMARY KEY. Description Varchar2( 100 ) .Naresh i Technologies ITEM TYPES TABLE :  Used to store the names of the Item Types that are stocked by the store. ITEMS TABLE :  Used to store detailed information about the Items to be sold. DivName Varchar2 ( 15 ) NOT NULL ) . Sql > Create Table Item ( ItemID INTEGER Constraint ItemIDPK PRIMARY KEY. ItemTypeID INTEGER Constraint ItemTypeFK References ItemTypes ( ItemTypeID ) . ItemTName Varchar2 ( 10 ) Constraint ItemTName NOT NULL ) . ItemName Varchar2 ( 10 ) Constraint ItemNameNN NOT NULL . JOBS TABLE :  Used to store different Job Catogories Existing in the Organization. 2 ) ) . Price Number ( 5.

RANKING FUNCTIONS :  The Different types of Ranking Functins are 1 ) RANK ( ) Function : * * It returns the rank of items in a group. Constraint AllSalesPK PRIMARY KEY ( Year. RANK ( ) leaves a gap in the sequence of rankings in the event of a tie.Naresh i Technologies ) . SalAmt Number ( 8. ALL SALES TABLE :  Used to store the sum of all sales by specified amount. ItemTypeID. MONTH. JobID Char ( 3 ) Constraint JobIDFK References Jobs( JobID ) . EmpID ) ) . ITEM TYPE and EMOLOYEE. FirstName Varchar2 ( 10 ) Constraint FnameNN NOT NULL . Sql > Create Table EmpStores ( EmpID INTEGER Constraint EmpStoresPK PRIMARY KEY . Divid Char ( 3 ) Constraint DivIDFK References Division ( Divid ) ) . ItemTypeId INTEGER References ItemTypes ( ItemTypeID ) . EMPLOYEES TABLE :  Used to store the details of the Employees working in the stores. 2 ) DENSE_RANK ( ) Function : 118 Oragle 10 g Material . 2 ) . Month. LastName Varchar2 ( 20 ) Constraint LnameNN NOT NULL . Sql > Create Table AllSales ( Year INTEGER Constraint YearNN NOT NULL . EmpID INTEGER Constraint EmpIDAs References EmpStores ( EmpID ) . 0 ) . Month INTEGER Constraint MonthNN NOT NULL . for a particular YEAR. Sal Number ( 6.

EmpID) ORDER BY ItemTypeID . DENSE_RANK ( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) DENSE_RANK FROM AllSales Where Year = 2003 AND SaleAmt IS NOT NULL Group By ItemTypeID ORDER BY ItemTypeID . Month. APPLYING ROLLUP. Month ORDER BY ItemTypeID. RANK ( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) RANK From AllSales Where Year = 2003 GROUP BY GROUPING SETS (ItemTypeID. Sql Select ItemTypeID. RANK ( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) RANK . RANK ( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) RANK . EmpID.Naresh i Technologies * * It returns the rank of items in a group. Sum ( SaleAmt ) . EmpID . Month . Sum ( SaleAmt ) . EmpID . CUBE AND GROUPING SETS : Sql > Select ItemTypeID. Sum ( SaleAmt ) . PARTITION BY CLAUSE :  The Clause is used to divide groups into subgroups. RANK ( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) RANK From AllSales Where Year = 2003 GROUP BY RollUP(ItemTypeID) ORDER BY ItemTypeID . Sql > Select ItemTypeID. Sum ( SaleAmt) . EmpID) ORDER BY ItemTypeID . EmpID. DENSE_RANK ( ) doesn’t leave a gap in the sequence of rankings in the vent of tie. RANK ( ) OVER ( PARTITION BY Month ORDER BY Sum ( SaleAmt ) DESC ) RANK From AllSales Where Year = 2003 AND SaleAmt IS NOT NULL GROUP BY ItemTypeID. DENSE_RANK( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) 119 Oragle 10 g Material . RANK ( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) RANK From AllSales Where Year = 2003 GROUP BY CUBE(ItemTypeID. Sql > Select ItemTypeID. Sql > Select ItemTypeID. Sum ( SaleAmt ) . Sql > Select ItemTypeID. Sum ( SaleAmt ) .

CUME _ DIST ( ) Function :  It returns the position of a specified value relative to a group of values. NULLS FIRST AND NULLS LAST CLAUSE : Sql > Select ItemTypeID. Sum ( SaleAmt ) . ROW_NUMBER ( ) Function :  The Function is used to return a number with each row in a group. Sum ( SaleAmt ) . 120 Oragle 10 g Material . Sum ( SaleAmt ) .Naresh i Technologies DENSE_RANK From AllSales Where Year = 2003 GROUP BY ItemTypeID ORDER BY ItemTypeID . Sql > Select ItemTypeID. PERCENT_RANK( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) Percent From AllSales Where Year = 2003 GROUP BY ItemTypeID ORDER BY ItemTypeID . NTILE ( 4 ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) AS Ntile From AllSales Where Year = 2003 AND SaleAmt IS NOT NULL GROUP BY ItemTypeID ORDER BY ItemTypeID . Sql > Select ItemTypeID. NTILE ( ) Function :  The NTILE ( Buckets ) is used to calculate n – tiles. PERCENT_RANK ( ) Function :  It returns the Percent Rank of a Value relative to a group by Values.  The row number starts at 1.  The function represents the Cumulative distribution of the data. DENSE_RANK( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC NULLS LAST ) DENSE_RANK From AllSales Where Year = 2003 GROUP BY ItemTypeID ORDER BY ItemTypeID .  Bucket specifies the number of buckets into which groups of rows are placed. CUME_DIST( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) Cumulative . RANK ( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC NULL LAST ) RANK .

Sum ( Sum ( SaleAmt ) ) OVER ( ORDER BY Month ROWS BETWEEN UNBOUNDED PERCEDING AND CURRENT ROW ) 121 Oragle 10 g Material .6 ) WITHIN GROUP ( ORDER BY Sum ( SaleAmt ) DESC Percentile_Dist From AllSales Where Year = 2003 GROUP BY ItemTypeID . Sum ( SaleAmt ) . ROW_NUMBER( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) Row_Number From AllSales Where Year = 2003 GROUP BY ItemTypeID ORDER BY ItemTypeID . Sql > Select PERCENTILE_CONT ( 0. Sum ( SaleAmt ) MonthlyAmt . WINDOW FUNCTIONS :  The WINDOW Functions are used to calculate Cumulative Sums and moving averages within a specified range of rows. PERCENTILE_DIST ( 0.Naresh i Technologies Sql > Select ItemTypeID. INVERSE PERCENTAGE Function :  These functions are used to get the value corresponding to a percentile. PERCENTILE_CONT( ) :  It examines the percent rank values in each group until it finds one that is greater than or Equal to x.6 ) WITHIN GROUP ( ORDER BY Sum ( SaleAmt ) DESC Percentile_Cont .  The types of INVERSE percentile functions are o PERCENTILE_DIST( ) :  o It examines the cumulative distribution values in each group until it finds one that is greater than or equal to x.  The functions athat can be applied with windows are SUM ( ) COUNT ( ) AVG ( ) MAX ( ) MIN ( ) VARIANCE ( ) STDDEV ( ) LAST_VALUE ( ) FIRST_VALUE ( ) CALCULATING CUMULATIVE SUM : Sql > Select Month.

CALCULATING CENTERED AVERAGE : Sql > Select Month. Avg ( Sum ( SaleAmt ) ) OVER ( ORDER BY Month Rows BETWEEN 1 PRECEDING AND 1 FOLLOWING ) MovAvg From AllSales Where Year = 2003 GROUP BY Month ORDER BY Month . Sum ( SaleAmt ) MonthlyAmt .Naresh i Technologies CumulativeAmount From AllSales Where Year = 2003 Group By Month Order By Month . FIRST_VALUE ( Sum ( SaleAmt ) ) OVER 122 Oragle 10 g Material .  UnBounded Following : o Specifies that the window starts at the last row of the partition. Displaying First And Last Rows Using First_Value( ) and Last_Value ( ) : Sql > Select Month. Sum ( SaleAmt ) MonthlyAmt . Sum ( Sum ( SaleAmt ) ) OVER ( ORDER BY Month ROWS UNBOUNDED PERCEDING ) CumulativeAmount From AllSales Where Year = 2003 AND Month BETWEEN 6 AND 12 Group By Month Order By Month .  UnBounded Preceding : o Specifies that the window starts at the first row of the partition. Sql > Select Month. Sum ( SaleAmt ) MonthAmt. Avg ( Sum ( SaleAmt ) ) OVER ( ORDER BY Month ROWS BETWEEN 3 AND CURRENT ROW ) MovingAverage From AllSales Where Year = 2003 Group By Month Order By Month .  Current Row : o Specifies that the window begins at the Current Row or Value. Sum ( SaleAmt ) MonthAmt. CALCULATING MOVING AVERAGES : Sql > Select Month.

ItemTypeID ORDER BY Month. where that row is a certain number of rows away from the current row. Working With REPORTING Functions :  The Reporting function can be used to perform calculations across groups and partitions within groups. ItemTypeID ORDER BY Month. Sum ( Sum ( SaleAmt ) ) OVER ( PARTITION BY ItemTypeID ) Tot_Pesd_Type_Amt ) From AllSales Where Year = 2003 AND Month < = 3 GROUP BY Month.  The functions that can be used are …. SUM ( ) COUNT ( ) AVG ( ) VARIANCE ( ) MAX ( ) MIN ( ) STDDEV ( ) RATIO_TO_REPORT ( ) Sql > Select Month. ItemTypeID. LAG ( ) and LEAD Functions :  Are used to get a value in a row. Sum ( Sum ( SaleAmt ) ) OVER ( PARTITION BY Month ) Tot_Month_Amt .Naresh i Technologies ( ORDER BY Month Rows BETWEEN 1 PRECEDING AND 1 FOLLOWING ) PRRVMonthAmt . ItemTypeID . RATIO_TO_REPORT ( ) Function :  The function is used to compute the ratio of a value to the sum of a set of values. Sum ( SaleAmt ) ItemTypeAmt . ItemTypeID . 123 Oragle 10 g Material . Sql > Select Month. RATIO_TO_REPORT ( Sum ( SaleAmt ) ) OVER ( PARTITION BY Month ) ProTypeRatio From AllSales WHERE Year = 2003 AND Month < = 3 GROUP BY Month. ItemTypeID . LAST_VALUE ( Sum ( SaleAmt ) OVER ( ORDER BY Month Rows BETWEEN 1 PRECEDING AND 1 FOLLOWING ) NXTMonthAmt From AllSales Where Year = 2003 GROUP BY Month ORDER BY Month .

 It can be used to UPDATE the master table of Materialized View. Deptno ) = ( Select Job. Deptno From Emp Where Empno = 7499 ) 124 Oragle 10 g Material . PREREQUISITES :  The Table must be in the own Schema. Sum ( SaleAmt ) MonthAmt .  UPDATE object privilege should be available. the functions can be used in combination with all group functions. LEAD ( Sum ( SaleAmt ) . Sql > UPDATE Emp SET ( Job. 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. Sql > Select Min ( Month ) KEEP ( DENSE_RANK FIRST ORDER BY Sum ( SaleAmt ) ) LowestSaleMonth From AllSales Where Year = 2003 GROUP BY Month ORDER BY Month . Sql > Select Month . Examples : Sql > UPDATE EMP SET Comm = NULL WHERE Job = ‘CLERK’ .Naresh i Technologies FIRST and LAST Functions :  Are used to get the FIRST and LAST values in an ordered group. Avg ( Sum ( SaleAmt ) . Syntax : UPDATE < Table_Name > SET < Specification > WHERE Clause . 1 ) OVER ( ORDER BY Month ) NextMthAmt From AllSales WHERE Year = 2003 AND Month < = 3 GROUP BY Month ORDER BY Month . 1 ) OVER ( ORDER BY Month ) PrevMthAmt .

 DEFAULT key word is Introduced from Oracle 9i onwards. ( Sal. APPLYING DEFAULT VALUES :  It is used to UPDATE a value in a Column with DEFAULT value set in the Constraints. Sql > UPDATE Emp SET Hiredate = DEFAULT Where Ename = ‘TAYLOR’ .5 * Avg ( Comm ) From Emp E2 Where E1. Sal = 2500 . Sql > UPDATE Emp SET Sal = Sal * 1.Deptno ) Where Deptno IN ( Select Detpno From Dept Where Loc = ‘NEW YORK’ OR Loc = ‘BOSTON’ ) . Sql > UPDATE Emp SET Sal = DEFAULT Where Ename = ‘SMITH’ . Sql > UPDATE Emp SET Job = ‘MANAGER’ . Sal = Sal + 1000 Where Ename = ‘BLAKE’ .Deptno = E2.10 Where Deptno = ( Select Deptno From Dept Where Loc = ‘CHICAGO’ ) . Sql > UPDATE Emp E1 SET Deptno = ( Select Deptno From Dept Where Loc = ‘DALLAS’ ) . 1. RETURNING CLAUSE : 125 Oragle 10 g Material . Sql > UPDATE Employee SET Deptno = ( Select Deptno From Emp Where Empno = 7788 ) Where Job = ( Select Job From Emp Where Empno = 7788 . Deptno = 10 Where Ename = ‘ALLEN’ .1 * Avg ( Sal ) . Sql > UPDATE Emp SET Job = ‘ANALYST’ . Comm ) = ( Select 1.Naresh i Technologies Where Empno = 7698 .

Example : Sql > CREATE table Bonus ( Empno NUMBER . Example 1 : Sql > VARIABLE Sumsal Number Sql > UPDATE Emp Set Sal = Sal * 1.25 . UPDATE. It cannot be used to Retrieve LONG Types.  MERGE is a deterministic statement.  It is used to Return a value from a AGGREGATE Function.  The MERGE Statement is convenient to Combine multiple operations and avoid multiple INSERT. MERGE :  The MERGE Statement is used to SELECT rows from one or more sources for UPDATE or INSERT into one or more tables. It cannot be specified upon a VIEW upon which a INSTEAD OF Trigger is defined. Example 2 : Sql > VARIABLE Salary NUMBER . Ename INTO :Salary.1 Where Deptno = 10 RETURNING Sum ( Sal ) INTO :SumSal . :Name . It cannot be specified for multi table insert. :DeptNum . Deptno = 30 Where Ename = ‘JONES ‘ RETURNING Sal * 0. Sql > UPDATE Emp SET Job = ‘SALES MAN’ . using which the same row of the target table multiple times in the same MERGE statement. Sal = Sal + 1000 .Naresh i Technologies  The returning clause is introduced from 10g.  The Clause can be specified for tables and Materialized Views and for Views with a single base table. Deptno. Restrictions :      Each expression must be a simple expression or a single set Aggregate function. 126 Oragle 10 g Material . DELETE. Sql > VARIABLE DeptNum NUMBER . Sql > PRINT SumSal . It cannot be used with parallel DML or with Remote objects. Sql > VARIABLE Name VARCHAR2 ( 10 ) .

Naresh i Technologies Bonus NUMBER DEFAULT 100 ) ; Sql > INSERT INTO Bonus ( Empno ) ( SELECT E.Empno From Emp E Where Job = ‘SALES MAN’ ) ; Sql > MERGE INTO Bonus B USING ( SELECT Empno, Sal, Deptno From Emp Where Deptno = 30 ) S ON ( B.Empno = S.Empno ) WHEN MATCHED THEN UPDATE SET B.Bonus = B.Bonus + S.Sal * 0.1 DELETE WHERE ( S.Sal > 4000 ) WHEN NOT MATCHED THEN INSERT ( B.Empno, D.Bonus ) VALUES ( S.Empno, S.Sal * 0.1 ) WHERE ( S.Sal < = 4000 ) ;

Sql > CREATE Table ExamTimeTable
( ExamName VARCHAR2( 30 ) , ExamTime VARCHAR2 ( 6 ) , Constraint ExamNamePK PRIMARY KEY ( ExamName ) ) ;

Sql > INSER INTO ExamTimeTable
( ‘PHYSICAL SCIENCES‘ , ‘9:00 AM’ ) ; Sql > MERGE INTO ExamTimeTable E1 USING ExamTimeTable E2 ON ( E2.ExamName = E1.ExamName AND E1.ExamName = ‘PHYSICAL SCIENCES’ ) WHEN MATCHED THEN UPDATE SET E1.ExamTime = ’10:30 AM’ WHEN NOT MATCHED THEN INSERT ( E1.ExamName, E1.ExamTime ) VALUES ( ‘PHYSICAL SCIENCES’ , ’10:30 AM’ ) ; Sql > MERGE INTO ExamTimeTable E1 USING ExamTimeTable E2 ON ( E2.ExamName = E1.ExamName AND E1.ExamName = ‘CHEMICAL SCIENCES’ ) WHEN MATCHED THEN UPDATE SET E1.ExamTime = ’12:30 PM’ WHEN NOT MATCHED THEN INSERT ( E1.ExamName, E1.ExamTime ) VALUES ( ‘CHEMICAL SCIENCES’ , ’12:30 PM’ ) ; DELETE STATEMENT :  It is used to remove rows from o o o An 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.

127

Oragle 10 g Material

Naresh i Technologies

Prerequisites :  To DELETE rows from a table, the table must be in the users shema.  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 table partition or form the Base Table of any View. Syntax : DELETE [ FROM ] < Table_Name > [ WHERE Condition ] ; Example : Sql > DELETE From Emp Where Ename = ‘SMITH’ ; Sql > DELETE From Emp Where Hiredate > To_Date ( ‘01-01-1997’ , ‘DD-MM-YYYY’ ) ; Sql > DELETE From SalGrade ; Sql > DELETE From Emp Where Deptno = ( Select Deptno From Dept Where Dname = ‘SALES’ ) ; Sql > DELETE From ( Select * From Emp ) Where Job = ‘SALESMAN’ AND Comm < 300 ; USING RETURNING CLAUSE : Sql > VARIABLE Salary NUMBER ; Sql > DELETE From Emp Where Job = ‘SALESMAN’ AND Hiredate < Sysdate RETURNING Sal INTO :Salary ; Sql > PRINT :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. TRANSACTION START and END Cases :  A Transaction begins when the first executable SQL statement is encountered.  The Transaction terminates when the following specifications OCCUR. o o o A COMMIT or ROLLBACK is issued. A DDL Statement issued. A DML Statement issued.

128

Oragle 10 g Material

Naresh i Technologies o o 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 o COMMIT :  o It ends the current transaction by making all pending data changes permanent.

SAVEPOINT Name :  It marks a SavePoint within the Current Transaction.

o

ROLLBACK [ TO SAVEPOINT NAME ] :  It ends the Current Transaction by discarding all pending data changes.

STATE OF DATA BEFORE COMMIT OR ROLLBACK : Every data change made during the transaction is temporary until the transaction is committed. Data Manipulation operations primarily affect state of the data 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 last COMMIT.     STATE OF THE DATA AFTER COMMIT IS ISSUED :      Data changes are written to the database The previous state of the data is permanently lost All users can view the results of the transaction. The LOCKS on the affected rows are released All SAVEPOINTS are erased. Sql > COMMIT ; ALTERTING THE TABLE DEFINITION :  The ALTER TABLE statement is used to change the Tables Structural Definition.  The ALTER TABLE statement is used to o o o Syntax : ADD a new Column MODIFY an Existing Column DEFINE a DEFAULT value for a new Column.

129

Oragle 10 g Material

 If a second SAVEPOINT is created with the same name as an earlier SAVEPOINT. Sql > ALTER TABLE Dept30 ADD ( Job VARCHAR2 ( 9 ) ) . The Date changes are undone. Guidelines to MODIFY a Column :  We can Increase the width or precision of a Numeric Column 130 Oragle 10 g Material . Guidelines for ADDING Column :  A column can be ADDED or MODIFIED but cannot be dropped from a table. before the column is added.  A change to the Default value affects only subsequent insertions to the table. STATE OF THE DATA AFTER ROLLBACK :     ROLLBACK Statement is used to discard all pending changes. ALTER TABLE < TableName > MODIFY ( ColumnName Datatype [ DEFAULT Expr ] [ . size and Default value can be changed. it by default becomes the last column. ROLLING BACK CHANGES TO A SAVEPOINT :  SAVEPOINT is used to create a marker in the Current transaction.Naresh i Technologies ALTER TABLE < Table_name > ADD ( ColumnName DataType [ DEFAULT Expr ] [ . the new column contains NULL’s.  Using SAVEPOINT the transaction can be discarded up to the marker by using the o ROLLBACK TO < SAVEPOINT Name > . ColumnName DataType ] … ) . the Earlier SAVEPOINT is Deleted. ADDING A COLUMN TO A TABLE :  The ADD Clause is used to add Columns. The previous state of the data is returned The LOCKS on the affected rows are released.  If the table contains records. MODIFYING A COLUMN :  A column Datatype.  We cannot specify the location where the column can appear. Sql > ROLLBACK . Column Datatype ] … ) .

 After a column has been marked unused. SET UNUSED OPTION :  The SET UNUSED OPTION marks one or more columns as Unused such that they can be dropped when the damage on system Resources is less ( 8 i ) . 131 Oragle 10 g Material . we cannot have access to that column.  The option is used when we want to reclaim the extra disk space from unused columns in the table. DROPPING A COLUMN :  A column can be dropped from a table by using the ALTER TABLE statement. DROPPING A TABLE :  It removes the definition of the Oracle Table.  Unused columns are treated as if the were dropped.Naresh i Technologies  We can Decrease the width of a column if the column contains only NULL values and if the table has no rows. Sql > ALTER TABLE Dept30 DROP UNUSED COLUMNS .  The DROP Column Clause is used for this purpose and the feature is enabled from Oralce 8i Onwards. Sql > ALTER TABLE Dept30 SET UNUSED ( Ename ) . Once a column is dropped it cannot be recovered.  The Response time is faster than the DROP Clause.  A change to the default value of a column affects only subsequent insertions to the table. DROP UNUSED COLUMNS OPTION :  This option removes from the table all columns currently marked as unused.  We can add to a table a New Column with the same name as an unused column. Sql > ALTER TABLE Dept30 DROP Column Job . The table must have atleast one column remaining in it after it is altered. even trough their column data remains in the tables rows.  If the table does not contain unused columns the statement returns with no errors.  We can change the datatype if the column contains NULL’s  We can convert a CHAR column to the VARCHAR2 datatype or convert a VARCHAR2 column to the CHAR datatype if the column contains NULL values or if the Size is not changes. Guidelines to DROP a Column :     The column may or may not contain data Only one column can be dropped at a time.  The names and types of columns marked unused will not be displayed during a DESCRIBE.

Only the create of the table is a user with DROP any table privilege can remove a table The drop table statement once executed is irreversible . Sq l> TRUNCATE Table Department . • we must be the owner of the table for truncating APPLYING COMMENTS UPON A TABLE : • • • The comments command is used to add comments to a table or a column or view etc. Syntax : DROP TABLE < Table_Name > . TRUNCATING A TABLE : • • It is used it remove all rows from a table and to release the storage space used by the specific table. Example : DROP TABLE Dept30 . The truncate table will not facilitate for rollback Syntax : TRUNCATE TABLE < Table Name > . Sql > Rename Dept TO Department. GUIDELINES TO DROP TABLE : • • • • • The data is totally deleted from the table Any views and synonyms will remain that are invalid Any pending transactions are committed. 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 : RENAME < old name > TO < new name > .Naresh i Technologies  The Command not only drops the table but the entire Database is lost along with the associated Indexes. Each comment can be upto 2000 bytes The data dictionary is which comments are stored are… 132 Oragle 10 g Material ..

Sql > Create Table Sampdept1(Deptid . ADVANCED TABLE CREATION STRATEGIES : Creating a table from an existing table • Oracle allows the creation of a new table on_the_fly.Naresh i Technologies • • • • ALL_COL_COMMENTS USER_COL_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS COMMENT ON Table < Table Name > / column < Tablename. 133 Oragle 10 g Material . When the new table is described it reveals that it has “INHERITED” the column definition from the existing table. Syntax: DROPING A COMMENT : • A comment is dropped from the database by setting it to an empty string. Sql > COMMENT ON Table Emp is ‘ the table storing employee information ’ . Column > is ‘ Text ’ . Creating a table with column definitions and without data : Sql > Create Table Sampdept3 As Select * From Dept Where 1 = 2 . Sql > COMMENT ON Table Emp is ‘ ‘ . Deptname . Syntax : Create Table < Table Name > As Select columns From Table_Name . Sql > Create Table Sampdept as Select * from dept. Sql > Create Table Sampdept2 as Select Deptno .Dname From Dept. [ Where Condition ] . depending on a select statement on an already existing 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 is the invented columns. Using this style we can include all columns using Asterisk is a subset of columns from table. • • • • • The create table …As select…command will not work if one of the selected columns use long data type. Place) As Select * From Dept.

The table that is partitioned is called partitioned table and the parts are called partitions The partitioning is useful for very large tables The Important Goals Behind Partitioning Are… • • • • The performance of queries against the tables can improve performance The management of the table becomes easier As the partitioned table date is stored in multiple parts . Sampname Varchar2(20). Sampname ) )organization index . • • • To create a table as an index organized table we must create a primary key constraint on it To minimize the amount of active management of the index table only of the table’s data is very static An index organized table is most effective when the primary key constitutes a large part of the tables columns Working With Partitioned Tables : • • • Dividing the rows of a single table into multiple parts is called partitioning of a table. Constraint SampidSampnamePK Primary Key(Sampid. Sampdesc LONG ) . Sampdate DATE. Creating Index-Organized Table : • • • An index organized table keeps its data stored according to the primary hey column values for 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 Sql >Create Table Sample (Sampid Number(4). Sampname Varchar2(20).the table will not be re-create following a database failure The redo log files are used to recover the database • • • • Sql> Create Table SampDept NOLOGGING As Select * From Dept . 134 Oragle 10 g Material . Sampdate DATE.Naresh i Technologies 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 generating can be avoided by using the NOLOGGING keyword By circumventing the performance of 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 . it is easier to load and delete data in partitions than in the large table The backup and recovery operating can perform better Sql >Create Table Sampletable(Sampleid Number(4) Primary Key .

2) . 135 Oragle 10 g Material . Sal Number(8.. PARTITION Sampidpart2 VALUES LESS THAN(1000) . Sql > Create Table Emptablehash ( Empno Number(6) Constraint Empnopk Primary key. Sampdate Date . The maxvalue specifies oracle to use the partition to store any data that could not be stored In the easier partitions We can create multiple partitions each with its qwn upper value defined The minimum 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. PARTITION Sampidpart3 VALUES LESS THAN ( Maxvalue ) ) .) PARTITION BY HASH(Deptno) PARTITION 2 STRORE IN (Deptnopart1ts . Deptnopart2ts ) . Deptno Number(2) . Job Vachar2(30) . Sampdesc Varchar2( 4000 ) ) PARTITION By RANGE( Sampid ) (PARTITION Sampidpart1 VALUES LESS THAN(5000) . Sampname Varchar2(20) . Constraint Deptnofk_Hash Foreign Key( Deptno ) References Dept( deptno ) ) PARTITION BY HASH( Deptno ) PARTITIONS 10. Ename Varchar2(30) . decreasing the likelihood for i/o contention To create a hash partition we use the partition by hash clause Format choice Specify the number of partitions and the table space to use specify the named partitions Sq l> Create Table Emptablehash(Empno Number(6) Constraint Empnopk Primary Key. the maxvalue keyword is specified. • • • • The maximum value need not be specified fr the last partition.Naresh i Technologies Create Partition Table : Sql > Create Table Sampletablepart(Sampid Number(4) Primary Key .……………….

SPLITTING TABLE PARTITIONS : Sql>Alter Table Sampletablepart SPLIT PARTITION Sampidpart3 AT (2000) INTO (PARTITION Sampidpart3 . 136 Oragle 10 g Material .’ANALIST’) . PARTITION SAMPIDPART4 ) . Constraint Deptnofk Foreign Key ( Deptno ) References Dept( Deptno ) ) PARTITION Jpart1 VALUES (‘PRESIDENT’. PARTITION Ssalesman ) . PARTITION Jpart2 Values(‘MANAGER’. Job Varchar2(15) . Constraint Deptnofk Foreign Key( Deptno ) References Dept( Deptno ) ) PARTITION BY RANGE (Ename) SUBPARTITION BY HASH(Job) SUBPARTITIONS 5 (PARTITION Namep1 VALUES LESS THAN(’M’) PARTITION Namep2 VALUES LESS THAN ( Maxvalue ) . Sq l> Alter Table Empsamplelist SPLIT PARTITION Jpart2 Values(‘SALESMAN’) / INTO(PARTITION Jsalesman. the Composite Partition strategy is an effective way of separating the data into manageable and tunable divisions Sql > Create Table Empsamplesubpart ( Empno Number(6) Primary Key .2) . RANGE PARTITIONS 2.Naresh i Technologies WORKING WITH LIST PARTITIONING : • In list partitioning we specify oracle all the possible values and designated the partition into which the corresponding rows should be inserted Sql>Create Table Empsamplelist (Emp Number(4) Constraint Empnopk Primary Key.’CLECK’) ) . HASH PARTITIONS In very large tables.3) . Ename Varchar2(30) . Job Varchar2(30) . Generating sub partitions : • • • sub partitions are partitions of partition sub partitions can be used to combine the two types of partitions 1. Merging table PARTITIONS : Sql > Alter Table Empsamplelist MERGE PARTITIONS Jpart1. Ename Varchar2(20) . Hiredate Date . Sal number(8. Deptno Number(2) . Deptno Number(2) .’SALESMAN’. Sal Number(8.

2) ) .Jpart2) . Sql > Alter Table Sampletablepart MERGE PARTITIONS Sampidpart2 . Creating Indexes upon PARTITIONS : • • • Once a partitioned table is created . The rows of an object table can be referenced by other objects with in the database An object table is created using the create table command CREATING AN OBJECT : Syntax : CREATE OR REPLACE TYPE <TYPE NAME> AS OBJECT ( Column Name1 Data Type(Size). Doa Date . Samplepart3 INTO PARTITION Sampidpart3 . Dropping a table PARTITION : Sql > Alter Table Sampletablepart DROP PARTITION Sampleidpart3 . CREATING AN OBJECT TABLE : 137 Oragle 10 g Material .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 palced into specific table spaces Sql > Create Index Empsamplelistinx ON Empsamplelist ( Job ) LOCAL ( PARTITION Jpart1. Sql > Alter Table Empsamplelist DROP PARTITION Jpart1 . Dob Date . Fees Number(7. • • • • The local keyword tells oracle to create a separate index for each partition on the table The global keyword tells oracle to create a nonpartitioned index Local indexes are easier to manage than global indexes Global indexes can perform uniqueness checks faster than local indexes OBJECT TABLES : • • • • • IN an OBJECT TABLE each row is treated as an OBJECT Each row in an object table has an OID The OID is assigned by oracle when the row is created. Sql > CREATE OR REPLACE TYPE Student AN OBJECT( Studid Number(6) .…………………………………Column Name n Data Type( Size ) ) .Naresh i Technologies Jsalesman INTO PARTITION Jpart1 . Sname Varchar2(20).

UPDATING DATA FROM OBJECT TABLES : Sql > Update Mcastudent Set Studname = ‘Sriram’ Where Studid = 1234 . Sq l> Delete From Mcastudent .1300 ) ) .Naresh i Technologies Syntax : Create Table Table_Name of typename . THE REF FUNCTION : • The ref function allows to reference existing row objects 138 Oragle 10 g Material . Studname ) Values ( 1234. INSERTING RECORDS THROUGH COLUMN REFERENCES : Sql > Insert Into Mcastudents ( Studid. ’Krishna’ ) . SELECTING DATA FROM OBJECT TABLES : • the abstract data types column can be referred as a part of the table’s columns Sql > Select * From Mcastudent .’05-Sep-99’.Sysdate. Sql > Select Studid . INSERT USING WITHOUR CONSTRUCTOR METHOD : Sql > Insert Into Mcastudent Values(1234. Studname From Mcastudent Where Studid=1234 .’Kumar’. Studname From Mcastudent .Sysdate. • • • The above statement creates the tale mcastudent as an abstract data type Each row in the object table has an OID value The rows in 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 datatype or directly implement the insert ststement The normal insert or REGATIONAL INSERT is possible only when the table doesnot contain any nested datatypes INSERT UNSING CONSTRUCTOR METHOD : Sql > Insert Into Mcastudent Values ( Student 91234.15000 ) . Sql > Create Table Mcastudent Of Student . DELETING DATA FROM OBJECT TABLES : Sql > Delete From Mcastudent Where Studid = 1234 .’07-Oct-98’.’Satish’. Sql > Select Studid .

As mcastudent is an object table of the student data types the studentIncharge column can point to the row object within the mcastudent object table The studentIncharge table can be described as an ordinary table . • IN THE ABOVE CASE : 1. collections • The REF function by itself does not give any useful information DEREF FUNCTION : • The DEREF function takes a reference value i. Abstract data types 2. • • • • The StudentIncharge column references the data that is stored elsewhere The REF function points the StundentInchage column to a row object of the student data type. LOB’s 3.e. Sql > DESC StudentIncharge . INSERTING RECORDS INTO REFERENCE TABLES : • To insert records into reference tables we have to use the REF function Sql > INSERT INTO StudentIncharges SELECT ‘SUBRAMANYAM SHRMA’ REF(A) From Mcastudents A where Name=’SATISH KUMAR’ . • • • • The REF(A) value will be different under different system and may be wrapped onto multiple lines The REF function takes as its input the alias given to the object table The REF functions takes can only reference row objects . the OID generated for a reference and return the value of the row object Sql > Create Table Studentincharges ( Inchargename Varchar2(30). • Seeing full details of the reference Sql > SET DESCRIBE DEPTH 2 . Studentincharcge REF Student ) .Naresh i Technologies • The OID assigned to each row can be seen by using the REF function Sql > SELECT REF(A) from Mcastudent A Where Studname = ’SATISH’ . Sql > DESC StudentIncharge . The mcastudents table is queried first 139 Oragle 10 g Material .hence we cannot use REF for referencing column objects The column objects can be of 1.

The REFERENCE OID can be seem by querying upon the studentIncharge table Sql > SELECT * FROM studentIncharge . THE selected OID is stored in the studentIncharge table as a pointer to thet row object in the mcastudents object table 4. The studentIncharges actually contains the name of the studentIncharge and a reference to a row object in the mcastudents table 5. The REF function return the OID for the row object selected 3. • The reference value cannot be seem until we use the DEREF function Sql > SELECT DEREF(X>StudentIncharge) FROM studentIncharge X WHERE InchargeName= ’SUBRAMANYAM SHARMA’ . • The parameter for the DEREF function is the column Name of the REF column but not the table Name. 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 INVALID REFERENCES : • • We can DELETE the object to which a REFERENCE points We can D:ETE a row from mcastudents object table to which studentIncharge record ponts Sql > DELETE FROM Mcastudents WHERE name=’satish kumar’ . • • 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 object table when the row object is DELETED the OID is lost and the oracle doesn’t reuse the OID numbers • Hence if a new record for ‘SATISH KUMAR’ is inserted this is given a ane OID value .but the studentIncharge record still points to the old value 140 Oragle 10 g Material . POINTS TO NOTE : • • • • • The query uses a reference to a row object to travel from one table to the second A join is performing in the background without specifying the join criteria The object table it self 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 : Sq l> SELECT VALUE (A) FROM Mcastudents A WHERE SNAM = ’SATISH’ .Naresh i Technologies 2.

Pincode ) ) FROM students . • • • As student table was created without using the Myaddress and Mystudent data types it has to be accessed via OBJECT VIEWS. Statename. Cityname Varchar2(25) .Studdef ) As Select Studid . 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 Studentov (Studid . Street Varchar2(40) . CREATING ABSTRACT DATA TYPES : Sql > Create Or Raplace Type Myaddress As Object ( Street Varchar2(40) . Pincode number(6) ) . Cityname Varchar2(25) . Pincode Number(6) ) .hence the fact that two objects having the same data does not mean they are same OBJECT VIEWSWITH REFS : • • • OBJECT views are very important to super impose oops structures on an exiting relations table We can create abstract data types and use them within the object view of an existing table OBJECT view acts as a bridge between the existing relational application to object relational applications CREATING USER DEFINED DATA TYPES AND INTEGRATING THEM TO RELATIONAL TABLES : RELATIONAL STAGE : Sql > Create Table Students( Studid Number(6) Constraint Studidpk Primary Key . • we can access the students table directly as a relational table or via the CONSTRUCTOR methods for the abstract data types OBJECT VIEWS WITH REFERENCES : 141 Oragle 10 g Material . Sname Varchar2(30) . Sql > Create Or Replace Type Mystudent As Object(Sanme Varchar2(30) Saddress Myaddress ) . Statename Varchar2(40) . Statename Varchar2(40) . Mystudent (Sname . Myaddress (Street . Cityname .Naresh i Technologies • • In a relational system the join between two tables in dependent only on the current data In an OOP system the join is between objects .

’THERMO DYNAMICS’.then .’SATISH KUMAR’. Sql > Select * From Tab .Naresh i Technologies • • • • If the students table is related to another table . Sname VARCHAR2(30) . Studid) . • As the next step create a view based upon the studenttype by assigning OID values to the records in stundent table CREATE A REFERENCE TABLE FOR STUDENTS : Sql > Create Table StudentBooks( Libtranno Number(6). By Implementing the above concept we can access the table either as RELATIONAL TABLE OR AS OBJECTS When the table are treated as objects we can use the REF’s to automatically performs joins upon the tables using the DEREF function GENERATING OID’S : • • • We Can Use An Object view to assign OID’s to the records in students table. Pincode Number( 6 ) ) . SYSDATE ) . ’HYDERABAD’. Constraint LibtreamNoPK Primary Key (LibTeamNO. Cityname Varchar2(25). Sql > INSERT INTO StudentBooks VALUES (1000. Lendingdate Date . OID’s are assigned to records inan OBJECT TABLE and an OBJECT TABLE in turn is based on an ABSTRACT DATATYPES As first step create an ABSTRACT DATA TYPE that has the same structure as the student Sql > Create Or Replace Type Student Type As Object ( Studid Number(6) . Tname TabType Clustered ------------------------------------------------------------------------------ADMIN ADMINTABLE ARTIST IMAGETABLE THEME UPLOAD UPLOADS USERS Sql > Desc Admin . Booktittle Varchar2(50) . Studid Number(6). 506001 ) . 2000. TABLE TABLE TABLE TABLE TABLE TABLE TABLE TABLE 142 Oragle 10 g Material .object views can be create as a references between the table By using the above concept ORACLE uses the existing Primary KEY|Foreign Key relationships to simulated OID’s for use by REF’s between the table. ’ANDHRA PRADESH’ .Street Varchar2(40) . Sql > INSERT INTO Students VALUES ( 1000. Statename Varchar2(40) . ’SHIV BAGH’ . Constraint StudentBooksFK Foreign Key (Studid) References Students(Studid ) ) .

143 Oragle 10 g Material .Naresh i Technologies Name Null? Type -------------------------------------------------------------------------------------ADMIN PASSWORD Sql > Desc Artist . Name Null? Type -----------------------------------------------------------------------------------------THEMEID THEMENAME CATEGORY THEMENOTE Sql > Desc Upload . Name Null? Type ----------------------------------------------------------------------------------------ARTISTID ARTISTNAME PASSWORD INTAREA EXPERIENCE CLASSNAME HISTORY CONTENT Sql > Desc Theme . Name Null? Type -----------------------------------------------------------------------------------------IMAGEID FILENAME ARTISTID IMAGENAME LOCATION NUMBER(5) VARCHAR2( 30 ) VARCHAR2( 20 ) VARCHAR2( 20 ) NUMBER( 3 ) NUMBER(5) VARCHAR2(15) VARCHAR2(10) VARCHAR2(255) VARCHAR2(20) VARCHAR2(25) VARCHAR2(12) VARCHAR2(15) VARCHAR2(2) VARCHAR2(12) VARCHAR2(255) VARCHAR2(255) VARCHAR2(20) VARCHAR2(30) Sql > Desc Users .

Pincode From Student .StudID column to the STUDENT>StudID column From the studentov OBJECT View that has been created.Naresh i Technologies Name Null? Type -----------------------------------------------------------------------------------------USERNAME PASSWORD NAME PHONE EMAIL OCCUPATION ADDR1 ADDR2 ADDR3 ADDR4 Sql > Select * From Admintable . USERID PWD ------------------------------------------------------Kalyan Kalyan VARCHAR2( 20 ) VARCHAR2( 12 ) VARCHAR2( 25 ) NUMBER( 10 ) VARCHAR2( 25 ) VARCHAR2( 15 ) VARCHAR2( 20 ) VARCHAR2( 20 ) VARCHAR2( 20 ) VARCHAR2( 20 ) Sql > CREATEOR REPLACE VIEW STUDENTOV OF StudentType WITH OBJECT IDENTIFIER (StudID)AS SELECT StudID Sname. 144 Oragle 10 g Material . StudID ) studID. LendingDate From StudentBooks . • • • • • 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 With the above step the rows of students are now accessible as row OBJECTS via the studentOV View The PID values generated for the studentOV rows are called as PKOID’s as they are based upon students primary key values The relational tables can accessed as row OBJECTS if OBJECT Views are created upon them GENERATING REFERENCES : • • • • Actually the rows of studentBooks reference rows in students As per relational concept the relationship is determined by the foreign key pointing from the STUDENTBOOKS. Statename. BookTittle. LibTranNo. and the rows in students table can be accessed via OID’s we have to CREATE REFERENCE VALUES in studentBooks that reference students Once the Ref’s are create we can use DEREF function to Access the students data from student Books Sql > CREATE VIEW StudentBooksov As SELECT MAKE_REF( StudentOv . Cityname. Street.

STEPS PERFORMED : • • • • • • The Query finds the record in the StudentBooks table for which the LendingDate is the Current System Date . 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.DELETE UPDATE and SELECT statements They help in using OOP features such as REFERENCES against the Object TABLES They provide an Technological Bridge for migrating to an oops db architecture Oracle performs JOINS that resolve the references defined in the database When references\d data is retrieved it beings the entire row object that was referenced To reference the data we need to establish POID’s in the table that is ‘PRIMARI 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 it were stored in OBJECT TABLES. 145 Oragle 10 g Material . The StudentOV OBJECT View returned the record whose PKOID matched the REFERENCED value The DEREF function then gets activated returning the value of the referenced row The query return rows from students even through 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 table When OBJECT views are extended to row OBJECT they enable to generated OID values based on established FOREIGN KY| PRIMARY KEY relationship OBJECT Views allow us to continue to use the existing constraints and standard INSERT.StudID) FROM StudentBookOVSB Where BookTittle=’THERMO DYNAMICS’ .Naresh i Technologies MAKE_REF FUNCTION : • • • • It creates REFERENCES which are called PKREF’s from an existing view to another view PKREF’s are named so as they are based on PRIMARY KEYS The function takes as an arguments(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 creates 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 > SELCT DEREF(SB.