Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this


  1. 1. 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
  2. 2. 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.
  3. 3. 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)
  5. 5. preface
  6. 6. 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
  7. 7. ORACLE10
  8. 8. 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
  9. 9. 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
  10. 10. 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
  11. 11. 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
  12. 12. 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
  13. 13. 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
  14. 14. 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
  15. 15. 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
  16. 16. 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
  17. 17. 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
  18. 18. 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
  19. 19. 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
  20. 20. 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
  21. 21. 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
  22. 22. 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
  23. 23. 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
  24. 24. 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
  25. 25. 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
  26. 26. 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
  27. 27. ORACLE30
  28. 28. 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
  29. 29. 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
  30. 30. 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
  31. 31. 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
  32. 32. 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
  33. 33. 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
  34. 34. 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
  35. 35. 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
  36. 36. 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
  37. 37. 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
  38. 38. 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
  39. 39. 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
  40. 40. 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
  41. 41. 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
  42. 42. 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
  43. 43. 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
  44. 44. 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
  45. 45. 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
  46. 46. 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