Oracle
Upcoming SlideShare
Loading in...5
×
 

Oracle

on

  • 1,043 views

 

Statistics

Views

Total Views
1,043
Views on SlideShare
1,043
Embed Views
0

Actions

Likes
0
Downloads
64
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Oracle Oracle Document Transcript

  • Published by CFS Documentation CellCentre for Electronics Design and Technology of IndiaAn Autonomous Scientific Society under Department of Electronics,Govt. of India,New Delhi.First Edition: 1999TRADEMARKS: All brand name and product names mentioned in this book are trademarks or registered trademark of theirrespective companies.Every effort has been made to supply complete and accurate information. However, CEDTI assumes no responsibility for itsuse, nor for any infringement of the intellectual property rights of third parties which would result from such use.No part of this publication may be stored in a retrieval system, transmitted or reproduced in any forms or by any means,electronic, photocopy, photograph, magnetic or otherwise, without written permission of CEDTI.CEDTI/CFS/99/6/3.2/R1
  • FOREWORD The information technology and telecom sectors have suddenly opened up avenues,which require a very large specially trained manpower. These sectors are highly dynamic andneed training and re-training of manpower at a rapid rate. The growing gap of requirement ofthe industry and its fulfillment has created a challenging situation before manpower traininginstitutes of the country. To meet this challenge most effectively, Centre for Electronics Designand Technology of India (CEDTI) has launched its nation-wide franchising scheme. Centre for Electronics Design and Technology of India (CEDTI) is an AutonomousScientific Society under the Govt. of India, Department of Electronics with its Headquarters atNew Delhi. It operates seven centres located at Aurangabad, Calicut, Gorakhpur, Imphal,Mohali, Jammu and Tezpur. The scheme will be implemented and coordinated by these centres. The scheme endeavours to promote high quality computer and information technologyeducation in the country at an affordable cost while ensuring uniform standards in order tobuild a national resource of trained manpower. Low course fees will make this educationavailable to people in relatively small, semi urban and rural areas. State-of-the-art training willbe provided keeping in view the existing and emerging needs of the industrial and Govt.sectors. The examinations will be conducted by CEDTI and certificates will also be awardedby CEDTI. The scheme will be operated through all the seven centres of CEDTI. The CEDTI functions under the overall control and guidance of the Governing Councilwith Secretary, Department of Electronics as its Chairman. The members of the council aredrawn from scientific, government and industrial sectors. The Centres have separate executivecommittees headed by Director General, CEDTI. The members of these committees are fromacademic/professional institutes, state governments, industry and department of electronics. CEDTI is a quality conscious organisation and has taken steps to formally get recognitionof the quality and standards in various activities. CEDTI, Mohali was granted the prestigiousISO 9002 certificate in 1997. The other centres have taken steps to obtain the certification asearly as possible. This quality consciousness will assist CEDTI in globalizing some of itsactivities. In keeping with its philosophy of ‘Quality in every Activity’, CEDTI will endeavour toimpart state of the art – computer and IT training through its franchising scheme. The thrust of the Software Courses is to train the students at various levels to carry outthe Management Information System functions of a medium sized establishment, manufactureSoftware for domestic and export use, make multimedia presentations for management andeffectively produce various manufacturing and architectural designs.
  • The thrust of the Hardware Courses at Technician and Telecommunication EquipmentMaintenance Course levels is to train the students to diagnose the faults and carry out repairsat card level in computers, instruments, EPABX, Fax etc. and other office equipment. AtEngineer and Network Engineer levels the thrust is to train them as System Engineers toinstall and supervise the Window NT, Netware and Unix Networking Systems and repairMicrocontrollers / Microprocessor based electronic applications. An Advisory Committee comprising eminent and expert personalities from the InformationTechnology field have been constituted to advise CEDTI on introduction of new courses andrevising the syllabus of existing courses to meet the changing IT needs of the trade, industryand service sectors. The ultimate objective is to provide industry-specific quality education inmodular form to supplement the formal education. The study material has been prepared by the CEDTI, document centre. It is based onthe vast and rich instructional experience of all the CEDTI centres. Any suggestions on theimprovement of the study material will be most welcome. (R. S. Khandpur) Director General (CEDTI)
  • TABLE OF CONTENTSUNIT CHAPTER NAME PAGE NO.1 BASIC FEATURES OF ORACLE 112 SQL - AN INTRODUCTION 313 OPERATORS USED IN ORACLE 534 DATA MANIPULATION LANGUAGE 995 PL/SQL & ITS FEATURES 119
  • preface
  • BASIC FEATURES OF ORACLECOMPETENCY OBJECTIVESThis chapter covers the following topics v Basic features of oracle v Oracle server – introduction v Database – introduction v Physical files v Logical structure v Memory structure v Background processes v SQL, PL/SQL – introduction
  • ORACLE10
  • ORACLE CHAPTER - 1 BASIC FEATURES OF ORACLEORACLE SERVER - AN INTRODUCTIONThe Oracle server is an object-relational database management system . It provides an open,comprehensive, and integrated approach to information management. An Oracle server is combinationof an Oracle database and an Oracle server instance.STRUCTURED QUERY LANGUAGE (SQL)SQL is the programming language that defines and manipulates the database. SQL databases arerelational databases which implies that data is stored in a set of simple relations. A database can haveone or more tables. And each table has columns and rows.In addition to SQL commands, the Oracle server has a procedural language called PL/SQL. PL/SQLenables the programmer to program SQL statements. It allows you to control the flow of a SQL program,to use variables, and to write error-handling procedures.DATABASE ARCHITECTURE Database Structure Physical Database Structure Logical Database StructureDatabase StructureAn Oracle database has both a physical and a logical structure. Because the physical and logical serverstructure are separate, the physical storage of data can be managed without affecting the access tological storage structures.Physical Database StructureAn Oracle database’s physical structure is determined by the operating system files that constitute thedatabase. Each Oracle database is made of three types of files: one or more datafiles, two or more redo 11
  • ORACLElog files, and one or more control files. The files of an Oracle database provide the actual physicalstorage for database information.Logical Database StructureAn Oracle database’s logical structure is determined by:• one or more tablespaces A tablespace is a logical area of storage.• the database’s schema objects A schema is a collection of objects. Schema objects are the logical structures that directly refer to the database’s data. Schema objects include such structures as tables, views, sequences, stored procedures, synonyms, indexes, clusters, and database links.The logical storage structures, including tablespaces, segments, and extents, dictate how the physicalspace of a database is used. The schema objects and the relationships among them form the relationaldesign of a database.AN ORACLE INSTANCEEvery time a database is started, a system global area (SGA) is allocated and Oracle background processesare started. The system global area is a an area of memory used for database information shared by thedatabase users. The combination of the background processes and memory buffers is called an Oracleinstance.An Oracle instance has two types of processes: user processes and Oracle processes. Fig. 1-1 : An Oracle Instance• A user process executes the code of an application program (such as an Oracle Forms applica- tion) or an Oracle Tool (such as Oracle Enterprise Manager).• Oracle processes are server processes that perform work for the user processes and background processes that perform maintenance work for the Oracle server.Figure 1-1 illustrates a multiple-process Oracle instance. 12
  • ORACLEORACLE DATABASESAn Oracle database is the collection of data that is treated as a unit. The general purpose of a databaseis to store and retrieve related information.Open and Closed DatabasesAn Oracle database can be open (accessible) or closed (not accessible). In normal situations, the data-base is open and available for use. However, the database is sometimes closed for specific administra-tive functions that require the database’s data to be unavailable to users.ARCHITECTURE OF DATABASEThe database has logical structures and physical structures.Logical Database StructuresThe following sections explain logical database structures, including tablespaces, schema objects, datablocks, extents, and segments.TablespacesA database is divided into logical storage units called tablespaces. A tablespace is used to group relatedlogical structures together. For example, tablespaces commonly group all of an application’s objects tosimplify some administrative operations.Databases, Tablespaces, and DatafilesThe relationship among databases, tablespaces, and datafiles (datafiles are described in the next section)is illustrated in Figure 1-2. Figure 1-2 Databases, Tablespaces, and DatafilesThis figure illustrates the following:• Each database is logically divided into one or more tablespaces.• One or more datafiles are explicitly created for each tablespace to physically store the data of all logical structures in a tablespace. 13
  • ORACLEOnline and Offline TablespacesA tablespace can be online (accessible) or offline (not accessible). A tablespace is normally online sothat users can access the information within the tablespace. However, sometimes a tablespace may betaken offline to make a portion of the database unavailable while allowing normal access to the remainderof the database. This makes many administrative tasks easier to perform.MEMORY STRUCTURE OF ORACLE DATABASEAn Oracle server uses memory structures and processes to manage and access the database. All memorystructures exist in the main memory of the computers that constitute the database system. Processes arejobs or tasks that work in the memory of these computers. Figure 1-3 shows a typical variation of theOracle server memory and process structures.Memory StructuresOracle creates and uses memory structures to complete several jobs. For example, memory stores programcode being executed and data that is shared among users. Several basic memory structures are associatedwith Oracle: the system global area (which includes the database buffers, redo log buffers, and theshared pool) and the program global areas. The following subsections explain each in detail. Figure 1-3 Memory Structures and Processes of Oracle 14
  • ORACLESYSTEM GLOBAL AREAThe System Global Area (SGA) is a shared memory region that contains data and control informationfor one Oracle instance. An SGA and the Oracle background processes constitute an Oracle instance.Oracle allocates the system global area when an instance starts and deallocates it when the instanceshuts down. Each instance has its own system global area.Users currently connected to an Oracle server share the data in the system global area. For optimalperformance, the entire system global area should be as large as possible (while still fitting in realmemory) to store as much data in memory as possible and minimize disk I/O.The information stored within the system global area is divided into several types of memory struc-tures, including the database buffers, redo log buffer, and the shared pool. These areas have fixed sizesand are created during instance startup.Database Buffer CacheDatabase buffers of the system global area store the most recently used blocks of database data; the setof database buffers in an instance is the database buffer cache. The buffer cache contains modified aswell as unmodified blocks. Because the most recently (and often the most frequently) used data is keptin memory, less disk I/O is necessary and performance is improved.Redo Log BufferThe redo log buffer of the system global area stores redo entries - a log of changes made to the database.The redo entries stored in the redo log buffers are written to an online redo log file, which is used ifdatabase recovery is necessary. Its size is static.Shared PoolThe shared pool is a portion of the system global area that contains shared memory constructs such asshared SQL areas. A shared SQL area is required to process every unique SQL statement submitted toa database. A shared SQL area contains information such as the parse tree and execution plan for thecorresponding statement. A single shared SQL area is used by multiple applications that issue the samestatement, leaving more shared memory for other uses.Statement Handles or CursorsA cursor is a handle (a name or pointer) for the memory associated with a specific statement. (TheOracle Call Interface, OCI, refers to these as statement handles.) Although most Oracle users rely onthe automatic cursor handling of the Oracle utilities, the programmatic interfaces offer applicationdesigners more control over cursors.For example, in precompiler application development, a cursor is a named resource available to aprogram and can be specifically used for the parsing of SQL statements embedded within the application.The application developer can code an application so that it controls the phases of SQL statementexecution and thus improve application performance. 15
  • ORACLEBACKGROUND PROCESSESOracle creates a set of background processes for each instance. They consolidate functions that wouldotherwise be handled by multiple Oracle programs running for each user process. The backgroundprocesses asynchronously perform I/O and monitor other Oracle processes to provide increased paral-lelism for better performance and reliability.An SGA and the set of Oracle background processes constitute an Oracle instance. Each Oracle in-stance may use several background processes. The names of these processes are DBWn, LGWR, CKPT,SMON, PMON, ARCH, RECO, Dnnn, LCKn, SNPn, and QMNn.Database Writer (DBWn)The Database Writer writes modified blocks from the database buffer cache to the datafiles. Althoughone database writer process (DBW0) is sufficient for most systems, you can configure additional pro-cesses (DBW1 through DBW9) to improve write performance for a system that modifies data heavily.The initialization parameter DB_WRITER_PROCESSES specifies the number of DBWn processes.Since Oracle uses write-ahead logging, DBWn does not need to write blocks when a transaction com-mits. Instead, DBWn is designed to perform batched writes with high efficiency. In the most commoncase, DBWn writes only when more data needs to be read into the system global area and too fewdatabase buffers are free. The least recently used data is written to the datafiles first. DBWn also per-forms writes for other functions such as checkpointing.Log Writer (LGWR)The Log Writer writes redo log entries to disk. Redo log data is generated in the redo log buffer of thesystem global area. As transactions commit and the log buffer fills, LGWR writes redo log entries intoan online redo log file.Checkpoint (CKPT)At specific times, all modified database buffers in the system global area are written to the datafiles byDBWn; this event is called a checkpoint. The Checkpoint process is responsible for signalling DBWnat checkpoints and updating all the datafiles and control files of the database to indicate the most recentcheckpoint.System Monitor (SMON)The system monitor performs instance recovery at instance startup. In a multiple instance system (onethat uses Oracle Parallel Server), SMON of one instance can also perform instance recovery for otherinstances that have failed. SMON also cleans up temporary segments that are no longer in use andrecovers dead transactions skipped during crash and instance recovery because of file-read or offlineerrors. These transactions are eventually recovered by SMON when the tablespace or file is broughtback online. SMON also coalesces free extents within the database to make free space contiguous andeasier to allocate. 16
  • ORACLEProcess Monitor (PMON)The process monitor performs process recovery when a user process fails. PMON is responsible forcleaning up the cache and freeing resources that the process was using. PMON also checks on dispatcher(see below) and server processes and restarts them if they have failed.THE PROGRAM INTERFACEThe program interface is the mechanism by which a user process communicates with a server process.It serves as a method of standard communication between any client tool or application (such as OracleForms) and Oracle software. Its functions are to:• act as a communications mechanism, by formatting data requests, passing data, and trapping and returning errors• perform conversions and translations of data, particularly between different types of computers or to external user program datatypesAN EXAMPLE OF HOW ORACLE WORKSThe following example illustrates an Oracle configuration where the user and associated server processare on separate machines (connected via a network).1. An instance is currently running on the computer that is executing Oracle (often called the host or database server).2. A computer running an application (a local machine or client workstation) runs the application in a user process. The client application attempts to establish a connection to the server using the proper Net8 driver.3. The server is running the proper Net8 driver. The server detects the connection request from the application and creates a (dedicated) server process on behalf of the user process.4. The user executes a SQL statement and commits the transaction. For example, the user changes a name in a row of a table.5. The server process receives the statement and checks the shared pool for any shared SQL area that contains an identical SQL statement. If a shared SQL area is found, the server process checks the user’s access privileges to the requested data and the previously existing shared SQL area is used to process the statement; if not, a new shared SQL area is allocated for the statement so that it can be parsed and processed.6. The server process retrieves any necessary data values from the actual datafile (table) or those stored in the system global area.7. The server process modifies data in the system global area. The DBWn process writes modified blocks permanently to disk when doing so is efficient. Because the transaction committed, the LGWR process immediately records the transaction in the online redo log file.8. If the transaction is successful, the server process sends a message across the network to the application. If it is not successful, an appropriate error message is transmitted.9. Throughout this entire procedure, the other background processes run, watching for conditions that require intervention. In addition, the database server manages other users’ transactions and prevents contention between transactions that request the same data.These steps describe only the most basic level of operations that Oracle performs. 17
  • ORACLEDATA CONCURRENCY AND CONSISTENCYThis section explains the software mechanisms used by Oracle to fulfill the following important re-quirements of an information management system:• Data must be read and modified in a consistent fashion.• Data concurrency of a multi-user system must be maximized.• High performance is required for maximum productivity from the many users of the database system.ConcurrencyA primary concern of a multiuser database management system is how to control concurrency, or thesimultaneous access of the same data by many users. Without adequate concurrency controls, datacould be updated or changed improperly, compromising data integrity.If many people are accessing the same data, one way of managing data concurrency is to make eachuser wait his or her turn. The goal of a database management system is to reduce that wait so it is eithernon-existent or negligible to each user. All data manipulation (DML) statements should proceed withas little interference as possible and destructive interactions between concurrent transactions must beprevented. Destructive interaction is any interaction that incorrectly updates data or incorrectly altersunderlying data structures. Neither performance nor data integrity can be sacrificed.Oracle resolves such issues by using various types of locks and a multiversion consistency model. Bothfeatures are discussed later in this section. These features are based on the concept of a transaction. It isthe application designer’s responsibility to ensure that transactions fully exploit these concurrency andconsistency features.READ CONSISTENCYRead consistency, as supported by Oracle, does the following:• guarantees that the set of data seen by a statement is consistent with respect to a single point-in- time and does not change during statement execution (statement-level read consistency)• ensures that readers of database data do not wait for writers or other readers of the same data• ensures that writers of database data do not wait for readers of the same data• ensures that writers only wait for other writers if they attempt to update identical rows in con- current transactionsThe simplest way to think of Oracle’s implementation of read consistency is to imagine each useroperating a private copy of the database, hence the multiversion consistency model.Read Consistency, Rollback Segments, and TransactionsTo manage the multiversion consistency model, Oracle must create a read-consistent set of data whena table is being queried (read) and simultaneously updated (written). When an update occurs, the origi-nal data values changed by the update are recorded in the database’s rollback segments. As long as this 18
  • ORACLEupdate remains part of an uncommitted transaction, any user that later queries the modified data viewsthe original data values - Oracle uses current information in the system global area and information inthe rollback segments to construct a read-consistent view of a table’s data for a query.Only when a transaction is committed are the changes of the transaction made permanent. Statementsthat start after the user’s transaction is committed only see the changes made by the committed transac-tion.Note that a transaction is key to Oracle’s strategy for providing read consistency. This unit of commit-ted (or uncommitted) SQL statements:• dictates the start point for read-consistent views generated on behalf of readers• controls when modified data can be seen by other transactions of the database for reading or updating.Read-Only TransactionsBy default, Oracle guarantees statement-level read consistency. The set of data returned by a singlequery is consistent with respect to a single point in time. However, in some situations, you may alsorequire transaction-level read consistency - the ability to run multiple queries within a single transac-tion, all of which are read-consistent with respect to the same point in time, so that queries in thistransaction do not see the effects of intervening committed transactions.If you want to run a number of queries against multiple tables and if you are doing no updating, youmay prefer a read-only transaction. After indicating that your transaction is read-only, you can executeas many queries as you like against any table, knowing that the results of each query are consistent withrespect to the same point in time.LOCKING MECHANISMSOracle also uses locks to control concurrent access to data. Locks are mechanisms intended to preventdestructive interaction between users accessing Oracle data.Locks are used to achieve two important database goals:consistency Ensures that the data a user is viewing or changing is not changed (by other users) until the user is finished with the data.integrity Ensures that the database’s data and structures reflect all changes made to them in the correct sequence.Locks guarantee data integrity while allowing maximum concurrent access to the data by unlimitedusers.Automatic LockingOracle locking is performed automatically and requires no user action. Implicit locking occurs for SQLstatements as necessary, depending on the action requested. 19
  • ORACLEOracle’s sophisticated lock manager automatically locks table data at the row level. By locking tabledata at the row level, contention for the same data is minimized.Oracle’s lock manager maintains several different types of row locks, depending on what type of opera-tion established the lock. In general, there are two types of locks: exclusive locks and share locks. Onlyone exclusive lock can be obtained on a resource (such as a row or a table); however, many share lockscan be obtained on a single resource. Both exclusive and share locks always allow queries on thelocked resource, but prohibit other activity on the resource (such as updates and deletes).Manual LockingUnder some circumstances, a user may want to override default locking. Oracle allows manual over-ride of automatic locking features at both the row level (by first querying for the rows that will beupdated in a subsequent statement) and the table level.ORDBMSDatabase management systems have evolved from hierarchical to network to relational models. Themost widely accepted database model is the relational model. Oracle extends the relational model to anobject-relational model, which makes it possible to store complex business models in a relationaldatabase.The Relational ModelThe relational model has three major aspects:structures Structures are well-defined objects (such as tables, views, indexes, and so on) that store or access the data of a database. Structures and the data contained within them can be manipulated by operations.operations Operations are clearly defined actions that allow users to manipulate the data and structures of a database. The operations on a database must adhere to a predefined set of integrity rules.integrity rules Integrity rules are the laws that govern which operations are allowed on the data and structures of a database. Integrity rules protect the data and the structures of a database.Relational database management systems offer benefits such as:• independence of physical data storage and logical database structure• variable and easy access to all data• complete flexibility in database design• reduced data storage and redundancyTHE OBJECT-RELATIONAL MODELThe object-relational model allows users to define object types, specifying both the structure of the dataand the methods of operating on the data, and to use these datatypes within the relational model. 20
  • ORACLEObject types are abstractions of the real-world entities - for example, purchase orders - that applicationprograms deal with. An object type has three kinds of components:• A name, which serves to identify the object type uniquely.• Attributes, which are built-in datatypes or other user-defined types. Attributes model the struc- ture of the real world entity.• Methods, which are functions or procedures written in PL/SQL and stored in the database, or written in a language like C and stored externally. Methods implement specific operations that an application can perform on the data. Every object type has a constructor method that makes a new object according to the datatype’s specification.SCHEMAS AND SCHEMA OBJECTSA schema is a collection of database objects that are available to a user. Schema objects are the logicalstructures that directly refer to the database’s data. Schema objects include such structures as tables,views, sequences, stored procedures, synonyms, indexes, clusters, and database links. (There is norelationship between a tablespace and a schema; objects in the same schema can be in differenttablespaces, and a tablespace can hold objects from different schemas.)TablesA table is the basic unit of data storage in an Oracle database. The tables of a database hold all of theuser-accessible data.Table data is stored in rows and columns. Every table is defined with a table name and set of columns.Each column is given a column name, a datatype (such as CHAR, DATE, or NUMBER), and a width(which may be predetermined by the datatype, as in DATE) or scale and precision (for the NUMBERdatatype only). Once a table is created, valid rows of data can be inserted into it. The table’s rows canthen be queried, deleted, or updated.Oracle8 provides for the partitioning of tables.To enforce defined business rules on a table’s data, integrity constraints and triggers can also be definedfor a table.ViewsA view is a custom-tailored presentation of the data in one or more tables. A view can also be thoughtof as a “stored query”.Views do not actually contain or store data; rather, they derive their data from the tables on which theyare based, referred to as the base tables of the views. Base tables can in turn be tables or can themselvesbe views.Like tables, views can be queried, updated, inserted into, and deleted from, with some restrictions. Alloperations performed on a view actually affect the base tables of the view. 21
  • ORACLEViews are often used to do the following:• Provide an additional level of table security by restricting access to a predetermined set of rows and columns of a table. For example, a view of a table can be created so that columns with sensitive data (for example, salary information) are not included in the definition of the view.• Hide data complexity. For example, a single view can combine 12 monthly sales tables to pro- vide a year of data for analysis and reporting. A single view can also be used to create a join, which is a display of related columns or rows in multiple tables. However, the view hides the fact that this data actually originates from several tables.• Simplify commands for the user. For example, views allow users to select information from multiple tables without requiring the users to actually know how to perform a correlated subquery.• Present the data in a different perspective from that of the base table. For example, views pro- vide a means to rename columns without affecting the tables on which the view is based.• Store complex queries. For example, a query might perform extensive calculations with table information. By saving this query as a view, the calculations are performed only when the view is queried.Views that involve a join (a SELECT statement that selects data from multiple tables) of two or moretables can only be updated under certain conditions.SequencesA sequence generates a serial list of unique numbers for numeric columns of a database’s tables. Se-quences simplify application programming by automatically generating unique numerical values forthe rows of a single table or multiple tables.For example, assume two users are simultaneously inserting new employee rows into the EMP table.By using a sequence to generate unique employee numbers for the EMPNO column, neither user has towait for the other to input the next available employee number. The sequence automatically generatesthe correct values for each user.Sequence numbers are independent of tables, so the same sequence can be used for one or more tables.After creation, a sequence can be accessed by various users to generate actual sequence numbers.Program UnitsThe term “program unit” is used in this manual to refer to stored procedures, functions, packages,triggers, and anonymous blocks.A procedure or function is a set of SQL and PL/SQL (Oracle’s procedural language extension to SQL)statements grouped together as an executable unit to perform a specific task. Procedures and functionsallow you to combine the ease and flexibility of SQL with the procedural functionality of a structuredprogramming language. Using PL/SQL, such procedures and functions can be defined and stored in thedatabase for continued use. Procedures and functions are identical, except that functions always returna single value to the caller, while procedures do not return a value to the caller.Packages provide a method of encapsulating and storing related procedures, functions, and other pack-age constructs together as a unit in the database. While packages provide the database administrator or 22
  • ORACLEapplication developer organizational benefits, they also offer increased functionality and database per-formance.SynonymsA synonym is an alias for a table, view, sequence, or program unit. A synonym is not actually a schemaobject itself, but instead is a direct reference to a schema object. Synonyms are used to• mask the real name and owner of a schema object• provide public access to a schema object• provide location transparency for tables, views, or program units of a remote database• simplify the SQL statements for database usersA synonym can be public or private. An individual user can create a private synonym, which is avail-able only to that user. Database administrators most often create public synonyms that make the baseschema object available for general, system-wide use by any database user.THE DATA DICTIONARYEach Oracle database has a data dictionary. An Oracle data dictionary is a set of tables and views thatare used as a read-only reference about the database. For example, a data dictionary stores informationabout both the logical and physical structure of the database. In addition to this valuable information, adata dictionary also stores such information as:• the valid users of an Oracle database• information about integrity constraints defined for tables in the database• how much space is allocated for a schema object and how much of it is in useA data dictionary is created when a database is created. To accurately reflect the status of the databaseat all times, the data dictionary is automatically updated by Oracle in response to specific actions (suchas when the structure of the database is altered). The data dictionary is critical to the operation of thedatabase, which relies on the data dictionary to record, verify, and conduct ongoing work. For example,during database operation, Oracle reads the data dictionary to verify that schema objects exist and thatusers have proper access to them.DATA ACCESSThis section introduces how Oracle meets the general requirements for a DBMS to:• adhere to industry accepted standards for a data access language• control and preserve the consistency of a database’s information while manipulating its data• provide a system for defining and enforcing rules to maintain the integrity of a database’s information• provide high performanceSQL - THE STRUCTURED QUERY LANGUAGESQL is a simple, powerful database access language that is the standard language for relational data-base management systems. The SQL implemented by Oracle Corporation for Oracle is 100 percentcompliant with the ANSI/ISO standard SQL data language. 23
  • ORACLESQL StatementsAll operations on the information in an Oracle database are performed using SQL statements. A SQLstatement is a string of SQL text that is given to Oracle to execute. A statement must be the equivalentof a complete SQL sentence, as in:SELECT ename, deptno FROM emp;Only a complete SQL statement can be executed, whereas a sentence fragment, such as the following,generates an error indicating that more text is required before a SQL statement can execute:SELECT enameA SQL statement can be thought of as a very simple, but powerful, computer program or instruction.SQL statements are divided into the following categories:• Data Definition Language (DDL) statements• Data Manipulation Language (DML) statements• transaction control statements• session control statements• system control statements• embedded SQL statementsData Definition Statements (DDL)DDL statements define, maintain, and drop schema objects when they are no longer needed. DDLstatements also include statements that permit a user to grant other users the privileges, or rights, toaccess the database and specific objects within the database.Data Manipulation Statements (DML)DML statements manipulate the database’s data. For example, querying, inserting, updating, and delet-ing rows of a table are all DML operations; locking a table or view and examining the execution plan ofan SQL statement are also DML operations.Transaction Control StatementsTransaction control statements manage the changes made by DML statements. They allow the user orapplication developer to group changes into logical transactions.Session Control StatementsSession control statements allow a user to control the properties of his current session, including en-abling and disabling roles and changing language settings. The two session control statements areALTER SESSION and SET ROLE. 24
  • ORACLESystem Control StatementsSystem control commands change the properties of the Oracle server instance. The only system controlcommand is ALTER SYSTEM; it allows you to change such settings as the minimum number ofshared servers, to kill a session, and to perform other tasks.Embedded SQL StatementsEmbedded SQL statements incorporate DDL, DML, and transaction control statements in a procedurallanguage program (such as those used with the Oracle Precompilers). Examples include OPEN, CLOSE,FETCH, and EXECUTE.PL/SQLPL/SQL is Oracle’s procedural language extension to SQL. PL/SQL combines the ease and flexibilityof SQL with the procedural functionality of a structured programming language, such as IF ... THEN,WHILE, and LOOP.When designing a database application, a developer should consider the advantages of using stored PL/SQL:• Because PL/SQL code can be stored centrally in a database, network traffic between applica- tions and the database is reduced, so application and system performance increases.• Data access can be controlled by stored PL/SQL code. In this case, the users of PL/SQL can access data only as intended by the application developer (unless another access route is granted).• PL/SQL blocks can be sent by an application to a database, executing complex operations with- out excessive network traffic.Even when PL/SQL is not stored in the database, applications can send blocks of PL/SQL to the data-base rather than individual SQL statements, thereby again reducing network traffic.The following sections describe the different program units that can be defined and stored centrally ina database.Procedures and FunctionsProcedures and functions consist of a set of SQL and PL/SQL statements that are grouped together as aunit to solve a specific problem or perform a set of related tasks. A procedure is created and stored incompiled form in the database and can be executed by a user or a database application. Procedures andfunctions are identical except that functions always return a single value to the caller, while proceduresdo not return values to the caller.PackagesPackages provide a method of encapsulating and storing related procedures, functions, variables, andother package constructs together as a unit in the database. While packages allow the administrator orapplication developer the ability to organize such routines, they also offer increased functionality (forexample, global package variables can be declared and used by any procedure in the package) andperformance (eg. all objects of the package are parsed, compiled, and loaded into memory once). 25
  • ORACLEDatabase TriggersOracle allows you to write procedures that are automatically executed as a result of an insert in, updateto, or delete from a table. These procedures are called database triggers.Database triggers can be used in a variety of ways for the information management of your database.For example, they can be used to automate data generation, audit data modifications, enforce complexintegrity constraints, and customize complex security authorizations.MethodsA method is a procedure or function that is part of the definition of a user-defined datatype (object type,nested table, or variable array).Methods are different from stored procedures in two ways:• You invoke a method by referring to an object of its associated type.• A method has complete access to the attributes of its associated object and to information about its type.Every user-defined datatype has a system-defined constructor method, that is, a method that makes anew object according to the datatype’s specification. The name of the constructor method is the nameof the user-defined type. In the case of an object type, the constructor method’s parameters have thenames and types of the object type’s attributes. The constructor method is a function that returns thenew object as its value. Nested tables and arrays also have constructor methods.Comparison methods define an order relationship among objects of a given object type. A map methoduses Oracle’s ability to compare built-in types. For example, Oracle can compare two rectangles bycomparing their areas if an object type called RECTANGLE has attributes HEIGHT and WIDTH andyou define a map method area that returns a number, namely the product of the rectangle’s HEIGHTand WIDTH attributes. An order method uses its own internal logic to compare two objects of a givenobject type. It returns a value that encodes the order relationship. For example, it may return -1 if thefirst is smaller, 0 if they are equal, and 1 if the first is larger.DATA INTEGRITYIt is very important to guarantee that data adheres to certain business rules, as determined by the data-base administrator or application developer. For example, assume that a business rule says that no rowin the INVENTORY table can contain a numeric value greater than 9 in the SALE_DISCOUNT col-umn. If an INSERT or UPDATE statement attempts to violate this integrity rule, Oracle must roll backthe invalid statement and return an error to the application. Oracle provides integrity constraints anddatabase triggers as solutions to manage a database’s data integrity rules.Integrity ConstraintsAn integrity constraint is a declarative way to define a business rule for a column of a table. An integrityconstraint is a statement about a table’s data that is always true: 26
  • ORACLE• If an integrity constraint is created for a table and some existing table data does not satisfy the constraint, the constraint cannot be enforced.• After a constraint is defined, if any of the results of a DML statement violate the integrity constraint, the statement is rolled back and an error is returned.Integrity constraints are defined with a table and are stored as part of the table’s definition, centrally inthe database’s data dictionary, so that all database applications must adhere to the same set of rules. Ifa rule changes, it need only be changed once at the database level and not many times for each applica-tion.The following integrity constraints are supported by Oracle:NOT NULL Disallows nulls (empty entries) in a table’s column.UNIQUE Disallows duplicate values in a column or set of columns.PRIMARY KEY Disallows duplicate values and nulls in a column or set of columns.FOREIGN KEY Requires each value in a column or set of columns match a value in a related table’s UNIQUE or PRIMARY KEY (FOREIGN KEY integrity constraints also define referential integrity actions that dictate what Oracle should do with dependent data if the data it references is altered).CHECK Disallows values that do not satisfy the logical expression of the constraint.KeysThe term “key” is used in the definitions of several types of integrity constraints. A key is the column orset of columns included in the definition of certain types of integrity constraints. Keys describe therelationships between the different tables and columns of a relational database. The different types ofkeys include:primary key The column or set of columns included in the definition of a table’s PRIMARY KEY constraint. A primary key’s values uniquely identify the rows in a table. Only one primary key may be defined per table.unique key The column or set of columns included in the definition of a UNIQUE constraint.foreign key The column or set of columns included in the definition of a referential integrity constraint.Referenced key The unique key or primary key of the same or different table that is referenced by a foreign key.Individual values in a key are called key values.Database TriggersCentralized actions can be defined using a non-declarative approach (writing PL/SQL code) with databasetriggers. A database trigger is a stored procedure that is fired (implicitly executed) when an INSERT,UPDATE, or DELETE statement is issued against the associated table. Database triggers can be used tocustomize a database management system with such features as value-based auditing and the enforcement 27
  • ORACLEof complex security checks and integrity rules. For example, a database trigger might be created toallow a table to be modified only during normal business hours.Note:While database triggers allow you to define and enforce integrity rules, a database trigger is not thesame as an integrity constraint. Among other things, a database trigger defined to enforce an integrityrule does not check data already loaded into a table. Therefore, it is strongly recommended that you usedatabase triggers only when the integrity rule cannot be enforced by integrity constraints. 28
  • ORACLE SQL - AN INTRODUCTIONCOMPETENCY OBJECTIVESThis chapter covers the following topics v SQL - An Introduction v Data types in SQL v SQL - Queries v SQL Commands 29
  • ORACLE30
  • ORACLE CHAPTER - 2 SQL - AN INTRODUCTIONThe language, Structured English Query Language (“SEQUEL”) was developed by IBM Corporation,Inc., to use Codd’s model. SEQUEL later became SQL (still pronounced “sequel”). In 1979, RelationalSoftware, Inc. (now Oracle Corporation) introduced the first commercially available implementationof SQL. Today, SQL is accepted as the standard RDBMS language.Working of SQLThe strengths of SQL benefit all types of users, including application programmers, database adminis-trators, management, and end users. Technically speaking, SQL is a data sublanguage: the purpose ofSQL is to provide an interface to a relational database such as Oracle, and all SQL statements areinstructions to the database. In this it differs from general-purpose programming languages like C andBASIC. Among the features of SQL are the following:• It processes sets of data as groups rather than as individual units.• It provides automatic navigation to the data.Essentially, SQL lets you work with data at the logical level. You need to be concerned with the imple-mentation details only when you want to manipulate the data. For example, to retrieve a set of rowsfrom a table, you define a condition used to filter the rows. All rows satisfying the condition are re-trieved in a single step and can be passed as a unit to the user, to another SQL statement, or to anapplication. You need not deal with the rows one by one, nor do you have to worry about how they arephysically stored or retrieved. All SQL statements use the optimizer, a part of Oracle that determines afast means of accessing the specified data. Oracle also provides techniques you can use to make theoptimizer perform its job better.SQL provides commands for a variety of tasks, including:• querying data• inserting, updating, and deleting rows in a table• creating, replacing, altering, and dropping objects• controlling access to the database and its objects• guaranteeing database consistency and integritySQL unifies all of the above tasks in one consistent language. 31
  • ORACLELanguage for All Relational DatabasesAll major relational database management systems support SQL, so you can transfer all skills you havegained with SQL from one database to another. In addition, all programs written in SQL are portable:they can often be moved from one database to another with very little modification.EMBEDDED SQLEmbedded SQL refers to the use of standard SQL commands embedded within a procedural programminglanguage. Embedded SQL is a collection of these commands:• all SQL commands, such as SELECT and INSERT, available with SQL with interactive tools• dynamic SQL execution commands, such as PREPARE and OPEN, which integrate the standard SQL commands with a procedural programming languageEmbedded SQL also includes extensions to some standard SQL commands. Embedded SQL is supportedby the Oracle precompilers. The Oracle precompilers interpret embedded SQL statements and translatethem into statements that can be understood by procedural language compilers.Each of these Oracle precompilers translates embedded SQL programs into a different procedurallanguage:• the Pro*C/C++ precompiler• the Pro*COBOL precompiler• the Pro*FORTRAN precompiler• the SQL*Module for ADAELEMENTS OF SQL LANGUAGEBasic elements of Oracle SQL :• Literals• Text• Integer• Number• Datatypes• Nulls• Pseudocolumns• CommentsLiteralsThe terms literal and constant value are synonymous and refer to a fixed data value. For example,‘JACK’, ‘BLUE ISLAND’, and ‘101’ are all character literals; 5001 is a numeric literal. Note thatcharacter literals are enclosed in single quotation marks, which enable Oracle to distinguish them fromschema object names.Many SQL statements and functions require you to specify character and numeric literal values. Youcan also specify literals as part of expressions and conditions. You can specify character literals with 32
  • ORACLEthe ‘text’ notation, national character literals with the N’text’ notation, and numeric literals with theinteger or number notation, depending on the context of the literal. The syntactic forms of these notationsappear in the following sections.TextText specifies a text or character literal. You must use this notation to specify values whenever ‘text’ orchar appear in expressions, conditions, SQL functions, and SQL commands in other parts of this refer-ence.A text literal must be enclosed in single quotation marks. This reference uses the terms text literal andcharacter literal interchangeably.Text literals have properties of both the CHAR and VARCHAR2 datatypes:• Within expressions and conditions, Oracle treats text literals as though they have the datatype CHAR by comparing them using blank-padded comparison semantics.• A text literal can have a maximum length of 4000 bytes.Here are some valid text literals:‘Hello’‘ORACLE.dbs’‘Jackie’’s raincoat’’09-MAR-92N’nchar literal’IntegerYou must use the integer notation to specify an integer whenever integer appears in expressions,conditions, SQL functions, and SQL commands described in other parts of this reference.An integer can store a maximum of 38 digits of precision.Here are some valid integers:7+255NumberYou must use the number notation to specify values whenever number appears in expressions, condi-tions, SQL functions, and SQL commands in other parts of this reference.A number can store a maximum of 38 digits of precision.If you have established a decimal character other than a period (.) with the initialization parameterNLS_NUMERIC_CHARACTERS, you must specify numeric literals with ‘text’ notation. In such cases,Oracle automatically converts the text literal to a numeric value. 33
  • ORACLEFor example, if the NLS_NUMERIC_CHARACTERS parameter specifies a decimal character ofcomma, specify the number 5.123 as follows:‘5,123’Here are some valid representations of number:25+6.340.525e-03-1DatatypesEach literal or column value manipulated by Oracle has a datatype. A value’s datatype associates afixed set of properties with the value. These properties cause Oracle to treat values of one datatypedifferently from values of another. For example, you can add values of NUMBER datatype, but notvalues of RAW datatype.When you create a table or cluster, you must specify an internal datatype for each of its columns. Whenyou create a procedure or stored function, you must specify an internal datatype for each of its arguments.These datatypes define the domain of values that each column can contain or each argument can have.For example, DATE columns cannot accept the value February 29 (except for a leap year) or the values2 or ‘SHOE’. Each value subsequently placed in a column assumes the column’s datatype. For example,if you insert ’01-JAN-92 into a DATE column, Oracle treats the ’01-JAN-92 character string as aDATE value after verifying that it translates to a valid date.Table 2-1 summarizes Oracle internal datatypes. The rest of this section describes these datatypes indetail. 34
  • ORACLETable 2-1 : Internal Datatype Summary INTERNAL CODE DATATYPE DESCRIPTION Variable-length character string having maximum length 1 VARCHAR2(size) size bytes. Maximum size is 4000, and minimum is 1. You must specify size for a VARCHAR2. Variable-length character string having maximum length size characters or bytes, depending on the choice of NVARCHAR2(size) national character set. Maximum size is determined by the number of bytes required to store each character, with an upper limit of 4000 bytes. You must specify size for NVARCHAR2. Number having precision p and scale s. The precision p can 2 NUMBER(p,s) range from 1 to 38. The scale s can range from -84 to 127. Character data of variable length up to 2 gigabytes, or 231 - 8 LONG 1 bytes. Valid date range from January 1, 4712 BC to December 31, 12 DATE 4712 AD. Raw binary data of length size bytes. Maximum size is 23 RAW(size) 2000 bytes. You must specify size for a RAW value. 24 LONG RAW Raw binary data of variable length up to 2 gigabytes. Hexadecimal string representing the unique address of a 69 ROWID row in its table. This datatype is primarily for values returned by the ROWID pseudocolumn. Fixed length character data of length size bytes. Maximum 96 CHAR(size) size is 2000 bytes. Default and minimum size is 1 byte.Character DatatypesCharacter datatypes store character (alphanumeric) data-words and free-form text-in the database ornational character set. They are less restrictive than other datatypes and consequently have fewerproperties. For example, character columns can store all alphanumeric values, but NUMBER columnscan store only numeric values.Character data is stored in strings with byte values corresponding to one of the character sets, such as 7-bit ASCII or EBCDIC Code , specified when the database was created. Oracle supports both single-byte and multibyte character sets.These datatypes are used for character data:These datatypes are used for character data:• CHAR Datatype• VARCHAR2 Datatype 35
  • ORACLECHAR DatatypeThe CHAR datatype specifies a fixed-length character string. When you create a table with a CHARcolumn, you supply the column length in bytes. Oracle subsequently ensures that all values stored inthat column have this length. If you insert a value that is shorter than the column length, Oracle blank-pads the value to column length. If you try to insert a value that is too long for the column, Oraclereturns an error.The default length for a CHAR column is 1 character and the maximum allowed is 2000 characters. Azero-length string can be inserted into a CHAR column, but the column is blank-padded to 1 characterwhen used in comparisons.VARCHAR2 DatatypeThe VARCHAR2 datatype specifies a variable-length character string. When you create a VARCHAR2column, you can supply the maximum number of bytes of data that it can hold. Oracle subsequentlystores each value in the column exactly as you specify it, provided it does not exceed the column’smaximum length. This maximum must be at least 1 byte, although the actual length of the string storedis permitted to be zero. If you try to insert a value that exceeds the specified length, Oracle returns anerror.You must specify a maximum length for a VARCHAR2 column. The maximum length of VARCHAR2data is 4000 bytes. Oracle compares VARCHAR2 values using nonpadded comparison semantics.VARCHAR DatatypeThe VARCHAR datatype is currently synonymous with the VARCHAR2 datatype. Oracle recommendsthat you use VARCHAR2 rather than VARCHAR. In the future, VARCHAR might be defined as aseparate datatype used for variable-length character strings compared with different comparisonsemantics.NUMBER DatatypeThe NUMBER datatype stores zero, positive and negative fixed and floating-point numbers withmagnitudes between 1.0 x 10-130 and 9.9...9 x 10125 (38 nines followed by 88 zeroes) with 38 digits ofprecision. If you specify an arithmetic expression whose value has a magnitude greater than or equal to1.0 x 10126, Oracle returns an error.Specify a fixed-point number using the following form:NUMBER(p,s)where:s is the scale, or the number of digits to the right of the decimal point. The scale can range from -84 to 127. 36
  • ORACLESpecify an integer using the following form:NUMBER(p) is a fixed-point number with precision p and scale 0. This is equivalent to NUMBER(p,0).Specify a floating-point number using the following form:NUMBER is a floating-point number with decimal precision 38. Note that a scale value is not applicable for floating-point numbers.Scale and PrecisionSpecify the scale and precision of a fixed-point number column for extra integrity checking on input.Specifying scale and precision does not force all values to a fixed length. If a value exceeds the precision,Oracle returns an error. If a value exceeds the scale, Oracle rounds it.The following examples show how Oracle stores data using different precisions and scales. 7456123.89 NUMBER 7456123.89 7456123.89 NUMBER(9) 7456124 7456123.89 NUMBER(9,2) 7456123.89 7456123.89 NUMBER(9,1) 7456123.9 7456123.89 NUMBER(6) exceeds precision 7456123.89 NUMBER(7,-2) 7456100 7456123.89 NUMBER(-7,2) exceeds precisionNegative ScaleIf the scale is negative, the actual data is rounded to the specified number of places to the left of thedecimal point. For example, a specification of (10,-2) means to round to hundreds.Scale Greater than PrecisionYou can specify a scale that is greater than precision, although it is uncommon. In this case, the precisionspecifies the maximum number of digits to the right of the decimal point. As with all number datatypes,if the value exceeds the precision, Oracle returns an error message. If the value exceeds the scale,Oracle rounds the value. For example, a column defined as NUMBER(4,5) requires a zero for the firstdigit after the decimal point and rounds all values past the fifth digit after the decimal point. Thefollowing examples show the effects of a scale greater than precision: Actual Data Specified As Stored As .01234 NUMBER(4,5) .01234 .00012 NUMBER(4,5) .00012 .000127 NUMBER(4,5) .00013 .0000012 NUMBER(2,7) .0000012 .00000123 NUMBER(2,7) .0000012 37
  • ORACLEFloating-Point NumbersOracle allows you to specify floating-point numbers, which can have a decimal point anywhere fromthe first to the last digit or can have no decimal point at all. A scale value is not applicable to floating-point numbers, because the number of digits that can appear after the decimal point is not restricted.Oracle also supports the ANSI datatype FLOAT. You can specify this datatype using one of thesesyntactic forms:FLOAT specifies a floating-point number with decimal precision 38, or binary precision 126.FLOAT(b) specifies a floating-point number with binary precision b. The precision b can range from 1 to 126. To convert from binary to decimal precision, multiply b by 0.30103. To convert from decimal to binary precision, multiply the decimal precision by 3.32193. The maximum of 126 digits of binary precision is roughly equivalent to 38 digits of decimal precision.LONG DatatypeLONG columns store variable length character strings containing up to 2 gigabytes, or 231-1 bytes.LONG columns have many of the characteristics of VARCHAR2 columns. You can use LONG columnsto store long text strings. Oracle uses LONG columns in the data dictionary to store the text of viewdefinitions. The length of LONG values may be limited by the memory available on your computer.You can reference LONG columns in SQL statements in these places:• SELECT lists• SET clauses of UPDATE statements• VALUES clauses of INSERT statementsThe use of LONG values are subject to some restrictions:• A table cannot contain more than one LONG column.• LONG columns cannot appear in integrity constraints (except for NULL and NOT NULL constraints).• LONG columns cannot be indexed.• A stored function cannot return a LONG value.• Within a single SQL statement, all LONG columns, updated tables, and locked tables must be located on the same database.LONG columns cannot appear in certain parts of SQL statements:• WHERE, GROUP BY, ORDER BY, or CONNECT BY clauses or with the DISTINCT operator in SELECT statements• the UNIQUE clause of a SELECT statement• the column list of a CREATE CLUSTER statement• the CLUSTER clause of a CREATE SNAPSHOT statement• SQL functions (such as SUBSTR or INSTR)• expressions or conditions• SELECT lists of queries containing GROUP BY clauses 38
  • ORACLE• SELECT lists of subqueries or queries combined by set operators• SELECT lists of CREATE TABLE ... AS SELECT statements• SELECT lists in subqueries in INSERT statementsTriggers can use the LONG datatype in the following manner:• A SQL statement within a trigger can insert data into a LONG column.• If data from a LONG column can be converted to a constrained datatype (such as CHAR and VARCHAR2), a LONG column can be referenced in a SQL statement within a trigger. Note that the maximum length for these datatypes is 32K.• Variables in triggers cannot be declared using the LONG datatype.• :NEW and :OLD cannot be used with LONG columns..DATE DATATYPEThe DATE datatype stores date and time information. Although date and time information can berepresented in both CHAR and NUMBER datatypes, the DATE datatype has special associated properties.For each DATE value, Oracle stores the following information: century, year, month, day, hour, minute,and second.To specify a date value, you must convert a character or numeric value to a date value with the TO_DATEfunction. Oracle automatically converts character values that are in the default date format into datevalues when they are used in date expressions. The default date format is specified by the initializationparameter NLS_DATE_FORMAT and is a string such as ‘DD-MON-YY’. This example date formatincludes a two-digit number for the day of the month, an abbreviation of the month name, and the lasttwo digits of the year.If you specify a date value without a time component, the default time is 12:00:00 am (midnight). If youspecify a date value without a date, the default date is the first day of the current month.The date function SYSDATE returns the current date and time. For information on the SYSDATE andTO_DATE functions and the default date format.Date ArithmeticYou can add and subtract number constants as well as other dates from dates. Oracle interprets numberconstants in arithmetic date expressions as numbers of days. For example, SYSDATE + 1 is tomorrow.SYSDATE - 7 is one week ago. SYSDATE + (10/1440) is ten minutes from now. Subtracting theHIREDATE column of the EMP table from SYSDATE returns the number of days since each employeewas hired. You cannot multiply or divide DATE values.Oracle provides functions for many of the common date operations. For example, the ADD_MONTHSfunction allows you to add or subtract months from a date. The MONTHS_BETWEEN function returnsthe number of months between two dates. The fractional portion of the result represents that portion ofa 31-day month. Because each date contains a time component, most results of date operations includea fraction. This fraction means a portion of one day. For example, 1.5 days is 36 hours. 39
  • ORACLEUsing Julian DatesA Julian date is the number of days since January 1, 4712 bc. Julian dates allow continuous dating froma common reference. You can use the date format model “J” with date functions TO_DATE andTO_CHAR to convert between Oracle DATE values and their Julian equivalents.ExampleThis statement returns the Julian equivalent of January 1, 1997:SELECT TO_CHAR(TO_DATE(’01-01-1997, ‘MM-DD-YYYY’),’J’) FROM DUAL;TO_CHAR————2450450RAW and LONG RAW DatatypesThe RAW and LONG RAW datatypes store data that is not to be interpreted (not explicitly convertedwhen moving data between different systems) by Oracle. These datatypes are intended for binary dataor byte strings. For example, you can use LONG RAW to store graphics, sound, documents, or arrays ofbinary data; the interpretation is dependent on the use.RAW is a variable-length datatype like the VARCHAR2 character datatype, except that Net8 (whichconnects user sessions to the instance) and the Import and Export utilities do not perform characterconversion when transmitting RAW or LONG RAW data. In contrast, Net8 and Import/Export auto-matically convert CHAR, VARCHAR2, and LONG data from the database character set to the usersession character set (set by the NLS_LANGUAGE parameter of the ALTER SESSION command), ifthe two character sets are different.When Oracle automatically converts RAW or LONG RAW data to and from CHAR data, the binarydata is represented in hexadecimal form with one hexadecimal character representing every four bits ofRAW data. For example, one byte of RAW data with bits 11001011 is displayed and entered as ‘CB’.You can index RAW data, but not LONG RAW data.ROWID DatatypeEach row in the database has an address. You can examine a row’s address by querying the pseudocolumnROWID. Values of this pseudocolumn are hexadecimal strings representing the address of each row.These strings have the datatype ROWID. You can also create tables and clusters that contain actualcolumns having the ROWID datatype. Oracle does not guarantee that the values of such columns arevalid ROWIDs.Datatype Comparison RulesThis section describes how Oracle compares values of each datatype. 40
  • ORACLENumber ValuesA larger value is considered greater than a smaller one. All negative numbers are less than zero and allpositive numbers. Thus, -1 is less than 100; -100 is less than -1.Date ValuesA later date is considered greater than an earlier one. For example, the date equivalent of ’29-MAR-1991 is less than that of ’05-JAN-1992 and ’05-JAN-1992 1:35pm’ is greater than ’05-JAN-199210:09am’.Character String ValuesCharacter values are compared using one of these comparison rules:• blank-padded comparison semantics• nonpadded comparison semanticsThe following sections explain these comparison semantics. The results of comparing two charactervalues using different comparison semantics may be different. Table 2-5 shows the results of compar-ing five pairs of character values using each comparison semantic. Usually, the results of blank-paddedand nonpadded comparisons are the same.The last comparison in the table illustrates the differencesbetween the blank-padded and nonpadded comparison semantics. Blank-Padded Nonpadded ab > aa ab > aa ab > a ab > a ab > a ab > a ab = ab ab = ab a = a a > aBlank-Padded Comparison SemanticsIf the two values have different lengths, Oracle first adds blanks to the end of the shorter one so theirlengths are equal. Oracle then compares the values character by character up to the first character thatdiffers. The value with the greater character in the first differing position is considered greater. If twovalues have no differing characters, then they are considered equal. This rule means that two values areequal if they differ only in the number of trailing blanks. Oracle uses blank-padded comparison seman-tics only when both values in the comparison are either expressions of datatype CHAR, NCHAR, textliterals, or values returned by the USER function.Nonpadded Comparison SemanticsOracle compares two values character by character up to the first character that differs. The value withthe greater character in that position is considered greater. If two values of different length are identicalup to the end of the shorter one, the longer value is considered greater. If two values of equal lengthhave no differing characters, then the values are considered equal. Oracle uses nonpadded comparisonsemantics whenever one or both values in the comparison have the datatype VARCHAR2 orNVARCHAR2. 41
  • ORACLESingle CharactersOracle compares single characters according to their numeric values in the database character set. Onecharacter is greater than another if it has a greater numeric value than the other in the character set.Oracle considers blanks to be less than any character, which is true in most character sets.These are some common character sets:• 7-bit ASCII (American Standard Code for Information Interchange)• EBCDIC Code (Extended Binary Coded Decimal Interchange Code)• ISO 8859/1 (International Standards Organization)• JEUC Japan Extended UNIXPortions of the ASCII and EBCDIC character sets appear in Table 2-6 and Table 2-7. Note that upper-case and lowercase letters are not equivalent. Also, note that the numeric values for the characters of acharacter set may not match the linguistic sequence for a particular language.Table 2-6: ASCII Character Set Symbol Decimal value Symbol Decimal value blank 32 ; 59 ! 33 < 60 " 34 = 61 # 35 > 62 $ 36 ? 63 % 37 @ 64 & 38 A-Z 65-90 39 [ 91 ( 40 92 ) 41 ] 93 * 42 ^^ 94 + 43 _ 95 , 44 ` 96 - 45 a-z 97-122 . 46 { 123 / 47 | 124 0-9 48-57 } 125 : 58 ~ 126 42
  • ORACLE Symbol Decimal value Symbol Decimal value blank 64 % 108 ¢ 74 _ 109 . 75 > 110 < 76 ? 111 ( 77 : 122 + 78 # 123 | 79 @ 124 & 80 125 ! 90 = 126 $ 91 " 127 * 92 a-i 129-137 ) 93 j-r 145-153 ; 94 s-z 162-169 ÿ 95 A-I 193-201 - 96 J-R 209-217 / 97 S-Z 226-233Data ConversionGenerally an expression cannot contain values of different datatypes. For example, an expression can-not multiply 5 by 10 and then add ‘JAMES’. However, Oracle supports both implicit and explicitconversion of values from one datatype to another.Implicit Data ConversionOracle automatically converts a value from one datatype to another when such a conversion makessense. Oracle performs conversions in these cases:• When an INSERT or UPDATE statement assigns a value of one datatype to a column of an- other, Oracle converts the value to the datatype of the column.• When you use a SQL function or operator with an argument with a datatype other than the one it accepts, Oracle converts the argument to the accepted datatype.• When you use a comparison operator on values of different datatypes, Oracle converts one of the expressions to the datatype of the other.Example 1The text literal ‘10’ has datatype CHAR. Oracle implicitly converts it to the NUMBER datatype if itappears in a numeric expression as in the following statement:SELECT sal + ‘10’ FROM emp;Example 2When a condition compares a character value and a NUMBER value, Oracle implicitly converts thecharacter value to a NUMBER value, rather than converting the NUMBER value to a character value. 43
  • ORACLEIn the following statement, Oracle implicitly converts ‘7936’ to 7936:SELECT ename FROM emp WHERE empno = ‘7936’;Example 3In the following statement, Oracle implicitly converts ’12-MAR-1993 to a DATE value using thedefault date format ‘DD-MON-YYYY’:SELECT ename FROM emp WHERE hiredate = ’12-MAR-1993;Example 4In the following statement, Oracle implicitly converts the text literal ‘AAAAZ8AABAAABvlAAA’ toa ROWID value:SELECT ename FROM emp WHERE ROWID = ‘AAAAZ8AABAAABvlAAA’;Explicit Data ConversionYou can also explicitly specify datatype conversions using SQL conversion functions. Table 2-8 showsSQL functions that explicitly convert a value from one datatype to anotherTable 2-8 SQL Functions for Datatype Conversion TO: FROM: CHAR NUMBER DATE RAW ROWID CHAR - TO_NUMBER TO_DATE HEXTORAW CHARTOROWID NUMBER TO_CHAR - TO_DATE (number, J) DATE TO_CHAR TO_CHAR - (date,J) RAW RAWTOHEX - ROWID ROWIDTOCHAR -Implicit vs. Explicit Data ConversionOracle recommends that you specify explicit conversions rather than rely on implicit or automaticconversions for these reasons:• SQL statements are easier to understand when you use explicit datatype conversions functions.• Automatic datatype conversion can have a negative impact on performance, especially if the datatype of a column value is converted to that of a constant rather than the other way around. 44
  • ORACLE• Implicit conversion depends on the context in which it occurs and may not work the same way in every case.• Algorithms for implicit conversion are subject to change across software releases and among Oracle products. Behavior of explicit conversions is more predictable.NullsIf a column in a row has no value, then column is said to be null, or to contain a null. Nulls can appearin columns of any datatype that are not restricted by NOT NULL or PRIMARY KEY integrity constraints.Use a null when the actual value is not known or when a value would not be meaningful.Do not use null to represent a value of zero, because they are not equivalent. (Oracle currently treats acharacter value with a length of zero as null. However, this may not continue to be true in futurereleases, and Oracle recommends that you do not treat empty strings the same as NULLs.) Any arithmeticexpression containing a null always evaluates to null. For example, null added to 10 is null. In fact, alloperators (except concatenation) return null when given a null operand.Nulls in SQL FunctionsAll scalar functions (except NVL and TRANSLATE) return null when given a null argument. The NVLfunction can be used to return a value when a null occurs. For example, the expression NVL(COMM,0)returns 0 if COMM is null or the value of COMM if it is not null.Most group functions ignore nulls. For example, consider a query that averages the five values 1000,null, null, null, and 2000. Such a query ignores the nulls and calculates the average to be (1000+2000)/2 = 1500.Nulls with Comparison OperatorsTo test for nulls, use only the comparison operators IS NULL and IS NOT NULL. If you use any otheroperator with nulls and the result depends on the value of the null, the result is UNKNOWN. Becausenull represents a lack of data, a null cannot be equal or unequal to any value or to another null. However,note that Oracle considers two nulls to be equal when evaluating a DECODE expression.Oracle also considers two nulls to be equal if they appear in compound keys. That is, Oracle considersidentical two compound keys containing nulls if all the non-null components of the keys are equal.Nulls in ConditionsA condition that evaluates to UNKNOWN acts almost like FALSE. For example, a SELECT statementwith a condition in the WHERE clause that evaluates to UNKNOWN returns no rows. However, acondition evaluating to UNKNOWN differs from FALSE in that further operations on an UNKNOWNcondition evaluation will evaluate to UNKNOWN. Thus, NOT FALSE evaluates to TRUE, but NOTUNKNOWN evaluates to UNKNOWN. 45
  • ORACLETable 2-9 shows examples of various evaluations involving nulls in conditions. If the conditionsevaluating to UNKNOWN were used in a WHERE clause of a SELECT statement, then no rows wouldbe returned for that query.Table 2-9: Conditions containing Nulls If A is: Condition Evaluates to: 10 a IS NULL FALSE 10 a IS NOT NULL TRUE NULL a IS NULL TRUE NULL a IS NOT NULL FALSE 10 a = NULL UNKNOWN 10 a != NULL UNKNOWN NULL a = NULL UNKNOWN NULL a != NULL UNKNOWN NULL a = 10 UNKNOWN NULL a != 10 UNKNOWNPSEUDOCOLUMNSA pseudocolumn behaves like a table column, but is not actually stored in the table. You can select frompseudocolumns, but you cannot insert, update, or delete their values. This section describes thesepseudocolumns:• CURRVAL and NEXTVAL• LEVEL• ROWID• ROWNUMCURRVAL and NEXTVALA sequence is a schema object that can generate unique sequential values. These values are often usedfor primary and unique keys. You can refer to sequence values in SQL statements with thesepseudocolumns:CURRVAL returns the current value of a sequence.NEXTVAL increments the sequence and returns the next value.You must qualify CURRVAL and NEXTVAL with the name of the sequence:sequence.CURRVALsequence.NEXTVALTo refer to the current or next value of a sequence in the schema of another user, you must have beengranted either SELECT object privilege on the sequence or SELECT ANY SEQUENCE system privi-lege, and you must qualify the sequence with the schema containing it: 46
  • ORACLEschema.sequence.CURRVALschema.sequence.NEXTVALTo refer to the value of a sequence on a remote database, you must qualify the sequence with a completeor partial name of a database link:schema.sequence.CURRVAL@dblinkschema.sequence.NEXTVAL@dblinkWhere to Use Sequence ValuesYou can use CURRVAL and NEXTVAL in these places:• the SELECT list of a SELECT statement that is not contained in a subquery, snapshot, or view• the SELECT list of a subquery in an INSERT statement• the VALUES clause of an INSERT statement• the SET clause of an UPDATE statementYou cannot use CURRVAL and NEXTVAL in these places:• a subquery in a DELETE, SELECT, or UPDATE statement• a view’s query or snapshot’s query• a SELECT statement with the DISTINCT operator• a SELECT statement with a GROUP BY or ORDER BY clause• a SELECT statement that is combined with another SELECT statement with the UNION, IN- TERSECT, or MINUS set operator• the WHERE clause of a SELECT statement• DEFAULT value of a column in a CREATE TABLE or ALTER TABLE statement• the condition of a CHECK constraintAlso, within a single SQL statement that uses CURVAL or NEXTVAL, all referenced LONG columns,updated tables, and locked tables must be located on the same database.How to Use Sequence ValuesWhen you create a sequence, you can define its initial value and the increment between its values. Thefirst reference to NEXTVAL returns the sequence’s initial value. Subsequent references to NEXTVALincrement the sequence value by the defined increment and return the new value. Any reference toCURRVAL always returns the sequence’s current value, which is the value returned by the last refer-ence to NEXTVAL. Note that before you use CURRVAL for a sequence in your session, you must firstinitialize the sequence with NEXTVAL.Within a single SQL statement, Oracle will increment the sequence only once. If a statement containsmore than one reference to NEXTVAL for a sequence, Oracle increments the sequence once and re-turns the same value for all occurrences of NEXTVAL. If a statement contains references to bothCURRVAL and NEXTVAL, Oracle increments the sequence and returns the same value for bothCURRVAL and NEXTVAL regardless of their order within the statement.A sequence can be accessed by many users concurrently with no waiting or locking. 47
  • ORACLEExample 1This example selects the current value of the employee sequence:SELECT empseq.currval FROM DUAL;Example 2This example increments the employee sequence and uses its value for a new employee inserted intothe employee table:INSERT INTO emp VALUES (empseq.nextval, ‘LEWIS’, ‘CLERK’, 7902, SYSDATE, 1200, NULL, 20);Example 3This example adds a new order with the next order number to the master order table. It then addssuborders with this number to the detail order table:INSERT INTO master_order(orderno, customer, orderdate) VALUES (orderseq.nextval, ‘Al’’s Auto Shop’, SYSDATE);INSERT INTO detail_order (orderno, part, quantity) VALUES (orderseq.currval, ‘SPARKPLUG’, 4);INSERT INTO detail_order (orderno, part, quantity) VALUES (orderseq.currval, ‘FUEL PUMP’, 1);INSERT INTO detail_order (orderno, part, quantity) VALUES (orderseq.currval, ‘TAILPIPE’, 2);LEVELFor each row returned by a hierarchical query, the LEVEL pseudocolumn returns 1 for a root node, 2 fora child of a root, and so on. A root node is the highest node within an inverted tree. A child node is anynonroot node. A parent node is any node that has children. A leaf node is any node without children.Figure 2-1 shows the nodes of an inverted tree with their LEVEL valuesFig. 2-1 : Hierarchical TreeTo define a hierarchical relationship in a query, you must use the START WITH and CONNECT BYclauses. 48
  • ORACLEROWIDFor each row in the database, the ROWID pseudocolumn returns a row’s address. ROWID valuescontain information necessary to locate a row:• the data object number of the object• which data block in the datafile• which row in the data block (first row is 0)• which datafile (first file is 1). The file number is relative to the tablespace.Usually, a ROWID value uniquely identifies a row in the database. However, rows in different tablesthat are stored together in the same cluster can have the same ROWID.Values of the ROWID pseudocolumn have the datatype ROWID.ROWID values have several important uses:• They are the fastest way to access a single row.• They can show you how a table’s rows are stored.• They are unique identifiers for rows in a table.You should not use ROWID as a table’s primary key. If you delete and reinsert a row with the Importand Export utilities, for example, its ROWID may change. If you delete a row, Oracle may reassign itsROWID to a new row inserted later.Although you can use the ROWID pseudocolumn in the SELECT and WHERE clauses of a query,these pseudocolumn values are not actually stored in the database. You cannot insert, update, or deletea value of the ROWID pseudocolumn.ExampleThis statement selects the address of all rows that contain data for employees in department 20:SELECT ROWID, ename FROM emp WHERE deptno = 20;ROWID ENAME————————— ———-—-AAAAfSAABAAAClaAAA SMITHAAAAfSAABAAAClaAAD JONESAAAAfSAABAAAClaAAH SCOTTAAAAfSAABAAAClaAAK ADAMSAAAAfSAABAAAClaAAM FORDROWNUMFor each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the orderin which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUMof 1, the second has 2, and so on. 49
  • ORACLEYou can use ROWNUM to limit the number of rows returned by a query, as in this example:SELECT * FROM emp WHERE ROWNUM < 10;Note that conditions testing for ROWNUM values greater than a positive integer are always false. Forexample, this query returns no rows:SELECT * FROM emp WHERE ROWNUM > 1;The first row fetched is assigned a ROWNUM of 1 and makes the condition false. The second row to befetched is now the first row and is also assigned a ROWNUM of 1 and makes the condition false. Allrows subsequently fail to satisfy the condition, so no rows are returned.You can also use ROWNUM to assign unique values to each row of a table, as in this example:UPDATE tabx SET col1 = ROWNUM;Oracle assigns a ROWNUM value to each row as it is retrieved, before rows are sorted for an ORDERBY clause, so an ORDER BY clause normally does not affect the ROWNUM of each row. However, ifan ORDER BY clause causes Oracle to use an index to access the data, Oracle may retrieve the rows ina different order than without the index, so the ROWNUMs may be different than they would bewithout the ORDER BY clause. 50
  • ORACLE SQL - AN INTRODUCTIONCOMPETENCY OBJECTIVESThis chapter covers the following topics v SQL Operators v SQL Functions v SQL Queries 51
  • ORACLE52
  • ORACLE CHAPTER - 3 OPERATORS USED IN SQL LANGUAGEAn operator manipulates individual data items and returns a result. The data items are called operandsor arguments. Operators are represented by special characters or by keywords. For example, themultiplication operator is represented by an asterisk (*) and the operator that tests for nulls is representedby the keywords IS NULL. Tables in this section list SQL operators.ARITHMETIC OPERATORS IN SQLYou can use an arithmetic operator in an expression to negate, add, subtract, multiply, and dividenumeric values. The result of the operation is also a numeric value. Some of these operators are alsoused in date arithmetic. Table 3-2 lists arithmetic operators. Oper Purpose Example ator + or Denotes a positive or negative expression. These SELECT * FROM orders - are unary operators. WHERE qtysold = -1; SELECT * FROM emp WHERE -sal < 0; */ Multiplies, divides. These are binary operators. UPDATE emp SET sal = sal * 1.1; +- Adds, subtracts. These are binary operators. SELECT sal + comm FROM emp WHERE SYSDATE - hiredate > 365; Table 3-2: Arithmetic OperatorsYou are advised not to use two consecutive minus signs with no separation (—) in arithmetic expressionsfor indicating double negation or the subtraction of a negative value. The characters — are used tobegin comments within SQL statements. Two consecutive minus signs should be separated with aspace or a parenthesis. 53
  • ORACLEConcatenation Operator in SQLThe concatenation operator manipulates character strings. Table 3-3 describes the concatenation operator. Operator Purpose Example || Concatenates character SELECT Name is || strings. ename FROM emp; Table 3-3 : Concatenation OperatorThe result of concatenating two character strings is another character string. If both character stringsare of datatype CHAR, the result has datatype CHAR and is limited to 2000 characters. If either stringis of datatype VARCHAR2, the result has datatype VARCHAR2 and is limited to 4000 characters.Trailing blanks in character strings are preserved by concatenation, regardless of the strings’ datatypes.ExampleThis example creates a table with both CHAR and VARCHAR2 columns, inserts values both with andwithout trailing blanks, and then selects these values, concatenating them. Note that for both CHARand VARCHAR2 columns, the trailing blanks are preserved.CREATE TABLE tab1 (col1 VARCHAR2(6), col2 CHAR(6), col3 VARCHAR2(6), col4 CHAR(6) );Table created.INSERT INTO tab1 (col1, col2, col3, col4) VALUES (‘abc’, ‘def ‘, ‘ghi ‘, ‘jkl’);1 row created.SELECT col1||col2||col3||col4 “Concatenation” FROM tab1;Concatenation————————————abcdef ghi jklComparison OperatorsComparison operators compare one expression with another. The result of such a comparison can beTRUE, FALSE, or UNKNOWNEquality test .SELECT * FROM emp WHERE sal = 1500; 54
  • ORACLEInequality test. Some forms of the inequality operator may be unavailable on some platforms.SELECT * FROM emp WHERE sal != 1500;“Greater than” and “less than” tests.SELECT * FROM emp WHERE sal > 1500;SELECT * FROM emp WHERE sal < 1500;“Greater than or equal to” and “less than or equal to” tests.SELECT * FROM emp WHERE sal >= 1500;SELECT * FROM emp WHERE sal <= 1500;IN“Equal to any member of” test. Equivalent to “= ANY”.SELECT * FROM emp WHERE job IN (‘CLERK’,’ANALYST’);SELECT * FROM emp WHERE sal IN (SELECT sal FROM emp WHERE deptno = 30);NOT INEquivalent to “!=ALL”. Evaluates to FALSE if any member of the set is NULL.SELECT * FROM emp WHERE sal NOT IN (SELECT sal FROM emp WHERE deptno = 30);SELECT * FROM emp WHERE job NOT IN (‘CLERK’, ANALYST’);ANYSOMECompares a value to each value in a list or returned by a query. Must be preceded by =, !=, >, <, <=, >=. 55
  • ORACLEEvaluates to FALSE if the query returns no rows.SELECT * FROM emp WHERE sal = ANY (SELECT sal FROM emp WHERE deptno = 30);ALLCompares a value to every value in a list or returned by a query. Must be preceded by =, !=, >, <, <=, >=.Evaluates to TRUE if the query returns no rows.SELECT * FROM emp WHERE sal >= ALL ( 1400, 3000);[NOT]BETWEENx AND y[Not] greater than or equal to x and less than or equal to y.SELECT * FROM emp WHERE sal BETWEEN 2000 AND 3000;EXISTSTRUE if a subquery returns at least one row.SELECT ename, deptno FROM dept WHERE EXISTS (SELECT * FROM emp WHERE dept.deptno = emp.deptno);x [NOT]LIKE y[ESCAPE‘z’]TRUE if x does [not] match the pattern y. Within y, the character “%” matches any string of zero ormore characters except null. The character “_” matches any single character. Any character, exceptingpercent (%) and underbar (_) may follow ESCAPE; a wildcard character is treated as a literal if precededby the character designated as the escape character.See “LIKE Operator”. 56
  • ORACLESELECT * FROM tab1 WHERE col1 LIKE ‘A_C/%E%’ ESCAPE ‘/’;IS[NOT]NULLTests for nulls. This is the only operator that you should use to test for nulls. See “Nulls”.SELECT ename, deptno FROM emp WHERE comm IS NULL;Additional information on the NOT IN and LIKE operators appears in the sections that follow.NOT IN OperatorIf any item in the list following a NOT IN operation is null, all rows evaluate to UNKNOWN (and norows are returned). For example, the following statement returns the string ‘TRUE’ for each row:SELECT ‘TRUE’ FROM emp WHERE deptno NOT IN (5,15);However, the following statement returns no rows:SELECT ‘TRUE’ FROM emp WHERE deptno NOT IN (5,15,null);The above example returns no rows because the WHERE clause condition evaluates to:deptno != 5 AND deptno != 15 AND deptno != nullBecause all conditions that compare a null result in a null, the entire expression results in a null. Thisbehavior can easily be overlooked, especially when the NOT IN operator references a subquery.LIKE OperatorThe LIKE operator is used in character string comparisons with pattern matching. The syntax for acondition using the LIKE operator is shown in this diagram:where:char1is a value to be compared with a pattern. This value can have datatype CHAR or VARCHAR2. 57
  • ORACLENOTlogically inverts the result of the condition, returning FALSE if the condition evaluates to TRUE andTRUE if it evaluates to FALSE.char2is the pattern to which char1 is compared. The pattern is a value of datatype CHAR or VARCHAR2 andcan contain the special pattern matching characters % and _.ESCAPEidentifies a single character as the escape character. The escape character can be used to cause Oracle tointerpret % or _ literally, rather than as a special character, in the pattern.If you wish to search for strings containing an escape character, you must specify this character twice.For example, if the escape character is ‘/’, to search for the string ‘client/server’, you must specify,‘client//server’.While the equal (=) operator exactly matches one character value to another, the LIKE operator matchesa portion of one character value to another by searching the first value for the pattern specified by thesecond. Note that blank padding is not used for LIKE comparisons.With the LIKE operator, you can compare a value to a pattern rather than to a constant. The pattern canonly appear after the LIKE keyword. For example, you can issue the following query to find the salariesof all employees with names beginning with ‘SM’:SELECT sal FROM emp WHERE ename LIKE ‘SM%’;The following query uses the = operator, rather than the LIKE operator, to find the salaries of allemployees with the name ‘SM%’:SELECT sal FROM emp WHERE ename = ‘SM%’;The following query finds the salaries of all employees with the name ‘SM%’. Oracle interprets ‘SM%’as a text literal, rather than as a pattern, because it precedes the LIKE operator:SELECT sal FROM emp WHERE ‘SM%’ LIKE ename;Patterns usually use special characters that Oracle matches with different characters in the value:An underscore (_) in the pattern matches exactly one character (as opposed to one byte in a multibytecharacter set) in the value. 58
  • ORACLEA percent sign (%) in the pattern can match zero or more characters (as opposed to bytes in a multibytecharacter set) in the value. Note that the pattern ‘%’ cannot match a null.Case Sensitivity and Pattern MatchingCase is significant in all conditions comparing character expressions including the LIKE and equality(=) operators. You can use the UPPER() function to perform a case-insensitive match, as in this condition:UPPER(ename) LIKE ‘SM%’Pattern Matching on Indexed ColumnsWhen LIKE is used to search an indexed column for a pattern, Oracle can use the index to improve thestatement’s performance if the leading character in the pattern is not “%” or “_”. In this case, Oracle canscan the index by this leading character. If the first character in the pattern is “%” or “_”, the indexcannot improve the query’s performance because Oracle cannot scan the index.Example 1This condition is true for all ENAME values beginning with “MA”:ename LIKE ‘MA%’All of these ENAME values make the condition TRUE:MARTIN, MA, MARK, MARYCase is significant, so ENAME values beginning with “Ma,” “ma,” and “mA” make the conditionFALSE.Example 2Consider this condition:ename LIKE ‘SMITH_’This condition is true for these ENAME values:SMITHE, SMITHY, SMITHSThis condition is false for ‘SMITH’, since the special character “_” must match exactly one characterof the ENAME value.ESCAPE OptionYou can include the actual characters “%” or “_” in the pattern by using the ESCAPE option. TheESCAPE option identifies the escape character. If the escape character appears in the pattern before thecharacter “%” or “_” then Oracle interprets this character literally in the pattern, rather than as a specialpattern matching character. 59
  • ORACLEExample:To search for any employees with the pattern ‘A_B’ in their name:SELECT ename FROM emp WHERE ename LIKE ‘%A_B%’ ESCAPE ‘’;The ESCAPE option identifies the backslash () as the escape character. In the pattern, the escapecharacter precedes the underscore (_). This causes Oracle to interpret the underscore literally, ratherthan as a special pattern matching character.Patterns Without %If a pattern does not contain the “%” character, the condition can be TRUE only if both operands havethe same length.Example:Consider the definition of this table and the values inserted into it:CREATE TABLE freds (f CHAR(6), v VARCHAR2(6));INSERT INTO freds VALUES (‘FRED’, ‘FRED’);Because Oracle blank-pads CHAR values, the value of F is blank-padded to 6 bytes. V is not blank-padded and has length 4.Logical OperatorsA logical operator combines the results of two component conditions to produce a single result basedon them or to invert the result of a single condition. Table 3-5 lists logical operators.Table 3-5 Logical OperatorsOperator Function ExampleNOTReturns TRUE if the following condition is FALSE. Returns FALSE if it is TRUE. If it is UNKNOWN,it remains UNKNOWN.SELECT * FROM emp WHERE NOT (job IS NULL);SELECT * FROM emp WHERE NOT (sal BETWEEN 1000 AND 2000);ANDReturns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE. Otherwisereturns UNKNOWN. SELECT * FROM emp 60
  • ORACLE WHERE job = ‘CLERK’ AND deptno = 10;ORReturns TRUE if either component condition is TRUE. Returns FALSE if both are FALSE. Otherwisereturns UNKNOWN.SELECT * FROM emp WHERE job = ‘CLERK’ OR deptno = 10;For example, in the WHERE clause of the following SELECT statement, the AND logical operator isused to ensure that only those hired before 1984 and earning more than $1000 a month are returned:SELECT * FROM emp WHERE hiredate < TO_DATE(’01-JAN-1984, ‘DD-MON-YYYY’) AND sal > 1000;NOT OperatorAND OperatorOR OperatorSet OperatorsSet operators combine the results of two component queries into a single result. Queries containing setoperators are called compound queries. Table 3-9 lists SQL set operators.UNIONAll rows selected by either query.UNION ALLAll rows selected by either query, including all duplicates.INTERSECTAll distinct rows selected by both queries.MINUSAll distinct rows selected by the first query but not the second.All set operators have equal precedence. If a SQL statement contains multiple set operators, Oracleevaluates them from the left to right if no parentheses explicitly specify another order. To comply withemerging SQL standards, a future release of Oracle will give the INTERSECT operator greater precedencethan the other set operators. Therefore, you should use parentheses to specify order of evaluation inqueries that use the INTERSECT operator with other set operators. 61
  • ORACLEThe corresponding expressions in the select lists of the component queries of a compound query mustmatch in number and datatype. If component queries select character data, the datatype of the returnvalues are determined as follows:If both queries select values of datatype CHAR, the returned values have datatype CHAR.If either or both of the queries select values of datatype VARCHAR2, the returned values have datatypeVARCHAR2.ExamplesConsider these two queries and their results:SELECT part FROM orders_list1;PART—————SPARKPLUGFUEL PUMPFUEL PUMPTAILPIPESELECT part FROM orders_list2;PART—————CRANKSHAFTTAILPIPETAILPIPEThe following examples combine the two query results with each of the set operators.UNION ExampleThe following statement combines the results with the UNION operator, which eliminates duplicateselected rows. This statement shows how datatype must match when columns do not exist in one or theother table:SELECT part, partnum, to_date(null) date_in FROM orders_list1UNIONSELECT part, to_null(null), date_in FROM orders_list2; 62
  • ORACLEPART PARTNUM DATE_IN————— ——— ————SPARKPLUG 3323165SPARKPLUG 10/24/98FUEL PUMP 3323162FUEL PUMP 12/24/99TAILPIPE 1332999TAILPIPE 01/01/01CRANKSHAFT 9394991CRANKSHAFT 09/12/02SELECT part FROM orders_list1UNIONSELECT part FROM orders_list2;PART—————SPARKPLUGFUEL PUMPTAILPIPECRANKSHAFTUNION ALL ExampleThe following statement combines the results with the UNION ALL operator, which does not eliminateduplicate selected rows:SELECT part FROM orders_list1UNION ALLSELECT part FROM orders_list2;PART—————SPARKPLUGFUEL PUMPFUEL PUMPTAILPIPECRANKSHAFTTAILPIPETAILPIPE 63
  • ORACLENote that the UNION operator returns only distinct rows that appear in either result, while the UNIONALL operator returns all rows. A PART value that appears multiple times in either or both queries (suchas ‘FUEL PUMP’) is returned only once by the UNION operator, but multiple times by the UNIONALL operator.INTERSECT ExampleThe following statement combines the results with the INTERSECT operator which returns only thoserows returned by both queries:SELECT part FROM orders_list1INTERSECTSELECT part FROM orders_list2;PART—————TAILPIPEMINUS ExampleThe following statement combines results with the MINUS operator, which returns only rows returnedby the first query but not by the second:SELECT part FROM orders_list1MINUSSELECT part FROM orders_list2;PART—————SPARKPLUGFUEL PUMPOther OperatorsTable 3-10 lists other SQL operators.(+)Indicates that the preceding column is the outer join column in a join. See “Outer Joins”.SELECT ename, dname FROM emp, dept WHERE dept.deptno = emp.deptno(+); 64
  • ORACLEPRIOREvaluates the following expression for the parent row of the current row in a hierarchical, or tree-structured, query. In such a query, you must use this operator in the CONNECT BY clause to define therelationship between parent and child rows. You can also use this operator in other parts of a SELECTstatement that performs a hierarchical query. The PRIOR operator is a unary operator and has the sameprecedence as the unary + and - arithmetic operators. See “Hierarchical Queries”.SELECT empno, ename, mgr FROM emp CONNECT BY PRIOR empno = mgr;SQL FunctionsA SQL function is similar to an operator in that it manipulates data items and returns a result. SQLfunctions differ from operators in the format in which they appear with their arguments. This formatallows them to operate on zero, one, two, or more arguments:function(argument, argument, ...)If you call a SQL function with an argument of a datatype other than the datatype expected by the SQLfunction, Oracle implicitly converts the argument to the expected datatype before performing the SQLfunction. See “Data Conversion”.If you call a SQL function with a null argument, the SQL function automatically returns null. The onlySQL functions that do not follow this rule are CONCAT, DECODE, DUMP, NVL, and REPLACE.SQL functions should not be confused with user functions written in PL/SQL. User functions aredescribed in “User Functions”.In the syntax diagrams for SQL functions, arguments are indicated with their datatypes following theconventions described in “Syntax Diagrams and Notation” in the Preface of this reference.SQL functions are of these general types: single-row (or scalar) functions group (or aggregate) functionsThe two types of SQL functions differ in the number of rows upon which they act. A single-row functionreturns a single result row for every row of a queried table or view; a group function returns a singleresult row for a group of queried rows.Single-row functions can appear in select lists (if the SELECT statement does not contain a GROUPBY clause), WHERE clauses, START WITH clauses, and CONNECT BY clauses. 65
  • ORACLEGroup functions can appear in select lists and HAVING clauses. If you use the GROUP BY clause in aSELECT statement, Oracle divides the rows of a queried table or view into groups. In a query containinga GROUP BY clause, all elements of the select list must be expressions from the GROUP BY clause,expressions containing group functions, or constants. Oracle applies the group functions in the selectlist to each group of rows and returns a single result row for each group.If you omit the GROUP BY clause, Oracle applies group functions in the select list to all the rows in thequeried table or view. You use group functions in the HAVING clause to eliminate groups from theoutput based on the results of the group functions, rather than on the values of the individual rows of thequeried table or view. For more information on the GROUP BY and HAVING clauses, see the GROUPBY Clause and the HAVING Clause.In the sections that follow, functions are grouped by the datatypes of their arguments and return values.Number FunctionsNumber functions accept numeric input and return numeric values. This section lists the SQL numberfunctions. Most of these functions return values that are accurate to 38 decimal digits. The transcendentalfunctions COS, COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, and TANH are accurate to 36 decimaldigits. The transcendental functions ACOS, ASIN, ATAN, and ATAN2 are accurate to 30 decimaldigits.ABSPurposeReturns the absolute value of n.ExampleSELECT ABS(-15) “Absolute” FROM DUAL;Absolute————— 15ACOSPurpose Returns the arc cosine of n. Inputs are in the range of -1 to 1, and outputs are in the range of 0 to andare expressed in radians.ExampleSELECT ACOS(.3)”Arc_Cosine” FROM DUAL;Arc_Cosine—————1.26610367 66
  • ORACLEASINPurposeReturns the arc sine of n. Inputs are in the range of -1 to 1, and outputs are in the range of -/2 to /2 andare expressed in radians.ExampleSELECT ASIN(.3) “Arc_Sine” FROM DUAL;Arc_Sine—————.304692654ATANPurposeReturns the arc tangent of n. Inputs are in an unbounded range, and outputs are in the range of -/2 to /2and are expressed in radians.ExampleSELECT ATAN(.3) “Arc_Tangent” FROM DUAL;Arc_Tangent—————.291456794ATAN2Purpose Returns the arc tangent of n and m. Inputs are in an unbounded range, and outputs are in the range of -to , depending on the signs of n and m, and are expressed in radians. Atan2(n,m) is the same as atan2(n/m)ExampleSELECT ATAN2(.3, .2) “Arc_Tangent2” FROM DUAL;Arc_Tangent2——————.982793723CEILPurposeReturns smallest integer greater than or equal to n.ExampleSELECT CEIL(15.7) “Ceiling” FROM DUAL;Ceiling————— 16 67
  • ORACLECOSPurposeReturns the cosine of n (an angle expressed in radians).ExampleSELECT COS(180 * 3.14159265359/180)“Cosine of 180 degrees” FROM DUAL;Cosine of 180 degrees——————————- -1COSHPurposeReturns the hyperbolic cosine of n.ExampleSELECT COSH(0) “Hyperbolic cosine of 0” FROM DUAL;Hyperbolic cosine of 0————————— 1EXPPurposeReturns e raised to the nth power; e = 2.71828183 ...ExampleSELECT EXP(4) “e to the 4th power” FROM DUAL;e to the 4th power————————— 54.59815FLOORPurposeReturns largest integer equal to or less than n.ExampleSELECT FLOOR(15.7) “Floor” FROM DUAL; Floor————— 15 68
  • ORACLELNPurposeReturns the natural logarithm of n, where n is greater than 0.ExampleSELECT LN(95) “Natural log of 95” FROM DUAL; Natural log of 95————————— 4.55387689LOGPurposeReturns the logarithm, base m, of n. The base m can be any positive number other than 0 or 1 and n canbe any positive number.ExampleSELECT LOG(10,100) “Log base 10 of 100” FROM DUAL; Log base 10 of 100————————— 2MODSyntaxMOD(m,n)PurposeReturns remainder of m divided by n. Returns m if n is 0.ExampleSELECT MOD(11,4) “Modulus” FROM DUAL; Modulus————— 3This function behaves differently from the classical mathematical modulus function when m is negative.The classical modulus can be expressed using the MOD function with this formula:m - n * FLOOR(m/n)The following statement illustrates the difference between the MOD function and the classical modulus:SELECT m, n, MOD(m, n),m - n * FLOOR(m/n) “Classical Modulus” FROM test_mod_table; 69
  • ORACLE M N MOD(M,N) Classical Modulus 11 4 3 3 11 –4 3 –1 –11 4 –3 1 –11 –4 –3 –3POWERPurposeReturns m raised to the nth power. The base m and the exponent n can be any numbers, but if m isnegative, n must be an integer.ExampleSELECT POWER(3,2) “Raised” FROM DUAL; Raised————— 9ROUNDSyntax ROUND(n[,m])PurposeReturns n rounded to m places right of the decimal point; if m is omitted, to 0 places. m can be negativeto round off digits left of the decimal point. m must be an integer.Example 1SELECT ROUND(15.193,1) “Round” FROM DUAL; Round————— 15.2Example 2SELECT ROUND(15.193,-1) “Round” FROM DUAL; Round————— 20SIGNSyntax SIGN(n)PurposeIf n<0, the function returns -1; if n=0, the function returns 0; if n>0, the function returns 1. 70
  • ORACLEExampleSELECT SIGN(-15) “Sign” FROM DUAL; Sign————— -1SINPurposeReturns the sine of n (an angle expressed in radians).ExampleSELECT SIN(30 * 3.14159265359/180)“Sine of 30 degrees” FROM DUAL; Sine of 30 degrees————————— .5SINHPurposeReturns the hyperbolic sine of n.ExampleSELECT SINH(1) “Hyperbolic sine of 1” FROM DUAL; Hyperbolic sine of 1—————————— 1.17520119SQRTPurposeReturns square root of n. The value n cannot be negative. SQRT returns a “real” result.ExampleSELECT SQRT(26) “Square root” FROM DUAL;Square root—————– 5.09901951TANPurposeReturns the tangent of n (an angle expressed in radians). 71
  • ORACLEExampleSELECT TAN(135 * 3.14159265359/180)“Tangent of 135 degrees” FROM DUAL; Tangent of 135 degrees——————————— -1TANHPurposeReturns the hyperbolic tangent of n.ExampleSELECT TANH(.5) “Hyperbolic tangent of .5” FROM DUAL; Hyperbolic tangent of .5———————————— .462117157TRUNCPurposeReturns n truncated to m decimal places; if m is omitted, to 0 places. m can be negative to truncate(make zero) m digits left of the decimal point.ExamplesSELECT TRUNC(15.79,1) “Truncate” FROM DUAL;Truncate————— 15.7SELECT TRUNC(15.79,-1) “Truncate” FROM DUAL;Truncate————— 10Character FunctionsSingle-row character functions accept character input and can return either character or number values.Character Functions Returning Character ValuesThis section lists character functions that return character values. Unless otherwise noted, these functionsall return values with the datatype VARCHAR2 and are limited in length to 4000 bytes. Functions thatreturn values of datatype CHAR are limited in length to 2000 bytes. If the length of the return value 72
  • ORACLEexceeds the limit, Oracle truncates it and returns the result without an error message.CHRSyntax CHR(n [USING NCHAR_CS])PurposeReturns the character having the binary equivalent to n in either the database character set or the nationalcharacter set.If the USING NCHAR_CS clause is not specified, this function returns the character having the binaryequivalent to n as a VARCHAR2 value in the database character set.If the USING NCHAR_CS clause is specified, this function returns the character having the binaryequivalent to n as a NVARCHAR2 value in the national character set.Example 1SELECT CHR(67)||CHR(65)||CHR(84) “Dog” FROM DUAL;Dog–––—CATExample 2SELECT CHR(16705 USING NCHAR_CS) FROM DUAL; C––ACONCATSyntax CONCAT(char1, char2)PurposeReturns char1 concatenated with char2. This function is equivalent to the concatenation operator (||).For information on this operator, see “Concatenation Operator”.ExampleThis example uses nesting to concatenate three character strings:SELECT CONCAT( CONCAT(ename, ‘ is a ‘), job) “Job”FROM empWHERE empno = 7900; 73
  • ORACLE Job————————-JAMES is a CLERKINITCAPPurposeReturns char, with the first letter of each word in uppercase, all other letters in lowercase. Words aredelimited by white space or characters that are not alphanumeric.ExampleSELECT INITCAP(‘the soap’) “Capitals” FROM DUAL;Capitals————-The SoapLOWERPurposeReturns char, with all letters lowercase. The return value has the same datatype as the argument char(CHAR or VARCHAR2).ExampleSELECT LOWER(‘MR. SCOTT MCMILLAN’) “Lowercase” FROM DUAL; Lowercase—————————— mr. scott mcmillanLPADPurposeReturns char1, left-padded to length n with the sequence of characters in char2; char2 defaults to asingle blank. If char1 is longer than n, this function returns the portion of char1 that fits in n.The argument n is the total length of the return value as it is displayed on your terminal screen. In mostcharacter sets, this is also the number of characters in the return value. However, in some multibytecharacter sets, the display length of a character string can differ from the number of characters in thestring.ExampleSELECT LPAD(‘Page 1’,15,’*.’) “LPAD example” FROM DUAL;LPAD example———————-*.*.*.*.*Page 1 74
  • ORACLELTRIMSyntax LTRIM(char [,set])PurposeRemoves characters from the left of char, with all the leftmost characters that appear in set removed; setdefaults to a single blank. Oracle begins scanning char from its first character and removes all charactersthat appear in set until reaching a character not in set and then returns the result.ExampleSELECT LTRIM(‘xyxXxyLAST WORD’,’xy’) “LTRIM example” FROM DUAL;LTRIM exampl——————XxyLAST WORDNLS_INITCAPPurposeReturns char, with the first letter of each word in uppercase, all other letters in lowercase. Words aredelimited by white space or characters that are not alphanumeric. The value of ‘nlsparams’ can havethis form:‘NLS_SORT = sort’where sort is either a linguistic sort sequence or BINARY. The linguistic sort sequence handles speciallinguistic requirements for case conversions. Note that these requirements can result in a return valueof a different length than the char. If you omit ‘nlsparams’, this function uses the default sort sequencefor your session.ExampleSELECT NLS_INITCAP (‘ijsland’, ‘NLS_SORT = XDutch’) “Capitalized” FROM DUAL;Capital———–IJslandNLS_LOWERSyntax NLS_LOWER(char [, ‘nlsparams’] )PurposeReturns char, with all letters lowercase. The ‘nlsparams’ can have the same form and serve the samepurpose as in the NLS_INITCAP function. 75
  • ORACLEExampleSELECT NLS_LOWER (‘CITTA’’’, ‘NLS_SORT = XGerman’) “Lowercase” FROM DUAL;Lower–––––cittáNLS_UPPERSyntax NLS_UPPER(char [, ‘nlsparams’] )PurposeReturns char, with all letters uppercase. The ‘nlsparams’ can have the same form and serve the samepurpose as in the NLS_INITCAP function.ExampleSELECT NLS_UPPER (‘groe’, ‘NLS_SORT = XGerman’) “Uppercase” FROM DUAL;Upper——–GROSSREPLACESyntax REPLACE(char,search_string[,replacement_string])PurposeReturns char with every occurrence of search_string replaced with replacement_string. Ifreplacement_string is omitted or null, all occurrences of search_string are removed. If search_string isnull, char is returned. This function provides a superset of the functionality provided by the TRANSLATEfunction. TRANSLATE provides single-character, one-to-one substitution. REPLACE allows you tosubstitute one string for another as well as to remove character strings.ExampleSELECT REPLACE(‘JACK and JUE’,’J’,’BL’) “Changes” FROM DUAL;Changes———————BLACK and BLUE 76
  • ORACLERPADSyntax RPAD(char1, n [,char2])PurposeReturns char1, right-padded to length n with char2, replicated as many times as necessary; char2 defaultsto a single blank. If char1 is longer than n, this function returns the portion of char1 that fits in n.The argument n is the total length of the return value as it is displayed on your terminal screen. In mostcharacter sets, this is also the number of characters in the return value. However, in some multibytecharacter sets, the display length of a character string can differ from the number of characters in thestring.ExampleSELECT RPAD(‘MORRISON’,12,’ab’) “RPAD example” FROM DUAL;RPAD example————————–MORRISONababRTRIMSyntax RTRIM(char [,set]PurposeReturns char, with all the rightmost characters that appear in set removed; set defaults to a single blank.RTRIM works similarly to LTRIM.ExampleSELECT RTRIM(‘BROWNINGyxXxy’,’xy’) “RTRIM e.g.” FROM DUAL;RTRIM e.g—————––BROWNINGyxXSOUNDEXSyntax SOUNDEX(char)PurposeReturns a character string containing the phonetic representation of char. This function allows you tocompare words that are spelled differently, but sound alike in English. 77
  • ORACLEThe phonetic representation is defined in The Art of Computer Programming, Volume 3: Sorting andSearching, by Donald E. Knuth, as follows:Retain the first letter of the string and remove all other occurrences of the following letters: a, e, h, i, o,u, w, y.Assign numbers to the remaining letters (after the first) as follows:b, f, p, v = 1c, g, j, k, q, s, x, z = 2d, t = 3l=4m, n = 5r=6If two or more letters with the same assigned number are adjacent, remove all but the first.Return the first four bytes padded with 0.ExampleSELECT ename FROM emp WHERE SOUNDEX(ename) = SOUNDEX(‘SMYTHE’);ENAME—————SMITHSUBSTRSyntax SUBSTR(char, m [,n])PurposeReturns a portion of char, beginning at character m, n characters long. If m is 0, it is treated as 1. If m ispositive, Oracle counts from the beginning of char to find the first character. If m is negative, Oraclecounts backwards from the end of char. If n is omitted, Oracle returns all characters to the end of char.If n is less than 1, a null is returned.Floating-point numbers passed as arguments to substr are automatically converted to integers.Example 1SELECT SUBSTR(‘ABCDEFG’,3.1,4) “Subs” FROM DUAL;Subs——CDEF 78
  • ORACLEExample 2SELECT SUBSTR(‘ABCDEFG’,-5,4) “Subs” FROM DUAL;Subs——CDEFSUBSTRBSyntax SUBSTR(char, m [,n])PurposeThe same as SUBSTR, except that the arguments m and n are expressed in bytes, rather than in characters.For a single-byte database character set, SUBSTRB is equivalent to SUBSTR.Floating-point numbers passed as arguments to substrb are automatically converted to integers.ExampleAssume a double-byte database character set:SELECT SUBSTRB(‘ABCDEFG’,5,4.2) “Substring with bytes” FROM DUAL;Substring with bytes————————CDTRANSLATESyntax TRANSLATE(char, from, to)PurposeReturns char with all occurrences of each character in from replaced by its corresponding character into. Characters in char that are not in from are not replaced. The argument from can contain morecharacters than to. In this case, the extra characters at the end of from have no corresponding charactersin to. If these extra characters appear in char, they are removed from the return value. You cannot use anempty string for to to remove all characters in from from the return value. Oracle interprets the emptystring as null, and if this function has a null argument, it returns null. 79
  • ORACLEExample 1The following statement translates a license number. All letters ‘ABC...Z’ are translated to ‘X’ and alldigits ‘012 . . . 9’ are translated to ‘9’:SELECT TRANSLATE(‘2KRW229’,‘0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ’,‘9999999999XXXXXXXXXXXXXXXXXXXXXXXXXX’) “License” FROM DUAL; License————9XXX999Example 2The following statement returns a license number with the characters removed and the digits remaining:SELECT TRANSLATE(‘2KRW229’,‘0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ’,‘0123456789’)“Translate example” FROM DUAL;Translate example———————–2229UPPERSyntax UPPER(char)PurposeReturns char, with all letters uppercase. The return value has the same datatype as the argument char.ExampleSELECT UPPER(‘Large’) “Uppercase” FROM DUAL;Upper——–LARGECharacter Functions Returning Number ValuesThis section lists character functions that return number values.ASCIISyntax ASCII(char) 80
  • ORACLEPurposeReturns the decimal representation in the database character set of the first character of char. If yourdatabase character set is 7-bit ASCII, this function returns an ASCII value. If your database characterset is EBCDIC Code Page 500, this function returns an EBCDIC value. Note that there is no similarEBCDIC character function.ExampleSELECT ASCII(‘Q’) FROM DUAL;ASCII(‘Q’)————— 81INSTRSyntaxINSTR (char1,char2 [,n[,m]])PurposeSearches char1 beginning with its nth character for the mth occurrence of char2 and returns the positionof the character in char1 that is the first character of this occurrence. If n is negative, Oracle counts andsearches backward from the end of char1. The value of m must be positive. The default values of bothn and m are 1, meaning Oracle begins searching at the first character of char1 for the first occurrence ofchar2. The return value is relative to the beginning of char1, regardless of the value of n, and is expressedin characters. If the search is unsuccessful (if char2 does not appear m times after the nth character ofchar1) the return value is 0.Example 1SELECT INSTR(‘CORPORATE FLOOR’,’OR’, 3, 2) “Instring” FROM DUAL; Instring————— 14Example 2SELECT INSTR(‘CORPORATE FLOOR’,’OR’, -3, 2)“Reversed Instring” FROM DUAL;Reversed Instring———————— 2INSTRBSyntax INSTRB(char1,char2[,n[,m]]) 81
  • ORACLEPurposeThe same as INSTR, except that n and the return value are expressed in bytes, rather than in characters.For a single-byte database character set, INSTRB is equivalent to INSTR.ExampleThis example assumes a double-byte database character set.SELECT INSTRB(‘CORPORATE FLOOR’,’OR’,5,2)“Instring in bytes”FROM DUAL;Instring in bytes———————— 27LENGTHSyntax LENGTH(char)PurposeReturns the length of char in characters. If char has datatype CHAR, the length includes all trailingblanks. If char is null, this function returns null.ExampleSELECT LENGTH(‘CANDIDE’) “Length in characters”FROM DUAL;Length in characters————————— 7LENGTHBSyntax LENGTHB(char)PurposeReturns the length of char in bytes. If char is null, this function returns null. For a single-byte databasecharacter set, LENGTHB is equivalent to LENGTH.ExampleThis example assumes a double-byte database character set.SELECT LENGTHB (‘CANDIDE’) “Length in bytes” FROM DUAL;Length in bytes——————— 14 82
  • ORACLENLSSORTSyntax NLSSORT(char [, ‘nlsparams’])PurposeReturns the string of bytes used to sort char. The value of ‘nlsparams’ can have the form‘NLS_SORT = sort’where sort is a linguistic sort sequence or BINARY. If you omit ‘nlsparams’, this function uses thedefault sort sequence for your session. If you specify BINARY, this function returns char.ExampleThis function can be used to specify comparisons based on a linguistic sort sequence rather on thebinary value of a string:SELECT ename FROM emp WHERE NLSSORT (ename, ‘NLS_SORT = German’) > NLSSORT (‘S’, ‘NLS_SORT = German’) ORDER BY ename;ENAME—————SCOTTSMITHTURNERWARDDate FunctionsDate functions operate on values of the DATE datatype. All date functions return a value of DATEdatatype, except the MONTHS_BETWEEN function, which returns a number.ADD_MONTHSSyntax ADD_MONTHS(d,n)PurposeReturns the date d plus n months. The argument n can be any integer. If d is the last day of the month orif the resulting month has fewer days than the day component of d, then the result is the last day of theresulting month. Otherwise, the result has the same day component as d.ExampleSELECT TO_CHAR( ADD_MONTHS(hiredate,1), ‘DD-MON-YYYY’) “Next month” FROM emp WHERE ename = ‘SMITH’; 83
  • ORACLENext Month—————–17-JAN-1981LAST_DAYSyntax LAST_DAY(d)PurposeReturns the date of the last day of the month that contains d. You might use this function to determinehow many days are left in the current month.Example 1SELECT SYSDATE, LAST_DAY(SYSDATE) “Last”, LAST_DAY(SYSDATE) - SYSDATE “Days Left” FROM DUAL;SYSDATE Last Days Left———— ———— —————23-OCT-97 31-OCT-97 8Example 2SELECT TO_CHAR( ADD_MONTHS( LAST_DAY(hiredate),5), ‘DD-MON-YYYY’) “Five months” FROM emp WHERE ename = ‘MARTIN’;Five months—————–28-FEB-1982MONTHS_BETWEENSyntax MONTHS_BETWEEN(d1, d2)PurposeReturns number of months between dates d1 and d2. If d1 is later than d2, result is positive; if earlier,negative. If d1 and d2 are either the same days of the month or both last days of months, the result isalways an integer; otherwise Oracle calculates the fractional portion of the result based on a 31-daymonth and considers the difference in time components of d1 and d2. 84
  • ORACLEExampleSELECT MONTHS_BETWEEN (TO_DATE(’02-02-1995,’MM-DD-YYYY’), TO_DATE(’01-01-1995,’MM-DD-YYYY’) ) “Months” FROM DUAL; Months—————1.03225806ROUNDSyntax ROUND(d[,fmt])PurposeReturns d rounded to the unit specified by the format model fmt. If you omit fmt, d is rounded to thenearest day. See “ROUND and TRUNC” for the permitted format models to use in fmt.ExampleSELECT ROUND (TO_DATE (’27-OCT-92),’YEAR’) “New Year” FROM DUAL;New Year————-01-JAN-93SYSDATESyntax SYSDATEPurposeReturns the current date and time. Requires no arguments. In distributed SQL statements, this functionreturns the date and time on your local database. You cannot use this function in the condition of aCHECK constraint.ExampleSELECT TO_CHAR (SYSDATE, ‘MM-DD-YYYY HH24:MI:SS’)”NOW” FROM DUAL;NOW—————————10-29-1993 20:27:11TRUNCSyntax 1TRUNC(d,[fmt]) 85
  • ORACLEPurposeReturns d with the time portion of the day truncated to the unit specified by the format model fmt. If youomit fmt, d is truncated to the nearest day. See “ROUND and TRUNC” for the permitted format modelsto use in fmt.ExampleSELECT TRUNC(TO_DATE(’27-OCT-92,’DD-MON-YY’), ‘YEAR’) “New Year” FROM DUAL;New Year————01-JAN-92CHARTOROWIDSyntaxCHARTOROWID(char)PurposeConverts a value from CHAR or VARCHAR2 datatype to ROWID datatype.ExampleSELECT ename FROM emp WHERE ROWID = CHARTOROWID(‘AAAAfZAABAAACp8AAO’);ENAME————LEWISCONVERTSyntaxCONVERT(char, dest_char_set [,source_char_set] )PurposeConverts a character string from one character set to another.The char argument is the value to be converted.The dest_char_set argument is the name of the character set to which char is converted.The source_char_set argument is the name of the character set in which char is stored in the database.The default value is the database character set.Both the destination and source character set arguments can be either literals or columns containing thename of the character set. 86
  • ORACLEFor complete correspondence in character conversion, it is essential that the destination character setcontains a representation of all the characters defined in the source character set. Where a characterdoes not exist in the destination character set, a replacement character appears. Replacement characterscan be defined as part of a character set definition.ExampleSELECT CONVERT(‘Groß’, ‘US7ASCII’, ‘WE8HP’)“Conversion” FROM DUAL;Conversion—————GrossCommon character sets include:US7ASCIIWE8DECWE8HPF7DECWE8EBCDIC500WE8PC850WE8ISO8859P1US 7-bit ASCII character setDEC West European 8-bit character setHP West European Laserjet 8-bit character setDEC French 7-bit character setIBM West European EBCDIC Code Page 500IBM PC Code Page 850ISO 8859-1 West European 8-bit character setHEXTORAWSyntax HEXTORAW(char)PurposeConverts char containing hexadecimal digits to a raw value.ExampleINSERT INTO graphics (raw_column)SELECT HEXTORAW(‘7D’) FROM DUAL;RAWTOHEXSyntax RAWTOHEX(raw)PurposeConverts raw to a character value containing its hexadecimal equivalent. 87
  • ORACLEExampleSELECT RAWTOHEX(raw_column) “Graphics” FROM graphics;Graphics————7DROWIDTOCHARSyntax ROWIDTOCHAR(rowid)PurposeConverts a ROWID value to VARCHAR2 datatype. The result of this conversion is always 18 characterslong.ExampleSELECT ROWID FROM offices WHERE ROWIDTOCHAR(ROWID) LIKE ‘%Br1AAB%’;ROWID—————————––––––AAAAZ6AABAAABr1AABTO_CHAR, date conversionSyntax TO_CHAR(d [, fmt [, ‘nlsparams’] ])PurposeConverts d of DATE datatype to a value of VARCHAR2 datatype in the format specified by the dateformat fmt. If you omit fmt, d is converted to a VARCHAR2 value in the default date format.The ‘nlsparams’ specifies the language in which month and day names and abbreviations are returned.This argument can have this form:‘NLS_DATE_LANGUAGE = language’If you omit nlsparams, this function uses the default date language for your session.ExampleSELECT TO_CHAR(HIREDATE, ‘Month DD, YYYY’) “New date format” FROM emp WHERE ename = ‘BLAKE’; 88
  • ORACLENew date format———————May 01, 1981TO_CHAR, number conversionSyntax TO_CHAR(n [, fmt [, ‘nlsparams’] ])PurposeConverts n of NUMBER datatype to a value of VARCHAR2 datatype, using the optional numberformat fmt. If you omit fmt, n is converted to a VARCHAR2 value exactly long enough to hold itssignificant digits.The ‘nlsparams’ specifies these characters that are returned by number format elements:- decimal character- group separator- local currency symbol- international currency symbolThis argument can have this form:‘NLS_NUMERIC_CHARACTERS = ‘’dg’’NLS_CURRENCY = ‘’text’’NLS_ISO_CURRENCY = territory ‘The characters d and g represent the decimal character and group separator, respectively. They must bedifferent single-byte characters. Note that within the quoted string, you must use two single quotationmarks around the parameter values. Ten characters are available for the currency symbol.If you omit ‘nlsparams’ or any one of the parameters, this function uses the default parameter values foryour session.Example 1In this example, the output is blank padded to the left of the currency symbol.SELECT TO_CHAR(-10000,’L99G999D99MI’) “Amount” FROM DUAL;Amount—————$10,000.00-Example 2SELECT TO_CHAR(-10000,’L99G999D99MI’,‘NLS_NUMERIC_CHARACTERS = ‘’,.’’NLS_CURRENCY = ‘’AusDollars’’ ‘) “Amount” FROM DUAL; 89
  • ORACLEAmount—————————AusDollars10.000,00-NotesIn the optional number format fmt, L designates local currency symbol and MI designates a trailingminus sign. See Table 3-13 for a complete listing of number format elements.During a conversion of Oracle numbers to string, if a rounding operation occurs that overflows orunderflows the Oracle NUMBER range, then ~ or -~ may be returned, representing infinity and negativeinfinity, respectively. This event typically occurs when you are using TO_CHAR() with a restrictivenumber format string, causing a rounding operation.TO_DATESyntaxTO_DATE(char [, fmt [, ‘nlsparams’] ])PurposeConverts char of CHAR or VARCHAR2 datatype to a value of DATE datatype. The fmt is a date formatspecifying the format of char. If you omit fmt, char must be in the default date format. If fmt is ‘J’, forJulian, then char must be an integer.The ‘nlsparams’ has the same purpose in this function as in the TO_CHAR function for date conversion.Do not use the TO_DATE function with a DATE value for the char argument. The returned DATEvalue can have a different century value than the original char, depending on fmt or the default dateformat.ExampleINSERT INTO bonus (bonus_date)SELECT TO_DATE( ‘January 15, 1989, 11:00 A.M.’, ‘Month dd, YYYY, HH:MI A.M.’, ‘NLS_DATE_LANGUAGE = American’) FROM DUAL;TO_MULTI_BYTESyntax TO_MULTI_BYTE(char)PurposeReturns char with all of its single-byte characters converted to their corresponding multibyte characters.Any single-byte characters in char that have no multibyte equivalents appear in the output string assingle-byte characters. This function is only useful if your database character set contains both single-byte and multibyte characters. 90
  • ORACLETO_NUMBERSyntax TO_NUMBER(char [,fmt [, ‘nlsparams’] ])PurposeConverts char, a value of CHAR or VARCHAR2 datatype containing a number in the format specifiedby the optional format model fmt, to a value of NUMBER datatype.Example 1UPDATE emp SET sal = sal + TO_NUMBER(‘100.00’, ‘9G999D99’) WHERE ename = ‘BLAKE’;The ‘nlsparams’ string in this function has the same purpose as it does in the TO_CHAR function fornumber conversions.Example 2SELECT TO_NUMBER(‘-AusDollars100’,’L9G999D99, ‘ NLS_NUMERIC_CHARACTERS = ‘’,.’’ NLS_CURRENCY = ‘’AusDollars’’ ‘) “Amount” FROM DUAL; Amount————— -100TO_SINGLE_BYTESyntax TO_SINGLE_BYTE(char)PurposeReturns char with all of its multibyte character converted to their corresponding single-byte characters.Any multibyte characters in char that have no single-byte equivalents appear in the output as multibytecharacters. This function is only useful if your database character set contains both single-byte andmultibyte characters.TRANSLATE USINGSyntax TRANSLATE(text USING {CHAR_CS | NCHAR_CS })PurposeConverts text into the character set specified for conversions between the database character set and thenational character set.The text argument is the expression to be converted. 91
  • ORACLESpecifying the USING CHAR_CS argument converts text into the database character set. The outputdatatype is VARCHAR2.Specifying the USING NCHAR_CS argument converts text into the national character set. The outputdatatype is NVARCHAR2.This function is similar to the Oracle CONVERT function, but must be used instead of CONVERT ifeither the input or the output datatype is being used as NCHAR or NVARCHAR2.Example 1CREATE TABLE t1 (char_col CHAR(20), nchar_col nchar(20));INSERT INTO t1VALUES (‘Hi’, N’Bye’);SELECT * FROM t1;CHAR_COL NCHAR_COL———— ————–––––Hi ByeExample 2UPDATE t1 SET nchar_col = TRANSLATE(char_col USING NCHAR_CS);UPDATE t1 SET char_col = TRANSLATE(nchar_col USING CHAR_CS);SELECT * FROM t1;CHAR_COL NCHAR_COL———— ———––––––Hi HiExample 3UPDATE t1 SET nchar_col = TRANSLATE(‘deo’ USING NCHAR_CS);UPDATE t1 SET char_col = TRANSLATE(N’deo’ USING CHAR_CS);CHAR_COL NCHAR_COL———— ––––————deo deoUID Syntax UID Purpose Returns an integer that uniquely identifies the current user. 92
  • ORACLEUSER Syntax USER Purpose Returns the current Oracle user with the datatype VARCHAR2. Oracle compares values of this function with blank-padded comparison semantics. a distributed SQL statement, the UID and USER functions identify the r on your local database. You cannot use these functions in the dition of a CHECK constraint. Example SELECT USER, UID FROM DUAL; UID ------------------------- ---------- 19USERENV Syntax USERENV(option) Purpose Returns information of VARCHAR2 datatype about the current session. This information can be useful for writing an application-specific audit trail table or for determining the language-specific characters currently used by your session. You cannot use USERENV in the condition of a CHECK constraint. The argument option can have any of these values: ISDBA returns TRUE if you currently have the ISDBA role enabled and FALSE if you do not. LANGUAGE returns the language and territory currently used by your session along with the database character set in this form: _territory.characterset TERMINAL returns the operating system identifier for your current sessions terminal. In distributed SQL statements, this option returns the identifier for your local session. In a distributed environment, this is supported only for remote SELECTs, not for remote INSERTs, UPDATEs, or DELETEs. SESSIONID returns your auditing session identifier. You cannot use this option in distributed SQL statements. To use this keyword in USERENV, the initialization parameter AUDIT_TRAIL must be set to TRUE. ENTRYID returns available auditing entry identifier. You cannot use this option in distributed SQL statements. To use this keyword in USERENV, the initialization parameter AUDIT_TRAIL must be set to TRUE. LANG Returns the ISO abbreviation for the language name, a shorter form than the existing LANGUAGE parameter. INSTANCE Returns the instance identification number of the current instance. Example SELECT USERENV(LANGUAGE) "Language" FROM DUAL; ----------------------------------- AMERICAN_AMERICA.WE8DEC 93
  • ORACLEVSIZE Syntax VSIZE(expr) Purpose Returns the number of bytes in the internal representation of expr. If expr is null, this function returns null. Example SELECT ename, VSIZE (ename) "BYTES" WHERE deptno = 10; ENAME BYTES ---------- ---------- CLARK 5 KING 4 MILLER 6Group FunctionsGroup functions return results based on groups of rows, rather than on single rows. In this way, groupfunctions are different from single-row functions.Many group functions accept these options:DISTINCT This option causes a group function to consider only distinct values of the argument expression.ALL This option causes a group function to consider all values, including all duplicates.For example, the DISTINCT average of 1, 1, 1, and 3 is 2; the ALL average is 1.5. If neither option isspecified, the default is ALL.All group functions except COUNT(*) ignore nulls. You can use the NVL in the argument to a groupfunction to substitute a value for a null.If a query with a group function returns no rows or only rows with nulls for the argument to the groupfunction, the group function returns null.AVG Syntax AVG([DISTINCT|ALL] n) Purpose Returns average value of n. Example SELECT AVG(sal) "Average" FROM emp; Average ---------- 2077.21429 94
  • ORACLECOUNT Syntax COUNT({* | [DISTINCT|ALL] expr}) Purpose Returns the number of rows in the query. If you specify expr, this function returns rows where expr is not null. You can count either all rows, or only distinct values of expr. If you specify the asterisk (*), this function returns all rows, including duplicates and nulls. Example 1 SELECT COUNT(*) "Total" from FROM emp; Total ---------- 18 Example 2 SELECT COUNT(job) "Count" FROM emp; Count ---------- 14 Example 3 SELECT COUNT(DISTINCT job) "Jobs" FROM emp; Jobs ---------- 5MAX Syntax MAX([DISTINCT|ALL] expr) Purpose Returns maximum value of expr. Example SELECT MAX(sal) "Maximum" FROM emp; Maximum ---------- 5000 95
  • ORACLEMIN Syntax MIN([DISTINCT|ALL] expr) Purpose Returns minimum value of expr. Example SELECT MIN(hiredate) "Earliest" FROM emp; Earliest --------- 17-DEC-80STDDEV Syntax STDDEV([DISTINCT|ALL] x) Purpose Returns standard deviation of x, a number. Oracle calculates the standard deviation as the square root of the variance defined for the VARIANCE group function. Example SELECT STDDEV(sal) "Deviation" FROM emp; Deviation ---------- 1182.50322SUM Syntax SUM([DISTINCT|ALL] n) Purpose Returns sum of values of n. Example SELECT SUM(sal) "Total" FROM emp; Total ---------- 29081 96
  • ORACLE DATA MANIPULATION LANGUAGECOMPETENCY OBJECTIVESThis chapter covers the following topics v Data Manipulation commands in SQL. 97
  • ORACLE98
  • ORACLE CHAPTER - 4 DATA MANIPULATION LANGUAGEALTER INDEXPurposeUse ALTER INDEX to:change storage allocation for, rebuild, or rename an indexExample: This statement alters SCOTT’S CUSTOMER index so that future data blocks withinthis index use 5 initial transaction entries and an incremental extent of 100 kilobytes:ALTER INDEX scott.customerINITRANS 5STORAGE (NEXT 100K);ALTER SEQUENCEPurposeTo change the sequence by• changing the increment between future sequence values• setting or eliminating the minimum or maximum value• changing the number of cached sequence numbers• specifying whether the sequence continues to generate numbers after reaching• the maximum or minimum value• specifying whether sequence numbers must be orderedExample: This statement sets a new maximum value for the ESEQ sequence:ALTER SEQUENCE eseqMAXVALUE 1500;ALTER TABLEPurposeTo alter the definition of a table in one of the following ways: 99
  • ORACLEl add a columnl add an integrity constraintl redefine a column (datatype, size, default value)l modify storage characteristics or other parametersl modify the real storage attributes of a nonpartitioned table or the default attributes of a partitioned tablel enable, disable, or drop an integrity constraint or triggerl explicitly allocate an extentl explicitly deallocate the unused space of a tablel allow or disallow writing to a tableExample I. The following statement adds a column named THRIFTPLAN of datatype NUMBERwith a maximum of seven digits and two decimal places and a column named LOANCODE ofdatatype CHAR with a size of one and a NOT NULL integrity constraint:ALTER TABLE empADD (thriftplan NUMBER(7,2),loancode CHAR(1) NOT NULL);Example II. The following statement increases the size of the THRIFTPLAN column to ninedigits:ALTER TABLE empMODIFY (thriftplan NUMBER(9,2));Because the MODIFY clause contains only one column definition, the parenthesesaround the definition are optional.Example III. The following statement changes the values of the PCTFREE and PCTUSEDparameters for the EMP table to 30 and 60, respectively:ALTER TABLE empPCTFREE 30PCTUSED 60;Example IV. The following statement allocates an extent of 5 kilobytes for the EMP table andmakes it available to instance 4:ALTER TABLE empALLOCATE EXTENT (SIZE 5K INSTANCE 4);Because this command omits the DATAFILE parameter, Oracle allocates the extent in one ofthe datafiles belonging to the tablespace containing the table.Example V. This example modifies the BAL column of the ACCOUNTS table so that it has adefault value of 0:ALTER TABLE accountsMODIFY (bal DEFAULT 0);If you subsequently add a new row to the ACCOUNTS table and do not specify a value for theBAL column, the value of the BAL column is automatically 0: 100
  • ORACLEINSERT INTO accounts(accno, accname)VALUES (accseq.nextval, ’LEWIS’)SELECT *FROM accountsWHERE accname = ’LEWIS’;ACCNO ACCNAME BAL——— ——— —-815234 LEWIS 0ALTER TABLESPACEPurposeTo alter an existing tablespace in one of the following ways:l add datafile(s)l rename datafilesl change default storage parametersl take the tablespace online or offlinel begin or end a backupl allow or disallow writing to a tablespacel change the default logging attribute of the tablespacel change the minimum tablespace extent lengthPrerequisitesIf you have ALTER TABLESPACE system privilege, you can perform any of this command’soperations. If you have MANAGE TABLESPACE system privilege, you can only perform thefollowing operations:l take the tablespace online or offlinel begin or end a backupl make the tablespace read-only or read-writeBefore you can make a tablespace read-only, the following conditions must be met. Performingthis function in restricted mode may help you meet these restrictions, since only users withRESTRICTED SESSION system privilege can be logged on.l The tablespace must be online.l There must not be any active transactions in the entire database. This is necessary to ensure that no undo information needs to be applied to the tablespace.l The tablespace must not contain any active rollback segments. For this reason, the SYSTEM tablespace can never be made read-only, because it contains the SYSTEM rollback segment. Additionally, because the rollback segments of a read-only tablespace are not accessible, Oracle recommends that you drop the rollback segments before you make a tablespace read-only. 101
  • ORACLEUSING ALTER TABLESPACEThe following examples illustrate the use of the ALTER TABLESPACE COMMAND.Example IV. The following statement adds a datafile to the tablespace and changes thedefault logging attribute to NOLOGGING; when more space is needed new extents of size 10kilobytes will be added up to a maximum of 100 kilobytes:ALTER TABLESPACE accounting NOLOGGINGADD DATAFILE ’disk3:pay3.dbf’AUTOEXTEND ONNEXT 10 KMAXSIZE 100 K;ALTER USERPurposeTo change any of the following characteristics of a database user:• authentication mechanism of the user• password• default tablespace for object creation• tablespace for temporary segments created for the user• tablespace access and tablespace quotas• limits on database resources• default rolesExample I. The following statement changes the user SCOTT’s password to LION and defaulttablespace to the tablespace TSTEST:ALTER USER scottIDENTIFIED BY lionDEFAULT TABLESPACE tstest;CREATE DATABASEPurposeTo create a database, making it available for general use, with the following options:• to establish a maximum number of instances, datafiles, redo log files groups, or• redo log file members• to specify names and sizes of datafiles and redo log files• to choose a mode of use for the redo log• to specify the national and database character setsThis command erases all data in any specified datafiles that already exist to prepare them forinitial database use. If you use the command on an existing database, all data in the datafilesis lost. 102
  • ORACLEAfter creating the database, this command mounts it in the mode specified by thePARALLEL_SERVER initialization parameter and opens it, making it available for normaluse.Keyword and ParametersDatabase is the name of the database to be created and can be up to eight bytes long. Thedatabase name can contain only ASCII characters. Oracle writes this name into the controlfile. If you subsequently issue an ALTER DATABASE statement and that explicitly specifies adatabase name, Oracle verifies that name with the name in the control file.Note: You cannot use special characters from European or Asian character sets in a database name. Forexample, the umlaut is not allowed.If you omit the database name from a CREATE DATABASE statement, Oracle uses the namespecified by the initialization parameter DB_NAME.CONTROLFILEREUSEreuses existing control files identified by the initialization parameter CONTROL_FILES, thusignoring and overwriting any information they currently contain.Normally you use this option only when you are re-creating a database, rather than creatingone for the first time. You cannot use this option if you also specify a parameter value thatrequires that the control file be larger than the existing files. These parameters areMAXLOGFILES, MAXLOGMEMBERS, MAXLOGHISTORY, MAXDATAFILES, andMAXINSTANCES. If you omit this option and any of the files specified by CONTROL_FILESalready exist, Oracle returns an error message. LOGFILE specifies one or more files to beused as redo log files. Each filespec specifies a redo log file group containing one or moreredo log file members, or copies.. All redo log files specified in a CREATE DATABASE statementare added to redo log thread number 1.GROUP uniquely identifies a redo log file group and can range from 1 to the value of theMAXLOGFILES parameter. You cannot specify multiple redo log file groups having the sameGROUP value. If you omit this parameter, Oracle generates its value automatically. You canexamine the GROUP value for a redo log file group through the dynamic performance tableV$LOG.If you omit the LOGFILE clause, Oracle creates two redo log file groups by default. Thenames and sizes of the default files depends on your operating system. MAXLOGFILESspecifies the maximum number of redo log file groups that can ever be created for the database.Oracle uses this value to determine how much space in the control file to allocate for thenames of redo log files. The default, minimum, and maximum values depends on your operatingsystem. 103
  • ORACLEThe number of redo log file groups accessible to your instance is also limited by the initializationparameter LOG_FILES. MAXLOGMEMBERS specifies the maximum number of members,or copies, for a redo log file group. Oracle uses this value to determine how much space in thecontrol file to allocate for the names of redo log files. The minimum value is 1. The maximumand default values depend on your operating system. MAXLOGHISTORY specifies themaximum number of archived redo log files for automatic media recovery of Oracle with theParallel Server option. Oracle uses this value to determine how much space in the control fileto allocate for the names of archived redo log files. The minimum value is 0. The default valueis a multiple of the MAXINSTANCES value and depends on your operating system. Themaximum value is limited only by the maximum size of the control file.Note: This parameter is useful only if you are using Oracle with the Parallel Server option in parallel mode, andarchivelog mode enabled.MAXDATAFILES specifies the initial sizing of the datafiles section of the control file at CREATEDATABASE or CREATE CONTROLFILE time. An attempt to add a file whose number isgreater than MAXDATAFILES, but less than or equal to DB_FILES, causes the Oracle8 controlfile to expand automatically so that the datafiles section can accommodate more files.Note that the number of datafiles accessible to your instance is also limited by the initializationparameter DB_FILES.MAXINSTANCES specifies the maximum number of instances that can simultaneously havethis database mounted and open. This value takes precedence over the value of initializationparameter INSTANCES. The minimum value is 1. The maximum and default values dependon your operating system.ARCHIVELOG establishes archivelog mode for redo log file groups. In this mode, the contentsof a redo log file group must be archived before the group can be reused. This option preparesfor the possibility of media recovery.NOARCHIVELOG establishes noarchivelog mode for redo log files groups. In this mode, thecontents of a redo log file group need not be archived before the group can be reused. Thisoption does not prepare for the possibility of media recovery. The default is noarchivelogmode. After creating the database, you can change between archivelog mode and noarchivelogmode with the ALTER DATABASE command.CHARACTER SET specifies the character set the database uses to store data. You cannotchange the database character set after creating the database. The supported character setsand default value of this parameter depend on your operating system.ExamplesExample I. The following statement creates a small database using defaults for all arguments:CREATE DATABASE; 104
  • ORACLEExample II. The following statement creates a database and fully specifies each argument:CREATE DATABASE newtestCONTROLFILE REUSELOGFILEGROUP 1 (’diskb:log1.log’, ’diskc:log1.log’) SIZE 50K,GROUP 2 (’diskb:log2.log’, ’diskc:log2.log’) SIZE 50KMAXLOGFILES 5MAXLOGHISTORY 100DATAFILE ’diska:dbone.dat’ SIZE 2MMAXDATAFILES 10MAXINSTANCES 2ARCHIVELOGCHARACTER SET US7ASCIINATIONAL CHARACTER SET JA16SJISFIXEDDATAFILE’disk1:df1.dbf’ AUTOEXTEND ON’disk2:df2.dbf’ AUTOEXTEND ON NEXT 10M MAXSIZE UNLIMITED;CREATE USERPurposeTo create a database user, or an account through which you can log in to the database andestablish the means by which Oracle permits access by the user. You can assign the followingoptional properties to the user:l default tablespacel temporary tablespacel quotas for allocating space in tablespacesl profile containing resource limitsExample I. If you create a new user with PASSWORD EXPIRE, the user’s password must bechanged before attempting to log in to the database. You can create the user SIDNEY byissuing the following statement:CREATE USER sidneyIDENTIFIED BY cartonDEFAULT TABLESPACE cases_tsQUOTA 10M ON cases_tsQUOTA 5M ON temp_tsQUOTA 5M ON systemPROFILE engineerPASSWORD EXPIRE;The user SIDNEY has the following characteristics: 105
  • ORACLEl the password CARTONl default tablespace CASES_TS, with a quota of 10 megabytesl temporary tablespace TEMP_TS, with a quota of 5 megabytesl access to the tablespace SYSTEM, with a quota of 5 megabytesl limits on database resources defined by the profile ENGINEERl an expired password, which must be changed before attempting to log in to the databaseExample II. To create a user accessible only by the operating system account GEORGE,prefix GEORGE by the value of the initialization parameter OS_AUTHENT_PREFIX. Forexample, if this value is “OPS$”, you can create the user OPS$GEORGE with the followingstatement:CREATE USER ops$georgeIDENTIFIED EXTERNALLYDEFAULT TABLESPACE accs_tsTEMPORARY TABLESPACE temp_tsQUOTA UNLIMITED ON accs_tsQUOTA UNLIMITED ON temp_ts;The user OPS$GEORGE has the following additional characteristics:l default tablespace ACCS_TSl default temporary tablespace TEMP_TSl unlimited space on the tablespaces ACCS_TS and TEMP_TSl limits on database resources defined by the DEFAULT profileExample III. The following example creates user CINDY as a global user:CREATE USER cindy IDENTIFIED GLOBALLY AS ’CN=cindyuser’DEFAULT TABLESPACE legal_tsQUOTA 20M ON legal_tsCREATE VIEWPurposeTo define a view, a logical table based on one or more tables or views.CREATE INDEXPurposeTo create an index on:l one or more columns of a table, a partitioned table, or a clusterl one or more scalar typed object attributes of a table or a clusterl a nested table storage table for indexing a nested table columnAn index is a schema object that contains an entry for each value that appears in the indexedcolumn(s) of the table or cluster and provides direct, fast access to rows. A partitioned indexconsists of partitions containing an entry for each value that appears in the indexed column(s)of the table. 106
  • ORACLEIndex ColumnsAn index can contain a maximum of 32 columns. The index entry becomes the concatenationof all data values from each column. You can specify the columns in any order. The order youchoose is important to how Oracle uses the index.When appropriate, Oracle uses the entire index or a leading portion of the index. Assume anindex named IDX1 is created on columns A, B, and C of table TAB1 (in the order A, B, C).Oracle uses the index for references to columns A, B, C (the entire index); A, B; or justcolumn A. References to columns B and C do not use the IDX1 index. Of course, you canalso create another index just for columns B and C.Multiple Indexes Per TableYou can create unlimited indexes for a table provided that the combination of columns differsfor each index. You can create more than one index using the same columns provided thatyou specify distinctly different combinations of the columns. For example, the followingstatements specify valid combinations:CREATE INDEX emp_idx1 ON emp (ename, job);CREATE INDEX emp_idx2 ON emp (job, ename);You cannot create an index that references only one column in a table if another such indexalready exists.Note that each index increases the processing time needed to maintain the table duringupdates to indexed data. Thus, updating a table with a single index will take less time than ifthe table had five indexes.CREATE SEQUENCEPurposeTo create a sequence. A sequence is a database object from which multiple users may generateunique integers. You can use sequences to automatically generate primary key values.Accessing Sequence ValuesOnce a sequence is created, you can access its values in SQL statements with the followingpseudocolumns:CURRVAL returns the current value of the sequence.NEXTVAL increments the sequence and returns the new value.Example. The following statement creates the sequence ESEQ:CREATE SEQUENCE eseqINCREMENT BY 10 107
  • ORACLECREATE SYNONYMPurposeTo create a synonym. A synonym is an alternative name for a table, view, sequence,procedure, stored function, package, snapshot, or another synonym.Scope of SynonymsA private synonym name must be unique in its schema. Oracle attempts to resolve referencesto objects at the schema level before resolving them at the PUBLIC synonym level. Oracleuses a public synonym only when resolving references to an object if both of the followingcases are true:l the object is not prefaced by a schemal the object is not followed by a database linkFor example, assume the schemas SCOTT and BLAKE each contain tables named DEPTand the user SYSTEM creates a PUBLIC synonym named DEPT for BLAKE.DEPT. If theuser SCOTT then issues the following statement, Oracle returns rows from SCOTT.DEPT:SELECT *FROM dept;To retrieve rows from BLAKE.DEPT, the user SCOTT must preface DEPT with theschema name:SELECT *FROM blake.dept;If the user ADAM’s schema does not contain an object named DEPT, then ADAMcan access the DEPT table in BLAKE’s schema by using the public synonym DEPT:SELECT *FROM dept;Example I. To define the synonym MARKET for the table MARKET_RESEARCH in the schemaSCOTT, issue the following statement:CREATE SYNONYM marketFOR scott.market_research;Example II. To create a PUBLIC synonym for the EMP table in the schema SCOTT on theremote SALES database, you could issue the following statement:CREATE PUBLIC SYNONYM empFOR scott.emp@sales;Note that a synonym may have the same name as the base table, provided the base table iscontained in another schema. 108
  • ORACLECREATE TABLEPurposeTo create a table, the basic structure to hold user data, specifying the following information:l column definitionsl table organization definitionl column definitions using objectsl integrity constraintsl the table’s tablespacel storage characteristicsExample I. To define the EMP table owned by SCOTT, you could issue the following statement:CREATE TABLE scott.emp(empno NUMBER CONSTRAINT pk_emp PRIMARY KEY,ename VARCHAR2(10) CONSTRAINT nn_ename NOT NULLCONSTRAINT upper_enameCHECK (ename = UPPER(ename)),job VARCHAR2(9),mgr NUMBER CONSTRAINT fk_mgrREFERENCES scott.emp(empno),hiredate DATE DEFAULT SYSDATE,sal NUMBER(10,2) CONSTRAINT ck_salCHECK (sal > 500),comm NUMBER(9,0) DEFAULT NULL,deptno NUMBER(2) CONSTRAINT nn_deptno NOT NULLCONSTRAINT fk_deptnoREFERENCES scott.dept(deptno) )PCTFREE 5 PCTUSED 75;This table contains 8 columns. The EMPNO column is of datatype NUMBER and has anassociated integrity constraint named PK_EMP. The HIRDEDATE column is of datatype DATEand has a default value of SYSDATE, and so on. This table definition specifies a PCTFREEof 5 and a PCTUSED of 75, which is appropriate for a relatively static table. The definitionalso defines integrity constraints on some columns of the EMP table.Example II. To define the sample table SALGRADE in the HUMAN_RESOURCE tablespacewith a small storage capacity and limited allocation potential, issue the following statement:CREATE TABLE salgrade( grade NUMBER CONSTRAINT pk_salgradeUSING INDEX TABLESPACE users_a,losal NUMBER,hisal NUMBER )TABLESPACE human_resourceSTORAGE (INITIAL 6144NEXT 6144 109
  • ORACLEMINEXTENTS 1MAXEXTENTS 5PCTINCREASE 5);The above statement also defines a PRIMARY KEY constraint on the GRADE column andspecifies that the index Oracle creates to enforce this constraint is created in the USERS_Atablespace.CREATE TABLESPACEPurposeTo create a tablespace. A tablespace is an allocation of space in the database that cancontain schema objects.About TablespacesA tablespace is an allocation of space in the database that can contain any of the followingsegments:l index segmentsl rollback segmentsl temporary segmentsAll databases have at least one tablespace, SYSTEM, which Oracle creates automaticallywhen you create the database.When you create a tablespace, it is initially a read-write tablespace. After creating thetablespace, you can subsequently use the ALTER TABLESPACE command to take it offlineor online, add datafiles to it, or make it a read-only tablespace.Many schema objects have associated segments that occupy space in the database. Theseobjects are located in tablespaces. The user creating such an object can optionally specifythe tablespace to contain the object. The owner of the schema containing the object musthave space quota on the object’s tablespace. You can assign space quota on a tablespace toa user with the QUOTA clause of the CREATE USER or ALTER USER commands.Example I. This command creates a tablespace named TABSPACE_2 with one data file:CREATE TABLESPACE tabspace_2DATAFILE ’diska:tabspace_file2.dat’ SIZE 20MDEFAULT STORAGE (INITIAL 10K NEXT 50KMINEXTENTS 1 MAXEXTENTS 999PCTINCREASE 10)ONLINE;Example II. This command creates a tablespace named TABSPACE_3 with one data file;when more space is required, 50 kilobyte extents will be added up to a maximum size of 10megabytes:CREATE TABLESPACE tabspace_5DATAFILE ’diskb:tabspace_file3.dat’ SIZE 500K REUSEAUTOEXTEND ON NEXT 500K MAXSIZE 10M; 110
  • ORACLEExample III. This command creates tablespace TABSPACE_5 with one data file andallocates every extent as a multiple of 64K:CREATE TABLESPACE tabspace_3DATAFILE ’tabspace_file5.dbf’ SIZE 2MMINIMUM EXTENT 64KDEFAULT STORAGE (INITIAL 128K NEXT 128K)LOGGING;CREATE VIEWPurposeTo define a view, a logical table based on one or more tables or views.Using ViewsA view is a logical table that allows you to access data from other tables and views. A viewcontains no data itself. The tables upon which a view is based are called base tables.Views are used for the following purposes:l To provide an additional level of table security, by restricting access to a predetermined set of rows and/or columns of a base table.l To hide data complexity. For example, a view may be used to act as one table when actually several tables are used to construct the result.l To present data from another perspective. For example, views provide a means of renaming columns without actually changing the base table’s definition.l To cause Oracle to perform some operations, such as joins, on the database containing the view, rather than another database referenced in the same SQL statement. You can use a view anywhere you can use a table in these SQL statements:l COMMENTl DELETEl INSERTl LOCK TABLEl UPDATEl SELECTl A view’s query cannot select the CURRVAL or NEXTVAL pseudocolumns.l If a view’s query selects the ROWID, ROWNUM, or LEVEL pseudocolumns, they must have aliases in the view’s query.l You can define a view with a query that uses an asterisk (*) to select all the columns of a table:CREATE VIEW emp_vuAS SELECT * FROM emp;Oracle translates the asterisk into a list of all the columns in the table at the time the CREATEVIEW statement is issued. If you subsequently add new columns to the table, the view will notcontain these columns unless you recreate the view by issuing another CREATE VIEWstatement with the OR REPLACE option. Oracle recommends that you explicitly specify allcolumns in the select list of a view query, rather than use the asterisk. 111
  • ORACLEJoin ViewsA join view is a view with a subquery containing a join. You can queryUSER_UPDATABLE_COLUMNS to see whether the columns in a join view are updatable.For example:CREATE VIEW ed ASSELECT e.empno, e.ename, d.deptno, d.locFROM emp e, dept dWHERE e.deptno = d.deptnoView created.SELECT column_name, updatableFROM user_updatable_columnsWHERE table_name = ’ED’;COLUMN_NAME UPD——————— —-ENAME YESDEPTNO NOEMPNO YESLOC NOIn the above example, note the unique index on the DEPTNO column of the DEPT table. Youcan insert, update or delete a row from the EMP base table, because all the columns in theview mapping to the emp table are marked as updatable and because the primary key of empis included in the view.Updatable Join ViewsA join view is a view that contains a join. Join views are updatable under the conditionsdiscussed in this section. A key-preserved table is a table in a join view, all of whose keycolumns are present as keys in the join view. This means the keys must not only be in the joinview, but must still be unique and not null in the join view. This implies that a key-preservedtable generally cannot be an outer-joined table. A key-preserved table could be an outer-joined table only if the outer join did not in fact generate any nulls. This, however, is a functionof the data and therefore inadmissible as a basis for operations.Therefore, you can execute the DML statements INSERT, UPDATE, and DELETE on a joinview only provided that all of the following are true:l The DML statement affects only one of the tables underlying the join.l If the statement is UPDATE, then all columns updated are extracted from a key- preserved table. In addition, if the view has the CHECK OPTION, join columns and columns taken from tables that are referenced more than once in the view are shielded from UPDATE.l If the statement is DELETE, then there is one and only one key-preserved table in the join. This table may be present more than once in the join, unless the view has the CHECK OPTION.l If the statement is INSERT, then all columns into which values are inserted come from a key-preserved table, and the view does not have the CHECK OPTION. 112
  • ORACLEExamplesExample I. The following statement creates a view of the EMP table named DEPT20. Theview shows the employees in Department 20 and their annual salary:CREATE VIEW dept20AS SELECT ename, sal*12 annual_salaryFROM empWHERE deptno = 20;Note that the view declaration need not define a name for the column based on the expressionSAL*12, because the subquery uses a column alias (ANNUAL_SALARY) for this expression.Example II. The following statement creates an updatable view named CLERKS of all clerksin the EMP table; only the employees’ IDs, names, and department numbers are visible inthis view and only these columns can be updated in rows identified as clerks:CREATE VIEW clerk (id_number, person, department, position)AS SELECT empno, ename, deptno, jobFROM empWHERE job = ’CLERK’WITH CHECK OPTION CONSTRAINT wco;Because of the CHECK OPTION, you cannot subsequently insert a new row into CLERK ifthe new employee is not a clerk.Example III. The following statement creates a read-only view named CLERKS of all clerksin the EMP table; only the employee’s IDs, names, and department numbers are visible in thisview:CREATE VIEW clerk (id_number, person, department, position) AS SELECTempno, ename, deptno, jobFROM empWHERE job = ’CLERK’WITH READ ONLY;INSERTPurposeTo add rows to:l a tablel a view’s base tableExamplesExample I. The following statement inserts a row into the DEPT table:INSERT INTO deptVALUES (50, ’PRODUCTION’, ’SAN FRANCISCO’); 113
  • ORACLEExample II. The following statement inserts a row with six columns into the EMP table. One ofthese columns is assigned NULL and another is assigned a number in scientific notation:INSERT INTO emp (empno, ename, job, sal, comm, deptno)VALUES (7890, ’JINKS’, ’CLERK’, 1.2E3, NULL, 40);Example III. The following statement has the same effect as Example II:INSERT INTO (select empno, ename, job, sal, comm, deptno from emp)VALUES (7890, ’JINKS’, ’CLERK’, 1.2E3, NULL, 40);Example IV. The following statement copies managers and presidents or employees whosecommission exceeds 25% of their salary into the BONUS table:INSERT INTO bonusSELECT ename, job, sal, commFROM empWHERE comm > 0.25 * salOR job IN (’PRESIDENT’, ’MANAGER’);LOCK TABLEPurposeTo lock one or more tables in a specified mode. This lock manually overrides automaticlocking and permits or denies access to a table or view by other users for the duration of youroperation.Lockmode is one of the following:ROW SHARE allows concurrent access to the locked table, but prohibits users from lockingthe entire table for exclusive access. ROW SHARE is synonymous with SHARE UPDATE,which is included for compatibility with earlier versions of Oracle.ROW EXCLUSIVE is the same as ROW SHARE, but also prohibits locking in SHARE mode.Row Exclusive locks are automatically obtained when updating, inserting, or deleting.SHARE UPDATE—see ROW SHARE.SHARE allows concurrent queries but prohibits updates to the locked table.SHARE ROW EXCLUSIVE is used to look at a whole table and to allow others to look at rowsin the table but to prohibit others from locking the table in SHARE mode or updating rows.EXCLUSIVE allows queries on the locked table but prohibits any other activity on it.NOWAIT specifies that Oracle returns control to you immediately if the specified table isalready locked by another user. In this case, Oracle returns a message indicating that thetable is already locked by another user. 114
  • ORACLEIf you omit this clause, Oracle waits until the table is available, locks it, and returns control toyou.Locking TablesSome forms of locks can be placed on the same table at the same time; other locks only allowone lock per table. For example, multiple users can place SHARE locks on the same table atthe same time, but only one user can place an EXCLUSIVE lock on a table at a time. For acomplete description of the interaction of lock modes, see Oracle8 Concepts. When you locka table, you choose how other users can access it. A locked table remains locked until youeither commit your transaction or roll it back, either entirely or to a savepoint before youlocked the table. A lock never prevents other users from querying the table. A query neverplaces a lock on a table. Readers never block writers and writers never block readers.Example I. The following statement locks the EMP table in exclusive mode, but does not waitif another user already has locked the table:LOCK TABLE empIN EXCLUSIVE MODENOWAIT;Example II. The following statement locks the remote ACCOUNTS table that is accessiblethrough the database link BOSTON:LOCK TABLE accounts@bostonIN SHARE MODE;UPDATEPurposeTo change existing values in a table or in a view’s base table.Example I. The following statement gives null commissions to all employees with the jobTRAINEE:UPDATE empSET comm = NULLWHERE job = ’TRAINEE’;Example II. The following statement promotes JONES to manager of Department 20 with a$1,000 raise (assuming there is only one JONES):UPDATE empSET job = ’MANAGER’, sal = sal + 1000, deptno = 20WHERE ename = ’JONES’; 115
  • ORACLE116
  • ORACLE PL/SQL AND ITS FEATURESCOMPETENCY OBJECTIVESThis chapter covers the following topics v PL/SQL advantages & structure of PL/SQL block v Variables & constants v Conditional structures v Unconditional branching v Cursors v SQL implicit cursor v Error handling exceptions v Procedures & functions v Parameter passing 117
  • ORACLE118
  • ORACLE CHAPTER - 5 PL/SQL AND ITS FEATURESPL/SQL is Oracle’s programmatic language (PL extension to the structured query language.)This chapter provides you with an introduction to PL/SQL.A good way to get familiar with PL/SQL is to look at a sample program. The program belowprocesses an order for tennis rackets. First, it declares a variable of type NUMBER to store thequantity of tennis rackets on hand. Then, it retrieves the quantity on hand from a databasetable named inventory. If the quantity is greater than zero, the program updates the tableand inserts a purchase record into another table named purchase_record. Otherwise, theprogram inserts an out-of-stock record into the purchase_record table.DECLAREQty1 NUMBER(5);BEGINSELECT quantity INTO qty FROM inventoryWHERE product = ’TENNIS RACKET’FOR UPDATE OF quantity;IF qty1 > 0 THEN — check quantityUPDATE inventory SET quantity = quantity - 1WHERE product = ’TENNIS RACKET’;INSERT INTO purchase_recordVALUES (’Tennis racket purchased’, SYSDATE);ELSEINSERT INTO purchase_recordVALUES (’Out of tennis rackets’, SYSDATE);END IF;COMMIT;END;With PL/SQL, you can use SQL statements to manipulate Oracle data and flow-of-controlstatements to process the data. Moreover, you can declare constants and variables, defineprocedures and functions, and trap runtime errors. Thus, PL/SQL combines the datamanipulating power of SQL with the data processing power of procedural languages. 119
  • ORACLEBlock StructurePL/SQL is a block-structured language. That is, the basic units (procedures, functions, andanonymous blocks) that make up a PL/SQL program are logical blocks, which can containany number of nested sub-blocks. Typically, each logical block corresponds to a problem orsubproblem to be solved. Thus, PL/SQL supports the divide-and- conquer approach to problemsolving called stepwise refinement.A block (or sub-block) lets you group logically related declarations and statements. That way,you can place declarations close to where they are used. The declarations are local to theblock and cease to exist when the block completes. As Figure 1–1 shows, a PL/SQL blockhas three parts: a declarative part, an executable part, and an exception-handling part. (InPL/SQL, a warning or error condition is called an exception.) Only the executable part isrequired. The order of the parts is logical. First comes the declarative part, in which items canbe declared. Once declared, items can be manipulated in the executable part. Exceptionsraised during execution can be dealt with in the exception-handling part.You can nest sub-blocks in the executable and exception-handling parts of a PL/SQL block orsubprogram but not in the declarative part. Also, you can define local subprograms in thedeclarative part of any block. However, you can call local subprograms only from the block inwhich they are defined. Fig. 1-1: Block StructureVariables and Constants in PL/SQLPL/SQL allows you to declare constants and variables, then use them in SQL and proceduralstatements anywhere an expression can be used. However, forward references are not allowed.So, you must declare a constant or variable before referencing it in other statements, includingother declarative statements.Declaring Variables in PL/SQLVariables in PL/SQL can have any SQL datatype, such as CHAR, DATE, and NUMBER, or anyPL/SQL datatype, such as BOOLEAN and BINARY_INTEGER. For example, assume that youwant to declare a variable named part_no to hold 4-digit numbers and a variable namedin_stock to hold the Boolean value TRUE or FALSE. You declare these variables as follows:part NUMBER(4);stock_status BOOLEAN; 120
  • ORACLEYou can also declare nested tables, variable-size arrays (varrays for short), and records usingthe TABLE, VARRAY, and RECORD composite datatypes.Assigning Values to a VariableYou can assign values to a variable in two ways. The first way uses the assignment operator(:=), a colon followed by an equal sign. You place the variable to the left of the operator andan expression to the right. Some examples follow:x := sale_value * tax_rate;bonus := sal * 0.10;amount := TO_NUMBER(SUBSTR(’750 rupees’, 1, 3));valid := FALSE;The second way to assign values to a variable is to select or fetch database values into it. Inthe following example, you have Oracle compute a 10% bonus when you select the salary ofan employee:SELECT sal * 0.10 INTO bonus FROM emp WHERE empno = emp_id;Then, you can use the variable bonus in another computation or insert its value into adatabase table.Declaring ConstantsDeclaring a constant is like declaring a variable except that you must add the keywordCONSTANT and immediately assign a value to the constant. Thereafter, no more assignmentsto the constant are allowed. In the following example, you declare a constant named credit:credit CONSTANT REAL := 1000.00;CursorsOracle uses work areas to execute SQL statements and store processing information. A PL/SQL construct called a cursor lets you name a work area and access its stored information.There are two kinds of cursors: implicit and explicit. PL/SQL implicitly declares a cursor for allSQL data manipulation statements, including queries that return only one row. For queriesthat return more than one row, you can explicitly declare a cursor to process the rows individually.An example follows:DECLARECURSOR c1 ISSELECT empno, ename, job FROM emp WHERE deptno = 20;The set of rows returned by a multi-row query is called the result set. Its size is the number ofrows that meet your search criteria. As Figure 1–2 shows, an explicit cursor “points” to thecurrent row in the result set. This allows your program to process the rows one at a time. 121
  • ORACLE Fig.1-2: Query ProcessingMulti-row query processing is somewhat like file processing. For example, a COBOL programopens a file, processes records, then closes the file. Likewise, a PL/SQL program opens acursor, processes rows returned by a query, then closes the cursor. Just as a file pointermarks the current position in an open file, a cursor marks the current position in a result set.You use the OPEN, FETCH, and CLOSE statements to control a cursor. The OPEN statementexecutes the query associated with the cursor, identifies the result set, and positions thecursor before the first row. The FETCH statement retrieves the current row and advances thecursor to the next row. When the last row has been processed, the CLOSE statement disablesthe cursor.Cursor FOR LoopsIn most situations that require an explicit cursor, you can simplify coding by using a cursorFOR loop instead of the OPEN, FETCH, and CLOSE statements. A cursor FOR loop implicitlydeclares its loop index as a record that represents a row in a database table, opens a cursor,repeatedly fetches rows of values from the result set into fields in the record, then closes thecursor when all rows have been processed. In the following example, the cursor FOR loopimplicitly declares emp_rec as a record:DECLARECURSOR c1 ISSELECT ename, sal, hiredate, deptno FROM emp;...BEGINFOR emp_rec IN c1 LOOP...salary_total := salary_total + emp_rec.sal;END LOOP;To reference individual fields in the record, you use dot notation, in which a dot (.) serves asthe component (field) selector.Cursor VariablesLike a cursor, a cursor variable points to the current row in the result set of a multi-row query.But, unlike a cursor, a cursor variable can be opened for any type-compatible query. It is nottied to a specific query. Cursor variables are true PL/SQL variables, to which you can assignnew values and which you can pass to subprograms stored in an Oracle database. This gives 122
  • ORACLEyou more flexibility and a convenient way to centralize data retrieval. Typically, you open acursor variable by passing it to a stored procedure that declares a cursor variable as one of itsformal parameters. The following procedure opens the cursor variable generic_cv for thechosen query:PROCEDURE open_cv (generic_cv IN OUT GenericCurTyp, choice IN NUMBER)ISBEGINIF choice = 1 THENOPEN generic_cv FOR SELECT * FROM emp;ELSIF choice = 2 THENOPEN generic_cv FOR SELECT * FROM dept;ELSIF choice = 3 THENOPEN generic_cv FOR SELECT * FROM salgrade;END IF;AttributesPL/SQL variables and cursors have attributes, which are properties that let you reference thedatatype and structure of an item without repeating its definition. Database columns andtables have similar attributes, which you can use to ease maintenance. A percent sign (%)serves as the attribute indicator.%TYPEThe %TYPE attribute provides the datatype of a variable or database column. This is particularlyuseful when declaring variables that will hold database values. For example, assume there isa column named title in a table named books. To declare a variable named my_titlethat has the same datatype as column title, you use dot notation and the %TYPE attribute,as follows:my_title books.title%TYPE;Declaring my_title with %TYPE has two advantages. First, you need not know the exactdatatype of title. Second, if you change the database definition of title (make it a longercharacter string, for example), the datatype of my_title changes accordingly at run time.%ROWTYPEIn PL/SQL, records are used to group data. A record consists of a number of related fields inwhich data values can be stored. The %ROWTYPE attribute provides a record type thatrepresents a row in a table. The record can store an entire row of data selected from the tableor fetched from a cursor or cursor variable. Columns in a row and corresponding fields in arecord have the same names and datatypes. In the example below, you declare a recordnamed dept_rec. Its fields have the same names and datatypes as the columns in thedept table. 123
  • ORACLEDECLAREdept_rec dept%ROWTYPE; — declare record variableYou use dot notation to reference fields, as the following example shows:my_deptno := dept_rec.deptno;If you declare a cursor that retrieves the last name, salary, hire date, and job title of anemployee, you can use %ROWTYPE to declare a record that stores the same information, asfollows:DECLARECURSOR c1 IS SELECT ename, sal, hiredate, job FROM emp;emp_rec c1%ROWTYPE; — declare record variable that— represents a row in the emp tableWhen you execute the statementFETCH c1 INTO emp_rec;the value in the ename column of the emp table is assigned to the ename field of emp_rec,the value in the sal column is assigned to the sal field, and so on. Figure 1–3 shows howthe result might appear. Fig.1-3: %ROWTYPE RecordControl Structures in PL/SQLControl structures are the most important PL/SQL extension to SQL. Not only does PL/SQLlet you manipulate Oracle data, it lets you process the data using conditional, iterative, andsequential flow-of-control statements such as IF-THEN-ELSE, FOR-LOOP, WHILE-LOOP, EXIT-WHEN, and GOTO. Collectively, these statements can handle any situation.Conditional ControlOften, it is necessary to take alternative actions depending on circumstances. The IF-THEN-ELSE statement lets you execute a sequence of statements conditionally. The IF clausechecks a condition; the THEN clause defines what to do if the condition is true; the ELSEclause defines what to do if the condition is false or null. 124
  • ORACLEConsider the program below, which processes a bank transaction. Before allowing you towithdraw $500 from account 3, it makes sure the account has sufficient funds to cover thewithdrawal. If the funds are available, the program debits the account; otherwise, the programinserts a record into an audit table.DECLAREacct_balance NUMBER(11,2);acct CONSTANT NUMBER(4) := 3;debit_amt CONSTANT NUMBER(5,2) := 500.00;BEGINSELECT bal INTO acct_balance FROM accountsWHERE account_id = acctFOR UPDATE OF bal;IF acct_balance >= debit_amt THENUPDATE accounts SET bal = bal - debit_amtWHERE account_id = acct;ELSEINSERT INTO temp VALUES(acct, acct_balance, ’Insufficient funds’);— insert account, current balance, and messageEND IF;COMMIT;END;A sequence of statements that uses query results to select alternative actions is common indatabase applications. Another common sequence inserts or deletes a row only if an associatedentry is found in another table. You can bundle these common sequences into a PL/SQLblock using conditional logic. This can improve performance and simplify the integrity checksbuilt into Oracle Forms applications.Iterative ControlLOOP statements let you execute a sequence of statements multiple times. You place thekeyword LOOP before the first statement in the sequence and the keywords END LOOP afterthe last statement in the sequence. The following example shows the simplest kind of loop,which repeats a sequence of statements continually:LOOP— sequence of statementsEND LOOP;The FOR-LOOP statement lets you specify a range of integers, then execute a sequence ofstatements once for each integer in the range. For example, suppose that you are amanufacturer of custom-made cars and that each car has a serial number. To keep track ofwhich customer buys each car, you might use the following FOR loop: 125
  • ORACLEFOR i IN 1..order_qty LOOPUPDATE sales SET custno = customer_idWHERE serial_num = serial_num_seq.NEXTVAL;END LOOP;The WHILE-LOOP statement associates a condition with a sequence of statements. Beforeeach iteration of the loop, the condition is evaluated. If the condition yields TRUE, the sequenceof statements is executed, then control resumes at the top of the loop. If the condition yieldsFALSE or NULL, the loop is bypassed and control passes to the next statement. In thefollowing example, you find the first employee who has a salary over $4000 and is higher inthe chain of command than employee 7902:DECLAREsalary emp.sal%TYPE;mgr_num emp.mgr%TYPE;last_name emp.ename%TYPE;starting_empno CONSTANT NUMBER(4) := 7902;BEGINSELECT sal, mgr INTO salary, mgr_num FROM empWHERE empno = starting_empno;WHILE salary < 4000 LOOPSELECT sal, mgr, ename INTO salary, mgr_num, last_nameFROM emp WHERE empno = mgr_num;END LOOP;INSERT INTO temp VALUES (NULL, salary, last_name);COMMIT;END;The EXIT-WHEN statement lets you complete a loop if further processing is impossible orundesirable. When the EXIT statement is encountered, the condition in the WHEN clause isevaluated. If the condition yields TRUE, the loop completes and control passes to the nextstatement. In the following example, the loop completes when the value of total exceeds25,000:LOOP...total := total + salary;EXIT WHEN total > 25000; — exit loop if condition is trueEND LOOP;— control resumes hereSequential ControlThe GOTO statement lets you branch to a label unconditionally. The label, an undeclaredidentifier enclosed by double angle brackets, must precede an executable statement or a PL/SQL block. When executed, the GOTO statement transfers control to the labeled statement orblock, as the following example shows: 126
  • ORACLEIF rating > 90 THENGOTO calc_raise; — branch to labelEND IF;...<<calc_raise>>IF job_title = ’SALESMAN’ THEN — control resumes hereamount := commission * 0.25;ELSEamount := salary * 0.10;END IF;ModularityModularity lets you break an application down into manageable, well-defined logic modules.Through successive refinement, you can reduce a complex problem to a set of simple problemsthat have easy-to-implement solutions. PL/SQL meets this need with program units. Besidesblocks and subprograms, PL/SQL provides the package, which allows you to group relatedprogram items into larger units.SubprogramsPL/SQL has two types of subprograms called procedures and functions, which can takeparameters and be invoked (called). As the following example shows, a subprogram is like aminiature program, beginning with a header followed by an optional declarative part, anexecutable part, and an optional exception-handling part:PROCEDURE award_bonus (emp_id NUMBER) ISbonus REAL;comm_missing EXCEPTION;BEGINSELECT comm * 0.15 INTO bonus FROM emp WHERE empno = emp_id;IF bonus IS NULL THENRAISE comm_missing;ELSEUPDATE payroll SET pay = pay + bonus WHERE empno = emp_id;END IF;EXCEPTIONWHEN comm_missing THEN...END award_bonus;When called, this procedure accepts an employee number. It uses the number to select theemployee’s commission from a database table and, at the same time, compute a 15% bonus.Then, it checks the bonus amount. If the bonus is null, an exception is raised; otherwise, theemployee’s payroll record is updated. 127
  • ORACLEExternal ProceduresSome programming tasks are more quickly or easily done in a lower-level language such asC, which is more efficient at machine-precision calculations. For example, a Fast FourierTransform (FFT) routine written in C runs faster than one written in PL/SQL.To support such special-purpose processing, PL/SQL provides an interface for calling routineswritten in other languages. This makes the strengths and capabilities of those languagesavailable to you. An external procedure is a third-generation-language routine stored in adynamic link library (DLL), registered with PL/SQL, and called by you to do special-purposeprocessing. At run time, PL/SQL loads the library dynamically, then calls the routine as if itwere a PL/SQL subprogram. Typically, external procedures are used to interface with embeddedsystems, solve scientific and engineering problems, analyze data, or control real-time devicesand processes. In the following example, you write a PL/SQL stand-alone function namedinterp that registers the C routine c_interp as an external function:CREATE FUNCTION interp (— find the value of y at x degrees using Lagrange interpolationx FLOAT,y FLOAT)RETURN FLOAT AS EXTERNALLIBRARY mathlibNAME “c_interp”LANGUAGE C;PackagesPL/SQL lets you bundle logically related types, variables, cursors, and subprograms into apackage. Each package is easy to understand and the interfaces between packages aresimple, clear, and well defined. This aids application development. Packages usually havetwo parts: a specification and a body. The specification is the interface to your applications; itdeclares the types, constants, variables, exceptions, cursors, and subprograms available foruse. The body defines cursors and subprograms and so implements the specification. In thefollowing example, you package two employment procedures:CREATE PACKAGE emp_actions AS — package specificationPROCEDURE hire_employee (empno NUMBER, ename CHAR, ...);PROCEDURE fire_employee (emp_id NUMBER);END emp_actions;CREATE PACKAGE BODY emp_actions AS — package bodyPROCEDURE hire_employee (empno NUMBER, ename CHAR, ...) ISBEGININSERT INTO emp VALUES (empno, ename, ...);END hire_employee;PROCEDURE fire_employee (emp_id NUMBER) ISBEGIN 128
  • ORACLEDELETE FROM emp WHERE empno = emp_id;END fire_employee;END emp_actions;Only the declarations in the package specification are visible and accessible to applications.Implementation details in the package body are hidden and inaccessible.Packages can be compiled and stored in an Oracle database, where their contents can beshared by many applications. When you call a packaged subprogram for the first time, thewhole package is loaded into memory. So, subsequent calls to related subprograms in thepackage require no disk I/O. Thus, packages can enhance productivity and improveperformance.Data AbstractionData abstraction lets you extract the essential properties of data while ignoring unnecessarydetails. Once you design a data structure, you can forget the details and focus on designingalgorithms that manipulate the data structure.CollectionsThe collection types TABLE and VARRAY allow you to declare nested tables and variable-size arrays (varrays for short). A collection is an ordered group of elements, all of the sametype. Each element has a unique subscript that determines its position in the collection. Toreference an element, you use standard subscripting syntax. For example, the following callreferences the fifth element in the nested table (of type Staff) returned by function new_hires:DECLARETYPE Staff IS TABLE OF Employee;staffer Employee;FUNCTION new_hires (hiredate DATE) RETURN Staff ISBEGIN...END;BEGINstaffer := new_hires(’10-NOV-96’)(5);...END;Collections work like the arrays found in most third-generation programming languages. Theycan store instances of an object type and, conversely, can be attributes of an object type.Also, collections can be passed as parameters. So, you can use them to move columns ofdata into and out of database tables or between client-side applications and storedsubprograms. 129
  • ORACLERecordsYou can use the %ROWTYPE attribute to declare a record that represents a row in a table or arow fetched from a cursor. But, with a user-defined record, you can declare fields of your own.Records contain uniquely named fields, which can have different datatypes.Suppose you have various data about an employee such as name, salary, and hire date.These items are dissimilar in type but logically related. A record containing a field for eachitem lets you treat the data as a logical unit.Consider the following example:DECLARETYPE TimeRec IS RECORD (minutes SMALLINT, hours SMALLINT);TYPE MeetingTyp IS RECORD (day DATE,time TimeRec, — nested recordplace VARCHAR2(20),purpose VARCHAR2(50));Notice that you can nest records. That is, a record can be the component of another record.Object TypesIn PL/SQL, object-oriented programming is based on object types. An object type encapsulatesa data structure along with the functions and procedures needed to manipulate the data. Thevariables that form the data structure are called attributes. The functions and procedures thatcharacterize the behavior of the object type are called methods.Object types reduce complexity by breaking down a large system into logical entities. Thisallows you to create software components that are modular, maintainable, and reusable.When you define an object type using the CREATE TYPE statement (in SQL*Plus for example),you create an abstract template for some real-world object. As the following example of abank account shows, the template specifies only those attributes and behaviors the objectwill need in the application environment:CREATE TYPE Bank_Account AS OBJECT (acct_number INTEGER(5),balance REAL,status VARCHAR2(10),MEMBER PROCEDURE open (amount IN REAL),MEMBER PROCEDURE verify_acct (num IN INTEGER),MEMBER PROCEDURE close (num IN INTEGER, amount OUT REAL),MEMBER PROCEDURE deposit (num IN INTEGER, amount IN REAL),MEMBER PROCEDURE withdraw (num IN INTEGER, amount IN REAL),MEMBER FUNCTION curr_bal (num IN INTEGER) RETURN REAL); 130
  • ORACLEAt run time, when the data structure is filled with values, you have created an instance of anabstract bank account. You can create as many instances (called objects) as you need. Eachobject has the number, balance, and status of an actual bank account.Information HidingWith information hiding, you see only the details that are relevant at a given level of algorithmand data structure design. Information hiding keeps high-level design decisions separatefrom low-level design details, which are more likely to change.AlgorithmsYou implement information hiding for algorithms through top-down design. Once you definethe purpose and interface specifications of a low-level procedure, you can ignore theimplementation details. They are hidden at higher levels. For example, the implementation ofa procedure named raise_salary is hidden. All you need to know is that the procedurewill increase a specific employee salary by a given amount. Any changes to the definition ofraise_salary are transparent to calling applications.Data StructuresYou implement information hiding for data structures though data encapsulation. By developinga set of utility subprograms for a data structure, you insulate it from users and other developers.That way, other developers know how to use the subprograms that operate on the data structurebut not how the structure is represented.With PL/SQL packages, you can specify whether subprograms are public or private. Thus,packages enforce data encapsulation by letting you put subprogram definitions in a blackbox. A private definition is hidden and inaccessible. Only the package, not your application, isaffected if the definition changes. This simplifies maintenance and enhancement.Error HandlingPL/SQL makes it easy to detect and process predefined and user-defined error conditionscalled exceptions. When an error occurs, an exception is raised. That is, normal executionstops and control transfers to the exception-handling part of your PL/SQL block or subprogram.To handle raised exceptions, you write separate routines called exception handlers.Predefined exceptions are raised implicitly by the runtime system. For example, if you try todivide a number by zero, PL/SQL raises the predefined exception ZERO_DIVIDE automatically.You must raise user-defined exceptions explicitly with the RAISE statement.You can define exceptions of your own in the declarative part of any PL/SQL block orsubprogram. In the executable part, you check for the condition that needs special attention.If you find that the condition exists, you execute a RAISE statement. In the example below,you compute the bonus earned by a salesperson. 131
  • ORACLEThe bonus is based on salary and commission. So, if the commission is null, you raise theexception comm_missing.DECLARE...comm_missing EXCEPTION; — declare exceptionBEGIN...IF commission IS NULL THENRAISE comm_missing; — raise exceptionELSEbonus := (salary * 0.10) + (commission * 0.15);END IF;EXCEPTIONWHEN comm_missing THENn process errorArchitectureThe PL/SQL runtime system is a technology, not an independent product. Think of thistechnology as an engine that executes PL/SQL blocks and subprograms. The engine can beinstalled in an Oracle server or in an application development tool such as Oracle Forms orOracle Reports. So, PL/SQL can reside in two environments:l the Oracle serverl Oracle toolsThese two environments are independent. PL/SQL might be available in the Oracle serverbut unavailable in tools, or the other way around. In either environment, the PL/SQL engineaccepts as input any valid PL/SQL block or subprogram.Figure 1–4 shows the PL/SQL engine processing an anonymous block. The engine executesprocedural statements but sends SQL statements to the SQL Statement Executor in theOracle server. Fig.1-4 : PL/SQL Engine 132
  • ORACLEIn the Oracle ServerApplication development tools that lack a local PL/SQL engine must rely on Oracle to rocessPL/SQL blocks and subprograms. When it contains the PL/SQL engine, an Oracle server canprocess PL/SQL blocks and subprograms as well as single SQL statements. The Oracleserver passes the blocks and subprograms to its local PL/SQL engine.Anonymous BlocksAnonymous PL/SQL blocks can be embedded in an Oracle Precompiler or OCI program. Atrun time, the program, lacking a local PL/SQL engine, sends these blocks to the Oracleserver, where they are compiled and executed. Likewise, interactive tools such as SQL*Plusand Enterprise Manager, lacking a local PL/SQL engine, must send anonymous blocks toOracle.Stored SubprogramsSubprograms can be compiled separately and stored permanently in an Oracle database,ready to be executed. A subprogram explicitly CREATEd using an Oracle tool is called astored subprogram. Once compiled and stored in the data dictionary, it is a schema object,which can be referenced by any number of applications connected to that database. Storedsubprograms defined within a package are called packaged subprograms; those definedindependently are called stand-alone subprograms. (Subprograms defined within anothersubprogram or within a PL/SQL block are called local subprograms. They cannot be referencedby other applications and exist only for the convenience of the enclosing block.)Stored subprograms offer higher productivity, better performance, memory savings, applicationintegrity, and tighter security. For example, by designing applications around a library of storedprocedures and functions, you can avoid redundant coding and increase your productivity.You can call stored subprograms from a database trigger, another stored subprogram, anOracle Precompiler application, an OCI application, or interactively from SQL*Plus or EnterpriseManager. For example, you might call the stand-alone procedure create_dept fromSQL*Plus as follows:SQL> EXECUTE create_dept(’FINANCE’, ’NEW YORK’);Subprograms are stored in parsed, compiled form. So, when called, they are loaded andpassed to the PL/SQL engine immediately. Also, they take advantage of shared memory. So,only one copy of a subprogram need be loaded into memory for execution by multiple users.Database Triggers in OracleA database trigger is a stored subprogram associated with a table. You can have Oracleautomatically fire the database trigger before or after an INSERT, UPDATE, or DELETE statementaffects the table. One of the many uses for database triggers is to audit data modifications. 133
  • ORACLEFor example, the following database trigger fires whenever salaries in the emp table areupdated:CREATE TRIGGER audit_salAFTER UPDATE OF sal ON empFOR EACH ROWBEGININSERT INTO emp_audit VALUES ...END;You can use all the SQL data manipulation statements and any procedural statement in theexecutable part of a database trigger.Advantages of PL/SQLPL/SQL is a completely portable, high-performance transaction processing language thatoffers the following advantages:• support for SQL• support for object-oriented programming• better performance• portability• higher productivity• integration with OracleSupport for SQLSQL has become the standard database language because it is flexible, powerful, and easyto learn. A few English-like commands such as INSERT, UPDATE, and DELETE make it easyto manipulate the data stored in a relational database. SQL is non-procedural, meaning thatyou can state what you want done without stating how to do it. Oracle determines the bestway to carry out your request. There is no necessary connection between consecutivestatements because Oracle executes SQL statements one at a time.PL/SQL lets you use all the SQL data manipulation, cursor control, and transaction controlcommands, as well as all the SQL functions, operators, and pseudocolumns. So, you canmanipulate Oracle data flexibly and safely. Also, PL/SQL fully supports SQL datatypes. Thatreduces the need to convert data passed between your applications and the database.Object-Oriented Programming (OOP) in PL/SQLObject types are an ideal object-oriented modeling tool, which you can use to reduce the costand time required to build complex applications. Besides allowing you to create softwarecomponents that are modular, maintainable, and reusable, object types allow different teamsof programmers to develop software components concurrently.By encapsulating operations with data, object types let you move data-maintenance code outof SQL scripts and PL/SQL blocks into methods. Also, object types hide implementation 134
  • ORACLEdetails, so that you can change the details without affecting clientprograms.In addition, object types allow for realistic data modeling. Complex real-world entities andrelationships map directly into object types. That helps your programs better reflect the worldthey are trying to simulate.Better PerformanceWithout PL/SQL, Oracle must process SQL statements one at a time. Each SQL statementresults in another call to Oracle and higher performance overhead. In a networked environment,the overhead can become significant. Every time a SQL statement is issued, it must be sentover the network, creating more traffic.However, with PL/SQL, an entire block of statements can be sent to Oracle at one time. Thiscan drastically reduce communication between your application and Oracle. As Figure 1–5shows, if your application is database intensive, you can use PL/SQL blocks and subprogramsto group SQL statements before sending them to Oracle for execution. Fig.1-5: PL/SQL Boosts PerformancePL/SQL also improves performance by adding procedural processing power to Oracle tools.Using PL/SQL, a tool can do any computation quickly and efficiently without calling on theOracle server. This saves time and reduces network traffic. 135