Siva Kumar HVK

Oracle 10g Structured Query Language (SQL)

1

Siva Kumar HVK

Table of Contents
Unit 1 Topic
Introduction to Oracle • What is Oracle • Oracle’s role in Client/Server Computing • What is Personal Oracle • Features of Oracle • Database Architecture • Overall System Architecture • Oracle Instance • SGA memory structure • Query process • Oracle versions • Oracle9i Features & Benefits • Oracle9i Products • What 9i supports • Data concurrency and consistency • Locking and Read Consistency • Environment • Summary Exercises OPERATORS AND QUERIES • Oracle Data types • Introduction to SQL • SQL in Application Programming • Writing simple queries • Expressions, conditions and Operators • Arithmetic Operators • Comparison Operators • Character Operators • Concatenation operator • Logical Operators • Miscellaneous Operators: IN, BETWEEN and DISTINCT • Distinct operator • Order by clause • Exercise FUNCTIONS • Predefined functions • Group functions • Aggregate functions • Single row functions • Arithmetic Functions • Character Functions • Conversion Functions • Date and Time Functions • Miscellaneous Functions • Exercise GROUP • • • • • • • AND HAVING CLAUSE GROUP BY CLAUSE ERROR with GROUP BY Clause Using Break CUBE and ROLLUP HAVING clause Points to remember Order of Execution Exercise

PageNo 03 - 30

2

31 – 57

3

58-110

4

111-126

5

NESTED • • • •

SUB QUERIES Single row sub queries Multi row sub queries Multi column sub queries Correlated sub queries.

127-142

2

Siva Kumar HVK
DML statements in sub queries ANY and ALL operators EXISTS And NOT EXISTS Operators Points to remember • Exercise INTEGRITY CONSTRAINTS • Integrity constraints • Table and Column level constraints • DDL statements • DML statements • COMMIT, ROLLBACK and SAVEPOINT • Implicit commit, Auto Rollback • Defining and Viewing constraints • Creating table from other tables • Referential Integrity constraints • Exercise JOINING TABLES • What is a Join • Perform an equi-join • Perform a non-equi-join • Perform an outer join • Join a table to itself • Left, right and full outer join • Natural and Inner joins • Cross join (cartesian product) Exercise OTHER OBJECTS • Sequence Object • Altering sequence • Views • Rules for deleting, updating and inserting rows • Index • Simple and Functional Index ADVANCED QUERIES • Top n analysis • Analitical queries • Rank, dense_rank, row_number • Case expressions • Nullif, nvl2, coalesec • Multiple insert and merge statements LOCKING MECHANISMS • What is Locking • DML and Dictionary locks • Explicit and Implicit Locking • Example SECURITY • What is Privilege • Object and system privileges • GRANT and REVOKE • Using Synonyms SQL*LOADER FLASHBACK QUERY ANNEXURE OCP QUESTIONS • • • •

6

143-163

7

164-180

8

181-192

9

193-201

10

202-203

11

204-206

12 13 14 15

207-211 212-224 225-231 232-258

3

Siva Kumar HVK

ORACLE
Course Day Session Estimated Time : : : : Oracle SQL 1 1 3 Hrs

Topics Introduction to Oracle Oracle’s Role in Client / Server Computing Oracle Features Database Architecture Overall System Structure Oracle Instance Query Process Oracle versions, features and Benefits Oracle9i – ORDBMS Data Concurrency And Consistency Environment Summary Exercise

4

Siva Kumar HVK

Presentation
Introduction
It is a DBMS, which manages a large amount of data in a multi user environment so that many users concurrently access the data. It also provides security and Recovery. It stores and manages data using relational model. Oracle is the name of database management system developed by Oracle Corporation. Oracle server manages data in the database. Users access Oracle server using SQL commands. So Oracle server receives SQL commands from users and executes them on the database.

SQL

ORACLE SERVER
CLIENT

Result

Database

CLIENT

5

Oracle is a database system that runs on the server. that accesses back-end running on the server. also called as front-end from clients. The following are some of the platforms on which Oracle runs. It is possible to develop an application using Personal Oracle and deploy it in a Client / Server environment. back-end may run on mainframe and front-end may be on a PC. runs on the server to manage database. which is also stored on the server. Client application and back-end run on different machines. Oracle server runs on different platforms. Back-end takes care of total database management. 6 . Applications running on the clients interact with the user. For example.Siva Kumar HVK Oracle’s Role in Client / Server Computing Client/Server computing is a method in which Database is stored on the server in the network A dedicated program. User access the data in database by running application. Novel Netware Unix What is Personal Oracle? Personal Oracle is one of the flavors of Oracle. In this Oracle server and client both run on the same machine. This is unlike other flavors where Oracle Server runs on Server and Front-end runs on Client. which may be of different types. The latest version of the Oracle server is 9i. The other name to database server is Back-End. called back-end. Windows NT. Personal Oracle can support up to 15 database connections. and used to manage the data.

Oracle server allows code to be stored in the database in the form of procedures and functions. Oracle adheres to industry standards for data access language. It is easy to port Oracle applications. This allows centralization of the code and reduces network traffic. which protects the investment of customer. It automatically locks and unlocks rows to maintain integrity of the data. Portability Oracle software can be ported to different operating systems and it is the name on all systems. 7 . Oracle server does all database management whereas Client does user interface. potentially hundreds of pita bytes in size. Data Security Oracle provides security in different levels – system level and object level. Support for Client / Server environment Oracle allows process to be split between client and server. Industry acceptance standards Oracle server is 100% compliant with Entry of the ANSI / ISO standards. Application development in Oracle can be ported to any operating system with little or no modifications. It also allows efficient usage of space by providing full control on space management.Siva Kumar HVK Features of Oracle The following are some of the important features of Oracle Server. Large Database Support Oracle supports largest database. Enforced Integrity Oracle allows users to define business rules and enforce them. These rules need not be included at the application level. network protocols etc. This makes Oracle an ‘open’ system. It also makes implementation of security easier through Roles. Data Concurrence Oracle supports concurrent access to database by multiple users.

Siva Kumar HVK Database Architecture A database contains any length of information. including the names of the other files in the database (Extension of file is ctl) Database Name Names and locations of data files and redo log files. It is physically a set of three operating system files. Path We can use this Oracle\oradata\orcl path in the server to see all the 3 types of files 8 . All changes made to the database are written to redo log file. we have to show only required information by hiding the unwanted information. In any RDBMS we can use 3 levels of data abstractions. The set of redo log files is known as databases redo log. Only Oracle Server can interpret these data files. Every table that is stored in the database is a part of these files. Redo Log Files Every database has a set of two or more Redo Log files. Data Files It contains the data of the database.log) Control Files Contain information required to verify the integrity of the database. (Filenames redo01. Data Files Redo log files Control files These files automatically create when database is created. This data hiding can be done using various data abstraction methods. But for the end user. Redo Log files are used in failure recovery. Physical level Logical Level View level Physical Level The Physical structure of the database is placed in Physical level.

Each Tablespace contains 65536 data files N number of such Table spaces creates a database. Every database contains SYSTEM tablespace.Siva Kumar HVK Logical Structure Logical Structure is independent of Physical structure. 9 . For example we can use a table space called PAYROLL to store all the data related to payroll application. N Number of continuous db blocks makes up an Extent. Example Table is a segment An Oracle database requires up to 4 types of segments Data segments Index Segments Rollback segments Temporary segments It is used to store data of tables Used to store indexes Undo information is stored Oracle stores Temporary tables Extents The storage space is allocated to segments is in the form of Extents. Each Oracle database contains the following components. An extent is made with in a data file. Segments Data into table spaces comes in the form of segments. By making a tablespace off-line. It is possible to make tablespace temporarily unavailable by making it off-line and makes it available again by changing it to on-line. Tablespaces Segments Extents Blocks Tablespace Each Database is a collection of tablespaces. SYSTEM tablespace contains the data dictionary tables. This is automatically created when a database is created. DBA can take the backup.

Figure 1 illustrates a typical variation of ORACLE's memory and process structures. It is important that you read through this section to familiarize yourself with the concepts and terminology to be used throughout this manual. some of the memory structures and processes in this diagram are discussed in the following section.'' 10 . see page 115 of ``ORACLE7 Server Concepts Manual. Before you can begin to use ORACLE. Most of the information contained in this section is DIRECTLY extracted from ``ORACLE7 Server Concepts Manual'' and all credit should be attributed to ORACLE.Siva Kumar HVK ORACLE Architecture and Terminology This section will provide a basic understanding of ORACLE including the concepts and terminology of the ORACLE Server. you must have a basic understanding of the architecture of ORACLE to help you start thinking about an ORACLE database in the correct conceptual manner. For more information on these memory structures and processes.

ORACLE Architecture 11 .Siva Kumar HVK Figure 1.

memory is used to store program code being executed and data that is shared among users. The information in a PGA depends on the configuration of ORACLE.Siva Kumar HVK Memory Structures and Processes The mechanisms of ORACLE execute by using memory structures and processes. All memory structures exist in the main memory of the computers that constitute the database system. Processes are jobs or tasks that work in the memory of these computers. A user process is created and maintained to execute the software code of an application program (such as a PRO*C program) or an ORACLE tool (such as SQL*PLUS). Some operating systems use the terms job or task. Processes A process is a ``thread of control'' or a mechanism in an operating system that can execute a series of steps. The Program Global Area (PGA) is a memory buffer that contains data and control information for a server process. Each instance that is started has its own SGA. User processes communicate with the server processes through the program interface. Memory Structures ORACLE creates and uses memory structures to complete several jobs. 12 . The SGA is allocated when an instance starts and deallocated when the instance shuts down. Several basic memory structures are associated with ORACLE: the system global area (which includes the database and redo log buffers. For example. A PGA is created by ORACLE when a server process is started. An ORACLE database system has two general types of processes: user processes and ORACLE processes. and the shared pool) and the program global area. An ORACLE instance contains the SGA and the background processes. The user process also manages the communication with the server processes. System Global Area (SGA) is a shared memory region allocated by ORACLE that contains data and control information for one ORACLE instance.

Integrity Rule Integrity rules are the laws that govern which operations are allowed on the data and structures of a database. ORACLE creates a server process to handle requests from connected user processes. including tablespaces. the database's schema objects (e. sequences. ORACLE also creates a set of background processes for each instance (see ``ORACLE7 Server Concepts Manual'' pages 1-18.. By separating physical and logical database structure. Integrity rules protect the data and the structures of a database. An ORACLE database has both a physical and a logical structure. 13 . The schema objects and the relationships among them form the relational design of a database.Siva Kumar HVK ORACLE processes are called by other processes to perform functions on behalf of the invoking process.g. Operations Operations are clearly defined actions that allow users to manipulate the data and structures of a database. 1-19). Database Structures The relational model has three major aspects: Structures Structures are well-defined objects that store the data of a database. clusters. indexes. The logical storage structures. The operations on a database must adhere to a pre-defined set of integrity rules. tables. views. stored procedures). and extents. segments. the physical storage of data can be managed without affecting the access to logical storage structures. Structures and the data contained within them can be manipulated by operations. Logical Database Structure An ORACLE database's logical structure is determined by: • • one or more tablespaces. dictate how the physical space of a database is used.

tablespaces. tablespaces and data files Each tablespace in an ORACLE database is comprised of one or more operating system files called data files. and tablespaces When a schema object such as a table or index is created. An object's segment allocates space in only one tablespace of a database. the simplest ORACLE database would have one tablespace. Although databases. A tablespace's data files physically store the associated database data on disk. data files. The space for this table's data segment is allocated in one or more of the data files that constitute the specified tablespace. segments. its segment is created within a designated tablespace in the database. with one data file. A more complicated database might have three tablespaces. and segments are closely related. 14 . Figure 2 illustrates this relationship. they have important differences: databases and tablespaces An ORACLE database is comprised of one or more logical storage units called tablespaces. The database's data is collectively stored in the database's tablespaces. The usable data of an ORACLE database is logically stored in the tablespaces and physically stored in the data files associated with the corresponding tablespace. schema objects.Siva Kumar HVK Tablespaces and Data Files Tablespaces are the primary logical storage structures of any ORACLE database. For example. For example. suppose a table is created in a specific tablespace using the CREATE TABLE command with the TABLESPACE option. each comprised of two data files (for a total of six data files). databases and data files A database's data is collectively stored in the data files that constitute each tablespace of the database.

Assign specific space quotas for database users. 15 . which is automatically created when the database is created. Allocate data storage across devices to improve performance.Siva Kumar HVK Figure 2. for example. A database administrator can use tablespaces to do the following: • • • • • Control disk space allocation for database data. Data Files and Tablespaces A database is divided into one or more logical storage units called tablespaces. Perform partial database backup or recovery operations. The SYSTEM tablespace always contains the data dictionary tables for the entire database. Control availability of data by taking individual tablespaces online or offline. You can query these data dictionary tables to obtain pertinent information about the database. the names of the tables that are owned by you or ones to which you have access. Every ORACLE database contains a tablespace named SYSTEM.

and segments. For example. while each index's data is stored in its own index segment.Siva Kumar HVK Data files associated with a tablespace store all the database data in that tablespace. when the existing extents of a segment are full. ORACLE blocks. The database administrator and endusers cannot control which data file stores an object. rather. An extent cannot span files. though. therefore. Because extents are allocated as needed. rollback segments. an ORACLE database's data is stored in data blocks (also called logical blocks. The units of logical database allocations are data blocks. and all are stored in the same tablespace. however. Therefore. The data in the segments of objects (data segments. 16 . the space is reserved to hold only the data for future segments of the associated tablespace . Note that a schema object does not correspond to a specific data file. extents. each table's data is stored in its own data segment.it cannot store any other program's data. and may or may not span files. Figure 3 illustrates the relationships between these data structures. As a segment (such as the data segment for a table) is created and grows in a tablespace. Segments The level of logical database storage above an extent is called a segment. an object can ``span'' one or more data files. Figure 4 illustrates a typical ORACLE data block. After a data file is initially created. and only one database. the extents of a segment may or may not be contiguous on disk. the allocated disk space does not contain any data. and Segments ORACLE allocates database space for all data in a database. or pages). a data file is a repository for the data of any object within a specific tablespace. An ORACLE database uses and allocates free database space in ORACLE data blocks. ORACLE uses the free space in the associated data files to allocate extents for the segment. Extents. ORACLE allocates another extent for that segment. A data file can be associated with only one tablespace. An extent is a specific number of contiguous data blocks that are allocated for storing a specific type of information. A segment is a set of extents which have been allocated for a specific type of data structure. Data Blocks At the finest level of granularity. One or more datafiles form a logical unit of database storage called a tablespace. Extents The next level of logical database space is called an extent. index segments. and so on) in a tablespace are physically stored in one or more of the data files that constitute the tablespace. Data Blocks. ORACLE allocates space for segments in extents. The extents of a single segment can be allocated in one or more data files of a tablespace (see Figure 3).

The Relationship Among Segments. A data block corresponds to a block of physical bytes on disk. or clustered data. index. A data block is the smallest unit of I/O used by a database.2048). 17 . equal to the ORACLE data block size (specifically set when the database is created . Figure 4 shows the format of the block. The ORACLE block format is similar regardless of whether the data block contains table. Extents and Data Blocks ORACLE manages the storage space in the data files of a database in units called data blocks.Siva Kumar HVK Figure 3. This block size can differ from the standard I/O block size of the operating system that executes ORACLE.

index. Row Data This portion of the block contains table or index data. Data Block Format Header (Common and Variable) The header contains general block information. this space is not reclaimed when the row is deleted. While some block overhead is fixed in size (about 107 bytes).Siva Kumar HVK Figure 4. segment type. Once the space has been allocated in the row directory of a block's header. Table Directory The table directory portion of the block contains information about the tables having rows in this block. Rows can span blocks. the total block overhead size is variable. or rollback. such as block address. Row Directory This portion of the block contains row information about the actual rows in the block (including addresses for each row piece in the row data area). such as data. 18 .

ORACLE automatically allocates an incremental extent for that segment. No matter what type.g. assume that you specify the following parameter within a CREATE TABLE statement: pctused 40 In this case. Space Used for Transaction Entries Data blocks allocated for the data segment of a table. This extent is called the segment's initial extent. cluster. as determined by PCTFREE. Both of these parameters can only be specified when creating or altering tables and clusters (data segments). Two space management parameters. For example. the storage parameter PCTFREE can also be specified when creating or altering indicies (index segments). when a trailing null is updated to a non-null value). or the index segment of an index can also use free space for transaction entries. In addition. allow a developer to control the use of free space for inserts of and updates to the rows in data blocks. each segment in a database is created with at least one extent to hold its data. PCTFREE and PCTUSED.Siva Kumar HVK Free Space Free space is used to insert new rows and for updates to rows that require additional space (e. Whether issued insertions actually occur in a given data block is a function of the value for the space management parameter PCTFREE and the amount of current free space in that data block. The PCTFREE parameter is used to set the percentage of a block to be reserved (kept free) for possible updates to rows that already are contained in that block. Before this value is achieved. a data block used for this table's data segment is not considered for the insertion of any new rows until the amount of used space in the blocks falls to 39\% or less (assuming that the block's used space has previously reached PCTFREE). the block is not considered for the insertion of new rows until the percentage of the block being used falls below the parameter PCTUSED. For example. After a data block becomes full. If the data blocks of a segment's initial extent become full and more space is required to hold new data. the free space of the data block can only be used for updates to rows already contained in the data block. assume that you specify the following parameter within a CREATE TABLE statement: pctfree 20 This states that 20\% of each data block used for this table's data segment will be kept free and available for possible updates to the existing rows already within each block. An incremental extent is a 19 ..

Storage parameters for a table. Every non-clustered table in an ORACLE database has a single data segment to hold all of its data.Siva Kumar HVK subsequent extent of the same or incremented size of the previous extent in that segment. and one or more control files.'' Physical Database Structure An ORACLE database's physical structure is determined by the operating system files that constitute the database. or cluster control the way that a data segment's extents are allocated. The files of a database provide the actual physical storage for database information. see ``ORACLE7 Server Concepts Manual. Setting these storage parameters directly via the CREATE TABLE/SNAPSHOT/CLUSTER or ALTER TABLE/SNAPSHOT/CLUSTER commands affects the efficiency of data retrieval and storage for that data segment.'' 20 . For more information on these physical storage files. two or more redo log files. see ``ORACLE7 Server Concepts Manual. For more information on Data Blocks. Each ORACLE database is comprised of these types of files: one or more data files. The data segment for a table is indirectly created via the CREATE TABLE/SNAPSHOT command. snapshot. Segments and Extents.

Maintaining the Free Space of Data Blocks with PCTFREE and PCTUSED 21 .Siva Kumar HVK Figure 5.

Siva Kumar HVK Overall System Structure A database system is partitioned into modules. The functional components of a database system are Query processor Component Storage manager component Query Processor Component This component is a collection of the following processes. DML Compiler : It translates DML statements into a lower level instructions that the query evaluation engine understands Embedded DML precompiler It converts DML statements embedded in an application program into normal procedure calls in the host language. Authorization and Integrity manager It tests for satisfaction of integrity constraints and checks the authority of users to access data. which handles different responsibilities of over all system. DDL Interpreter It interprets DDL statements and records them in a set of tables Query evaluation engine It executes lower level instructions generated by the DML compiler Storage manager component It is an Interface between the data stored in the database. application programs and queries submitted to the system. Transaction Manager It ensures concurrent transaction executions processed without conflicting. 22 . Buffer manager This is responsible for fetching data from disk storage into main memory. File manager It manages the allocation of space on disk and the data structures used to represent information.

read from the data dictionary. and written to. The database buffer cache is used to store the most recently used data. the data files.Siva Kumar HVK Oracle Instance Every oracle database is associated with an Oracle Instance. The redo log buffer is used to track changes made to the database by the server and background processes. The data is read from. Every time a database is started. The combination of SGA and Oracle processes is called as Oracle Instance. a memory area called System Global Area (SGA) or Shared Global Area is allocated and one or more processes are started. in the case of stored procedures. These SQL statements may be submitted by a user process or. SGA consists of several memory structures: The shared pool is used to store the most recently executed SQL statements and the most recently used data from the data dictionary. 23 .

it automatically creates two different processes called as User process and Server Process. and a parsed representation of the SQL statement is loaded into a shared SQL area. The user process is the application program that originates SQL statements. the SQL statement is passed from the user process to the server process. The server process executes the statements sent from the user process.Siva Kumar HVK Query process 1 Parse 2 Execute 3 Fetch 3 Server Process DB 1 User Process 2 Client When User connects to the database. There are three main stages in the processing of a query: Parse Execute Fetch Parsing During the parse stage. the server process performs the following functions: Searches for an existing copy of the SQL statement in the shared pool validates the SQL statement by checking its syntax Performs data dictionary lookups to validate table and column definitions 24 . During the parse.

The processing of a DELETE or INSERT command uses similar steps. DML Processing Steps A data manipulation language (DML) statement requires only two phases of processing: Parse is the same as the parse phase used for processing a query Execute requires additional processing to make data changes DML Execute Phase The server process records the before image to the rollback block and updates the data block. Because the changes made to the blocks are only recorded in memory structures and are not written immediately to disk. and the before image of an INSERT contains the row location information. a computer failure that causes the loss of the SGA can also lose these changes. 25 .Siva Kumar HVK Execute Execute: Identify rows selected The steps to be taken when executing the statement The optimizer is the function in the Oracle Server that determines the optimal execution plan. Fetch Fetch: Return rows to user process. it can fetch 20 records at a time. With each fetch process. Both of these changes are done in the database buffer cache. buffers that are not the same as the corresponding blocks on the disk. Any changed blocks in the buffer cache are marked as dirty buffers: that is. The before image for a DELETE contains the column values in the deleted row.

deploy and manage Internet applications.Siva Kumar HVK Oracle Versions Oracle Oracle Oracle Oracle Oracle Oracle Oracle Oracle Oracle 6. PL/SQL.0 7.It provides everything needed to develop. Benefits Scalability from departments to enterprise e-business sites Reliable.1 7.3 8.0 8i 9i 10g 1990 1995 1996 1997 1998 1999 2000 2001 2003 Object based ORDBMS Internet based Application Application server Features & Benefits Oracle Scalability One Management Interface 9i Reliability Internet Common Skill Sets Single Dev Model Features Oracle offers a comprehensive high performance infrastructure for ebusiness. easy development options Common skill sets including SQL.0 7.2 7. It is called Oracle9i.JAVA and XML One Management interface for all applications 26 . available and secure architecture One development model.

Application Server 9i Application server runs all the applications and 9i database stores our data. applications and data 27 .Siva Kumar HVK 9i Products There are two products. They provide a complete and simple infrastructure for Internet applications. Oracle 9i Application server runs Portals or web sites Java Transactional Applications Provides integration between users.

But the goal of the database system is to reduce wait time so that it is negligible to each user. Oracle returns a timepoint-based version of data. the data retrieved is consistent with the time at which the query started. So any changes made to database since query started will not be available. One way of managing data concurrency is by making other users wait until their turn comes.Siva Kumar HVK Oracle9i: ORDBMS Oracle is the first object-capable database developed by Oracle Corporation. It extends the data modeling capabilities of Oracle 8 to support a new object relational database model. 28 . when a user is accessing the data. and full compatibility with the relational world. when user X is modifying a row. Oracle uses locking mechanism and multiversioning to increase data concurrency while maintaining data integrity. That means. Note: it is the responsibility of the application developer to unlock rows that are locked by committing or rolling back the transaction. complex data types. For instance. At the same time data integrity should not be compromised. Locks are used to prevent destructive interference. it is locked so that other users cannot modify it until X completes modification. it doesn’t stop users querying the row. Oracle 9i supports User-Defined data types and objects Fully compatible with relational database (It supports all the CODD rules) Support of multimedia and Large objects It also support client server and web based applications Oracle 9i can scale tens of thousands of concurrent users and support up to 512 peta bytes of data (One pita byte = 1000 tera bytes and One terabyte = 1000 GB). Data Concurrency And Consistency Data concurrency allows many users to access the same data at the same time. Read Consistency For a query. However. Oracle provides a new engine that brings objectoriented programming. Locking Oracle uses Locks to control data concurrency. That means users reading the data will not be interrupted by user modifying and vice-versa. complex business objects.

in the query result.Siva Kumar HVK Ready consistency is made possible In Oracle using Rollback segment. doesn’t have to be implemented on each machine 29 . Rollback segment keeps a copy of unchanged data. if they attempt to update identical rows at the same time. This ensures readers do not wait for writers and vice-versa and ensures that writers only wait for other writers. does not have to be implemented on each machine Difference between SQL*Plus and ISQL*plus SQL*Plus is a CUI and iSQL*Plus runs on a browser SQL*plus should be loaded in each every client system. centrally loaded. This data is substituted for the data that has changed since query started. ISQL*plus is (Available only from Oracle 9i) An Environment Oracle proprietary Keywords can be abbreviated Runs on a browser Centrally loaded. SQL*plus and iSQL*plus. where as iSQL*plus. Environment Oracle uses two types of Environments for executing our SQL statements.

Oracle runs on the server as back-end to manage the data. In a Client/Server environment. to rollback segment to provide read consistency. The logical structure of the database is independent of physical structure of the database. where each process does a specific job. User is concerned with only the logical structure of the database. before the row is changed.Siva Kumar HVK Summary Oracle is RDBMS. An Oracle Instance is the combination of SGA and Oracle process. It copies the data of a row. 30 . Oracle instance contains a collection of background processes. Oracle uses locking mechanism to manage data concurrency.

Siva Kumar HVK Exercise 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) SGA stands for _______________________________ _____________ is the name of the tablespace that is automatically created when a database is created. In which segment the data of a table is stored? What is the difference between Personal Oracle and Client/Server Oracle Redo Log files are also called as ______________ File extension of control file is ___________ ________ Number of data files are there in each table space What is Oracle Instance? What is the maximum storage capacity of Oracle database What is Application server? 31 .

Expressions and Expressions 32 .Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 1 2 2 Hrs Topics Oracle data types Introduction to SQL An overview of SQL SQL in Application programming Structured Query Language SQL statements Simple Queries Operators.

Padded on right with blanks to full length of size. Character Data types CHAR Data type VARCHAR2 and VARCHAR Data types NCHAR and NVARCHAR2 Data types LONG Data type NUMBER Data type DATE Data type LOB Data types BLOB data type CLOB and NCLOB data types BFILE Data type RAW and LONG RAW Data types Character Datatypes The character data types store character (alphanumeric) data in strings. VARCHAR2 (size) Variable length characters strings having a maximum size of 4000 bytes (Default size is 1). Truncates leftover blank spaces. When you create a table. Truncates leftover blank spaces. depending on the choice of national character set. you must specify a data type for each of its columns. NVARCHAR2(size) Variable length characters strings having a maximum size of 4000 bytes (Default size is 1) Or characters. which is associated with a specific storage format. CHAR datatype Fixed length character data of length size in bytes. constraints.Siva Kumar HVK Presentation Oracle Datatypes Each column value and constant in a SQL statement has a data type. 33 . and a valid range of values.( Default size is 1 and maximum size is 2000). Oracle provides the following builtin data types. with byte values corresponding to the character.

BLOB 34 . otherwise the same as LONG. Only one LONG column is allowed in a table. TIMESTAMP(precision) WITH TIME ZONE Timestamp plus time zone displacement value.2) could nothing larger than 999. NUMBER (5. LONG Character data of variable size up to 2GB in length. For example.99 without an error. TIMESTAMP(precision) WITHLOCAL TIME ZONE TIMESTAMP. Long column cannot be used in sub queries.4712 BC to December 31. Maximum size is 2000 bytes. where precision is the number of digits in the fractional part of the seconds field (default is 6). where clause or indexes. CLOB Character Large object. DATE Valid date ranges from January 1.Siva Kumar HVK NUMBER(size. with normalized to local time zone. LONG RAW Raw binary data. (Default date format DD-MON-YY) TIMESTAMP(precision) Date plus time.9999 AD. up to 4GB in length. functions. These two data types allow storing pictures. size bytes long. RAW(size) Raw binary date.d) For number column specified with d digits after the decimal point. expressions.

up to 4GB in length. BFILE Pointer to a binary operating system file. 35 .Siva Kumar HVK Binary large object.

in contrast to the procedural or third generation languages (3GLs) such as COBOL and C that had been created up to that time. The characteristic that differentiates a DBMS from an RDBMS is that the RDBMS provides a set-oriented database language. Although these standard-making bodies prepare standards for database system designers to follow. NOTE: Nonprocedural means what rather than how. that can still be bought today for various platforms and environments). In technology in a single-user business application positions the application for future growth. The initials stand for Structured Query Language. For example. In fact. SQL enables a programmer or database administrator to do the following: Modify a database's structure Change system security settings Add user permissions on databases or tables Query a database for information Update the contents of a database 36 . and the language itself is often referred to as "sequel. SQL makes an RDBMS possible.Siva Kumar HVK Introduction to SQL A Brief History of SQL The history of SQL begins in an IBM laboratory in San Jose. rather than how to perform the operation. Two standards organizations. all database products differ from the ANSI standard to some degree. For most RDBMS. The ANSI-92 standard is the standard for the SQL used throughout this book. or RDBMS. Set oriented means that SQL processes sets of data in groups. An Overview of SQL SQL is the standard language used to manipulate and retrieve data from these relational databases. the American National Standards Institute (ANSI) and the International Standards Organization (ISO). or insert. SQL is a nonprocedural language." It was originally developed for IBM's DB2 product (a relational database management system. California. SQL describes what data to retrieve. this set-oriented database language is SQL. currently promote SQL standards to industry. where SQL was developed in the late 1970s. delete.

Siva Kumar HVK Structured Query Language Oracle server supports ANSI standard SQL and contains extensions. retrieve. and manipulate data in the tables. you can communicate with the Oracle server. Using SQL. SQL has the following advantages • • • Efficient Easy to learn and use Functionally complete (With SQL. you can define.) SQL Statements SELECT INSERT UPDATE DELETE MERGE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT GRANT REVOKE Data retrieval Data manipulation language(DML) Data definition language (DDL) Transaction control Data control language (DCL) 37 .

For example. the semicolon at the end of the statement tells the interpreter that you are finished writing the query.Siva Kumar HVK SELECT AND FROM It is a building block for data retrieval in SQL. because your query is typed in an edit box and executed when you push a button.--------. Your First Query INPUT: SQL> select * from EMP. 38 . OUTPUT: EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO -----. The database determines the order in which to return the columns. Syntax : SELECT <COLUMNS> FROM <TABLE>. f ll bl i d h h i h l Terminating an SQL Statement In some implementations of SQL.--------. On the other hand.---------. The asterisk (*) in select * tells the database to return all the columns associated with the given table described in the FROM clause.---------. For example. some implementations of SQL do not use the semicolon as a terminator. Microsoft Query and Borland's ISQL don't require a terminator.---------7369 SMITH CLERK 7902 17-DEC-80 800 20 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 7566 JONES MANAGER 7839 02-APR-81 2975 20 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 7782 CLARK MANAGER 7839 09-JUN-81 2450 10 7788 SCOTT ANALYST 7566 09-DEC-82 3000 20 7839 KING PRESIDENT 17-NOV-81 5000 10 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30 7876 ADAMS CLERK 7788 12-JAN-83 1100 20 7900 JAMES CLERK 7698 03-DEC-81 950 30 7902 FORD ANALYST 7566 03-DEC-81 3000 20 7934 MILLER CLERK 7782 23-JAN-82 1300 10 ANALYSIS: Notice that columns 6 and 8 in the output statement are right justified and that columns 2 and 3 are left justified. Oracle's SQL*PLUS won't execute the query until it finds a semicolon (or a slash). This format follows the alignment convention in which numeric data types are right justified and character data types are left justified.---------.---------.

Numeric. and Operators Expressions The definition of an expression is simple: An expression returns a value. SAL FROM EMP. for example) is an expression. and Boolean.---------. In fact. examine the following expression: WHERE ENAME = 'KING' It contains a condition. SAL are expressions: SELECT ENAME. Conditions. covering different data types such as String. In the following example amount is an expression that returns the value contained in the amount column. pretty much anything following a clause (SELECT or FROM. comm from EMP. DESIGNATION. ENAME = 'KING'. In the following statement NAME. Expression types are very broad. ENAME = 'KING' will be either TRUE or FALSE. sal. SELECT sal FROM EMP. OUTPUT EMPNO ---------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME SAL JOB COMM ---------. job. 39 .---------SMITH 800 CLERK ALLEN 1600 SALESMAN 300 WARD 1250 SALESMAN 500 JONES 2975 MANAGER MARTIN 1250 SALESMAN 1400 BLAKE 2850 MANAGER CLARK 2450 MANAGER SCOTT 3000 ANALYST KING 5000 PRESIDENT TURNER 1500 SALESMAN 0 ADAMS 1100 CLERK JAMES 950 CLERK FORD 3000 ANALYST MILLER 1300 CLERK 14 rows selected. Now.Siva Kumar HVK Changing the Order of the Columns We can change the order of selection of columns INPUT: SQL> SELECT empno. DESIGNATION. depending on the condition =.--------. ename. Expressions. which is an example of a Boolean expression.

---------. you could type INPUT/OUTPUT: SQL> SELECT * FROM EMP WHERE ENAME = 'KING'. The WHERE Clause The syntax of the WHERE clause is SYNTAX: SELECT <COLUMNS> FROM <TABLE> WHERE <SEARCH CONDITION>. In the second example the variable is SAL. Without the WHERE clause. and WHERE are the three most frequently used clauses in SQL. In the preceding example.-------------------------------7839 KING PRESIDENT 17-NOV-81 5000 10 ANALYSIS: This simple example shows how you can place a condition on the data that you want to retrieve.--------. In the first example the variable is ENAME. your condition would be SAL > 2000 Conditions enable you to make selective queries. FROM. SELECT. Which would yield only one record: EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO -----. the condition is ENAME = 'KING' To find everyone in your organization who worked more than 100 hours last month. you need one or more conditions.--------. In there most common form. conditions comprise a variable. the constant is 'KING'. If you wanted a particular EMPLOYEE. WHERE simply causes your queries to be more selective. If you wanted a particular EMPLOYEE. and a comparison operator. the constant is 100. You need to know about two more elements before you can write conditional queries: the WHERE clause and operators. and the comparison operator is >. and the comparison operator is =. the most useful thing you could do with a query is display all records in the selected table(s). Conditions are contained in the WHERE clause. a constant. you could type 40 .---------.---------.---------.Siva Kumar HVK Conditions If you ever want to find a particular item or group of items in your database.

OR SQL> SELECT * FROM BIKES WHERE ENAME <> 'KING'. Operators Operators are the elements you use inside an expression to articulate how you want specified conditions to retrieve data. logical.Siva Kumar HVK INPUT SQL> SELECT * FROM BIKES WHERE ENAME != 'KING'. Modulo returns the integer remainder of a division. multiply (*). Arithmetic Operators The arithmetic operators are plus (+). character. 41 . OUTPUT EMPNO ENAME JOB 7369 SMITH CLERK 7499 ALLEN SALESMAN 7521 WARD SALESMAN 7566 JONES MANAGER 7654 MARTIN SALESMAN 7698 BLAKE MANAGER 7782 CLARK MANAGER 7788 SCOTT ANALYST 7844 TURNER SALESMAN 7876 ADAMS CLERK 7900 JAMES CLERK 7902 FORD ANALYST 7934 MILLER CLERK MGR HIREDATE 7902 17-DEC-80 7698 20-FEB-81 7698 22-FEB-81 7839 02-APR-81 7698 28-SEP-81 7839 01-MAY-81 7839 09-JUN-81 7566 09-DEC-82 7698 08-SEP-81 7788 12-JAN-83 7698 03-DEC-81 7566 03-DEC-81 7782 23-JAN-82 SAL 800 1600 1250 2975 1250 2850 2450 3000 1500 1100 950 3000 1300 COMM 300 500 1400 DEPTNO 20 30 30 20 30 30 10 20 30 20 30 20 10 0 ANALYSIS: Displays all the employees other than KING. minus (-). Operators fall into six groups: arithmetic. The first four are self-explanatory. comparison. set. divide (/). and miscellaneous.

Siva Kumar HVK Comparison Operators True to their name. to test for a NULL condition. SELECT * FROM EMP WHERE SAL NOT BETWEEN 3000 AND 4000. It does not mean a column has a zero or a blank in it. SELECT * FROM EMP WHERE SAL >= 3000 AND SAL <= 4000. IS NULL. To understand how you could get an Unknown. NULL means nothing is in that field. SELECT * FROM EMP WHERE COMM IS NOT NULL. If you make a comparison like Field = 9 and the only value for Field is NULL. 42 . SELECT * FROM EMP WHERE SAL BETWEEN 3000 AND 4000. In database terms NULL is the absence of data in a field. you need to know a little about the concept of NULL. comparison operators compare expressions and return one of three values: TRUE. FALSE. Because Unknown is an uncomfortable condition. the comparison will come back Unknown. or Unknown. SELECT * FROM EMP WHERE SAL >= 2000. SELECT * FROM EMP WHERE COMM IS NULL. most flavors of SQL change Unknown to FALSE and provide a special operator. A zero or a blank is a value.

This section describes two character operators: the LIKE operator and the || operator. both in the output of data and in the process of placing conditions on data to be retrieved. which conveys the concept of character concatenation. but that process would be time-consuming. Consider the following: INPUT: SELECT * FROM EMP WHERE ENAME LIKE ‘A%’. ANALYSIS Displays all the employees whose names not beginning with letter A 43 .Siva Kumar HVK Character Operators You can use character operators to manipulate the way character strings are represented. you could use LIKE. LIKE operator What if you wanted to select parts of a database that fit a pattern but weren't quite exact matches? You could use the equal sign and run through all the possible cases. Instead. ANALYSIS Displays all the employees whose names begins with letter A INPUT: SELECT * FROM EMP WHERE ENAME NOT LIKE ‘A%’.

INPUT: SELECT * FROM EMP WHERE SAL LIKE ‘4%’. ANALYSIS Displays all the names whose name contains letter A more than one time INPUT: SELECT * FROM EMP WHERE HIREDATE LIKE ‘%DEC%’. (Implicit data conversion takes place). ANALYSIS Displays all the employees whose salary begins with number 4. INPUT: SELECT * FROM EMP WHERE HIREDATE LIKE ‘%81’.Siva Kumar HVK INPUT: SELECT * FROM EMP WHERE ENAME LIKE ‘%A%’. 44 . ANALYSIS Displays all the employees who joined in the year 81. ANALYSIS Displays all the employees who joined in the month of December. ANALYSIS Displays all the employees whose names contains letter A (Any number of A’s) INPUT: SELECT * FROM EMP WHERE ENAME LIKE ‘%A%A%’.

Siva Kumar HVK Underscore (_) The underscore is the single-character wildcard. OUTPUT: EMPNO ---------7521 7654 7900 ENAME ---------WARD MARTIN JAMES ANALYSIS Displays all the employees whose second letter is A INPUT: SQL> SELECT * FROM EMP WHERE ENAME LIKE ‘__A%’. OUTPUT: ENAME ---------AVINASH_K ANAND_VARDAN ADAMS_P ANALYSIS Displays all the employees with underscore (_). 45 . ‘\’ Escape character Underscore is used to identify a position in the string. OUTPUT: ENAME ---------BLAKE CLARK ADAMS ANALYSIS Displays all the employees whose third letter is A (Two underscores followed by A) INPUT: SQL> SELECT * FROM EMP WHERE ENAME LIKE ‘A%\_%’ ESCAPE ‘\’.ENAME FROM EMP WHERE ENAME LIKE ‘_A%’. INPUT: SQL> SELECT EMPNO. To treat _ as a character we have to use Escape (\) character.

‘ || JOB FROM EMP. SALESMAN ADAMS . SALESMAN WARD .Siva Kumar HVK Concatenation ( ||) operator Used to combine two given strings INPUT SELECT ENAME || JOB FROM EMP. OUTPUT ENAME||'. SALESMAN JONES .'||JOB ---------------------SMITH . OUTPUT ENAME||JOB ------------------SMITHCLERK ALLENSALESMAN WARDSALESMAN JONESMANAGER MARTINSALESMAN BLAKEMANAGER CLARKMANAGER SCOTTANALYST KINGPRESIDENT TURNERSALESMAN ADAMSCLERK JAMESCLERK FORDANALYST MILLERCLERK ANALYSIS Combines both name and designation as a single string. MANAGER MARTIN . CLERK FORD . PRESIDENT TURNER . CLERK JAMES . MANAGER CLARK . ANALYST KING . INPUT SQL>SELECT ENAME || ‘ . CLERK ALLEN . 46 . SALESMAN BLAKE . ANALYST MILLER . CLERK ANALYSIS Combines both name and designation as a single string separated by. MANAGER SCOTT .

SELECT * FROM EMP WHERE SAL NOT BETWEEN 3000 AND 4000. SELECT * FROM EMP WHERE SAL BETWEEN 3000 AND 4000. SELECT * FROM EMP WHERE SAL >= 3000 AND SAL <= 4000.Siva Kumar HVK Logical Operators INPUT: SELECT ENAME FROM EMP WHERE ENAME LIKE ‘%A%’ and ENAME NOT LIKE ‘%A%A%’ OUTPUT ENAME ---------ALLEN WARD MARTIN BLAKE CLARK JAMES ANALYSIS Displays all the employees whose names contains letter A exactly one time. 47 .

INPUT: SQL> SELECT * FROM EMP WHERE JOB IN('CLERK'. The above statement takes more time to parse it.'MANAGER'). clerk.Siva Kumar HVK Miscellaneous Operators: IN. JOB FROM EMP WHERE JOB= 'CLERK' OR JOB =‘MANAGER’ OR JOB = 'SALESMAN'. You could type the following: INPUT: SQL> SELECT ENAME. which reduces the efficiency. BETWEEN and DISTINCT The two operators IN and BETWEEN provide shorthand for functions you already know how to do. OUTPUT: ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK TURNER ADAMS JAMES MILLER JOB --------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER SALESMAN CLERK CLERK CLERK ANALYSIS Display employees with designations manager. 48 .'SALESMAN'. and salesman. and salesman. clerk. OUTPUT: ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK TURNER ADAMS JAMES MILLER JOB --------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER SALESMAN CLERK CLERK CLERK ANALYSIS Display employees with designations manager.

OUTPUT: ENAME ---------BLAKE SCOTT HIREDATE --------01-MAY-81 09-DEC-82 ANALYSIS Note : Efficiency is more when we write the query using IN operator rather than OR operator.JOB FROM EMP WHERE JOB NOT IN('CLERK'. OUTPUT: ENAME ---------SCOTT KING FORD JOB --------ANALYST PRESIDENT ANALYST ANALYSIS Display designations other than manager.HIREDATE FROM EMP WHERE HIREDATE IN (’01-MAY-1981’.Siva Kumar HVK INPUT: SQL> SELECT ENAME. clerk. and salesman INPUT: SQL> SELECT ENAME.'SALESMAN'.’09-DEC-1982’). 49 .'MANAGER').

50 . OUTPUT: JOB --------ANALYST CLERK MANAGER PRESIDENT SALESMAN ANALYSIS Distinct operator displays unique designations.Siva Kumar HVK DISTINCT OPERATOR INPUT: SQL> SELECT DISTINCT JOB FROM EMP. Distinct operator by default displays the information in ascending order.

Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 1 3 2 Hrs Topics Order BY clause Exercise Functions Group functions 51 .

OUTPUT ENAME ---------ADAMS ALLEN BLAKE CLARK FORD JAMES JONES KING MARTIN MILLER SCOTT SMITH TURNER WARD ANALYSIS Display employees in ascending order of names. 52 .Siva Kumar HVK Presentation ORDER BY CLAUSE Display the information in a particular order (Ascending or descending order) Syntax SELECT <COLUMNS> FROM <TABLE> WHERE <CONDITION> ORDER BY <COLUMN(S)>. INPUT SQL> SELECT ENAME FROM EMP ORDER BY ENAME.

ENAME.SAL FROM EMP ORDER BY JOB. OUTPUT: Display employees in descending order by jobs. ename desc.---------FORD 3000 SCOTT 3000 ADAMS 1100 JAMES 950 MILLER 1300 SMITH 800 BLAKE 2850 CLARK 2450 JONES 2975 KING 5000 ALLEN 1600 MARTIN 1250 TURNER 1500 WARD 1250 Display employees in ascending order of jobs. INPUT SQL> SELECT * 53 FROM EMP where JOB != ‘CLERK’ ORDER BY JOB. OUTPUT: Display employees in ascending order by jobs. name desc. With each job it places the information in descending order of names. INPUT SQL> SELECT * FROM EMP ORDER BY job desc.Siva Kumar HVK INPUT SQL> SELECT JOB. With each job it places the information in descending order of names. OUTPUT JOB --------ANALYST ANALYST CLERK CLERK CLERK CLERK MANAGER MANAGER MANAGER PRESIDENT SALESMAN SALESMAN SALESMAN SALESMAN ANALYSIS ENAME SAL ---------. . INPUT SQL> SELECT * FROM EMP ORDER BY job. With each job it places the information in ascending order of names.ENAME.

Siva Kumar HVK We can also use order by clause as INPUT SQL> SELECT * FROM EMP ORDER BY 3. 54 . ANALYSIS It places the information in the order of third column in the table.

23? (1) LONG. Assume there is a table student(sname char(6). (4) SELECT ename. _________ is the operator used to compare a column with null value. Display list of employees that start with letter C 8. Which data type should you use for interest rates with varying and unpredictable decimal places such as 1. 3.4. 10. 2. Which SQL statement will you use? (1) SELECT hiredate FROM emp. (3) NUMBER(p. salary*12 Annual SalaryFROM employees. s) (4) None 11. (3) SELECT emp FROM emp ORDER by hiredate. SQL commands are to be terminated with ______________ 7. What is the size of sname and sname1 5.Which SQL statement generates the alias Annual Salary for the calculated column SALARY*12? (1) SELECT ename. sname1 varchar2(6)). How many LONG columns can a table contain?_______ 6. (4) SELECT hiredate FROM emp ORDER BY hiredate DESC. (2) SELECT ename. Assume that value place in both columns is RAVI. The maximum number of character that can be stored in CHAR type is 4. salary*12 AS INITCAP(ANNUAL SALARY)FROM employees 55 . 5 and 1. salary*12 Annual SalaryFROM employees.Siva Kumar HVK Exercise 1.234. (2) SELECT hiredate FROM emp ORDER BY hiredate. 3. Display employees in ascending order of 5th column in the table 9. _________is used to compare one value with a set of values. (3) SELECT ename. salary*12 AS Annual SalaryFROM employees. Examine the trace instance chart for employee table. (2) NUMBER. You want to display each employee hiredate from earliest to latest.

FIRST_NAME VARCHAR2(25) DEPT_ID NUMBER(9) You need to display the names of the employees that are not assigned to the department. (3) Query executes successfully (4) Add a second condition to the where condition 3. (2) SELECT ENAMEFROM EMPWHERE HIRE_DATE-SYSDATE > 5. SELECT last_name. \ 56 . Management wants a list of names of employees who have been with the company for more than five years.Siva Kumar HVK 1. The EMP table has these columns: ENAME VARCHAR2(35). (3) You cannot specify a column alias in an ORDER BY clause. The employee table contains these columns. (2) Data values are displayed in descending order by default. Which SQL statement displays the required results? (1) SELECT ENAMEFROM EMPWHERE SYSDATE-HIRE_DATE > 5.2)HIRE_DATE DATE. SALARY NUMBER(8. Which statement about SQL is true? (1) Null values are displayed last in the ascending sequences. (4) SELECT ENAMEFROM EMPWHERE (SYSDATE-HIRE_DATE)* 365 > 5. (3) SELECT ENAMEFROM EMPWHERE (SYSDATE-HIRE_DATE)/365 > 5.LAST_NAME VARCHAR2 (25). first_name FROM employee WHERE dept_id is NULL which change should you make to achieve the desired result? (1) Create an outer join. Evaluate this SQL statement. (4) You cannot sort query results by a column that is not included in the SELECT list. (2) Change the column in the where condition. 2.

INPUT: SQL> SELECT COUNT(*) FROM EMP. which executes whenever we call it and returns a value to the calling place. Say you wanted to know how many employees are there. These functions are classified into two types Predefined functions User defined functions Predefined functions These functions are again classified into two types Group or Aggregate Functions Single row Functions Aggregate Functions These functions are also referred to as group functions. OUTPUT: COUNT(*) -------14 ANALYSIS It counts if row presents in the table 57 . COUNT The function COUNT returns the number of rows that satisfy the condition in the WHERE clause.Siva Kumar HVK FUNCTIONS A function is a sub program. They return a value based on the values in a column.

try an alias: INPUT/OUTPUT: SQL> SELECT COUNT(*) NUM_OF_EMP FROM EMP. INPUT/OUTPUT: SQL> SELECT COUNT(*) FROM EMP WHERE JOB = ‘MANAGER’.Siva Kumar HVK To make the code more readable. Column Note: Count (comm) faster than count(*) Count(*) count the row when a row present in the table where as Count(comm) counts the row only when there is a value in the column. COUNT(*) ------4 ANALYSIS It counts only managers 58 . NUM_OF_EMP ------------------14 INPUT/OUTPUT: SQL> SELECT COUNT(COMM) FROM EMP. COUNT(*) -------4 ANALYSIS It counts only those when there is a value in comm.

SUM(COMM) TOTAL_COMM. FROM EMP. Find the total salary drawn by all the employees INPUT/OUTPUT: SQL> SELECT SUM(SAL) TOTAL_SALARY. TOTAL_SALARY TOTAL_COMM ------------.---------29025 2200 INPUT/OUTPUT: SQL> SQL> SELECT SUM(SAL) TOTAL_SALARY.Siva Kumar HVK INPUT/OUTPUT: SQL> SELECT count (distinct job) FROM EMP. COUNT (*) ------4 ANALYSIS It counts only distinct jobs SUM SUM does just that. TOTAL_SALARY TOTAL_COMM ------------.---------5600 2200 59 . It returns the sum of all values in a column. SUM(COMM) TOTAL_COMM FROM EMP WHERE JOB = ‘SALESMAN’. INPUT: SQL> SELECT SUM(SAL) TOTAL_SALARY OUTPUT: TOTAL_SALARY ------------29025 ANALYSIS FROM EMP.

OUTPUT: AVERAGE_SALARY --------------2073.Siva Kumar HVK AVG The AVG function computes the average of a column. INPUT: SQL> SELECT AVG(sal) average_salary 2 FROM EMP. OUTPUT: AVERAGE_COMM ------------ 550 ANALYSIS Functions ignores null rows 60 .21429 ANALYSIS Find the average salary of all the employees INPUT: SQL> SELECT AVG(COMM) average_comm FROM EMP.

Siva Kumar HVK MAX INPUT: SQL> SELECT MAX(SAL) FROM EMP. OUTPUT: MAX(HIREDATE) ------------- 12-JAN-83 61 . OUTPUT: MAX(SAL) -------- 5000 ANALYSIS Takes the value from one different rows from one particular column INPUT: SQL> SELECT MAX(ENAME) FROM EMP. OUTPUT: MAX(ENAME) -------- WARD ANALYSIS Max of name is identified based on ASCII value INPUT: SQL> SELECT MAX (hiredate) FROM EMP.

21429 800 5000 14 ANALYSIS All the aggregate functions can be used together in a single SQL statement 62 .--------------. OUTPUT SUM(SAL) AVG(SAL) MIN(SAL) MAX(SAL) COUNT(*) -------------.MAX(SAL).MIN(SAL).-------------.COUNT(*) FROM EMP.------------29025 2073.AVG(SAL).Siva Kumar HVK MIN INPUT: SQL> SELECT MIN(SAL) FROM EMP. OUTPUT: MIN(SAL) -------- 800 INPUT: SQL> SELECT MIN(ENAME) FROM EMP. OUTPUT: MIN (ENAME) -------- ADAMS INPUT SELECT SUM(SAL).-------------.

Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 1 4 2 Hrs Revision / Practicals 63 .

Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 2 1&2 5 Hrs Topics Single Row Functions Exercise 64 .

ABS The ABS function returns the absolute value of the number you point to.Siva Kumar HVK Presentation SINGLE ROW FUNCTIONS These functions work on each and every row and return a value to the calling places. Most Implementations of SQL provide arithmetic functions similar to that of operators covered here.e. These functions are classified into different types Arithmetic Functions Character Functions Date functions Miscellaneous Functions Arithmetic Functions Many of the uses you have for the data you retrieve involve mathematics. OUTPUT ABSOLUTE_VALUE ---------------------------10 ANALYSIS ABS changes all the negative numbers to positive and leaves positive numbers alone. 65 . Dual is a system table or dummy table from where we can display system information (i. For example: INPUT: SQL> SELECT ABS(-10) ABSOLUTE_VALUE FROM dual. system date and username etc) or we can make our own calculations.

145) FROM DUAL.000) ----------------12 66 . FLOOR does just the reverse.000) FROM DUAL.678) ----------------12 INPUT: SQL> SELECT FLOOR(12.Siva Kumar HVK CEIL and FLOOR CEIL returns the smallest integer greater than or equal to its argument.145) ----------------13 INPUT: SQL> SELECT CEIL(12.678) FLOOR DUAL. INPUT: SQL> SELECT CEIL(12. OUTPUT: CEIL(12. to get the next higher integer number INPUT/OUTPUT: SQL> SELECT FLOOR(12. returning the largest integer equal to or less than its argument. OUTPUT: FLOOR(12. OUTPUT: CEIL(12. OUTPUT: FLOOR(12.000) ----------------12 ANALYSIS Minimum we require one decimal place .000) FROM DUAL.

OUTPUT: MOD(5. it returns numerator value as remainder. 67 .5) --------------2 ANALYSIS When numerator value less than denominator. OUTPUT: MOD(2.2) --------------1 INPUT SQL> SELECT MOD(2.Siva Kumar HVK MOD It returns remainder when we divide one value with another value INPUT SQL> SELECT MOD(5.2) FROM DUAL.5) FROM DUAL.

and 1 if its argument is greater than 0 INPUT: SQL> SELECT SIGN(-10). INPUT/OUTPUT: SQL> SELECT SQRT(4) FROM DUAL. 2 68 .----------1 1 0 SQRT The function SQRT returns the square root of an argument. OUTPUT: SIGN(-10) SIGN(10) SIGN(0) ---------. Because the square root of a negative number is undefined.SIGN(0) FROM DUAL.---------. 0 if its argument is equal to 0. you cannot use SQRT on negative numbers.3) FROM DUAL. In this function the first argument is raised to the power of the second: INPUT: SQL> SELECT POWER(5. OUTPUT: 125 SIGN SIGN returns -1 if its argument is less than 0. use POWER. SIGN(10).Siva Kumar HVK POWER To raise one number to the power of another.

OUTPUT KRISHNA KANTH 69 . OUTPUT: A CONCAT It is similar to that of concatenate operator ( | | ) INPUT: SQL> SELECT CONCAT(‘KRISHNA’. The character it returns depends on the character set of the database. INPUT: SQL> SELECT CHR(65) FROM DUAL. For this example the database is set to ASCII.Siva Kumar HVK Character Functions Many implementations of SQL provide functions to manipulate characters and strings of characters. ‘ KANTH’) FROM DUAL. CHR CHR returns the character equivalent of the number it uses as an argument.

LOWER changes all the characters to lowercase. OUTPUT: BEFORE ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD AFTER ---------Smith Allen Ward Jones Martin Blake Clark Scott King Turner Adams James Ford LOWER and UPPER As you might expect.LOWER(ENAME) LOWER_CASE FROM EMP. SQL>SELECT ENAME. ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER UPPER_CASE ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER LOWER_CASE ---------smith allen ward jones martin blake clark scott king turner adams james ford miller 70 .UPPER(ENAME) UPPER_CASE.Siva Kumar HVK INITCAP INITCAP capitalizes the first letter of a word and makes all other characters lowercase.INITCAP(ENAME) “AFTER”FROM EMP. INPUT: SQL> SELECT ENAME “BEFORE”. UPPER does just the changes all the characters to uppercase.

' --------------**********SMITH **********ALLEN ***********WARD **********JONES *********MARTIN **********BLAKE **********CLARK **********SCOTT ***********KING *********TURNER **********ADAMS **********JAMES ***********FORD *********MILLER ANALYSIS: 15 locations allocated to display ename.15.10. out of that. name is occupying some space and in the remaining space to the left side of the name pads with *. or it can be a single character or a character string. assuming that the field LASTNAME is defined as a 15-character field: INPUT: SQL> SELECT LPAD(ENAME. The second is the number of characters to pad it with. and the optional third argument is the character to pad it with. OUTPUT: 5000****** 71 .15. The third argument defaults to a blank. INPUT SQL> SELECT RPAD(5000.’*’) FROM DUAL.Siva Kumar HVK LPAD and RPAD LPAD and RPAD take a minimum of two and a maximum of three arguments. The following statement adds five pad characters. OUTPUT: LPAD(ENAME. The first argument is the character string to be operated on.’*’) FROM EMP.

RTRIM(ENAME. OUTPUT: ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER RTRIM(ENAM ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNE ADAMS JAMES FORD MILLE ANALYSIS Removes the rightmost character 72 . like LPAD and RPAD. INPUT: SQL> SELECT ENAME.’R’) FROM EMP. is a character string. The optional second element is either a character or character string or defaults to a blank. If you use a second argument that is not a blank. these trim functions will trim that character the same way they trim the blanks in the following examples.Siva Kumar HVK LTRIM and RTRIM LTRIM and RTRIM take at least one and at most two arguments. The first argument.

SYNTAX : REPLACE(STRING. VI’) FROM DUAL.’MA’. OUTPUT RANA ANALYSIS When the replace string is missing. search string removed from the given string INPUT SQL> SELECT REPLACE (‘RAMANA’. each occurrence of the search key on the string to be searched is removed and is not replaced with anything.’MA’.’MA’) FROM DUAL.REPLACE_STRING) INPUT: SQL> SELECT REPLACE (‘RAMANA’. the first is the string to be searched. OUTPUT RAVINA INPUT SQL> SELECT REPLACE(‘RAMANA’. The last is the optional replacement string. Of its three arguments. If the third argument is left out or NULL.Siva Kumar HVK REPLACE REPLACE does just that.SEARCH_STRING. The second is the search key. NULL) FROM DUAL. OUTPUT RANA 73 .

OUTPUT: RDCDND ANALYSIS Notice that the function is case sensitive. Elements of the target string that occur in the FROM string are translated to the corresponding element in the TO string. The third argument is the number of characters to show.1.NO_OF_CHARACTERS]) INPUT: SQL> SELECT SUBSTR(‘RAMANA’. When search string matches. SUBSTR This three-argument function enables you to take a piece out of a target string.’CD’) FROM DUAL. INPUT: SQL> SELECT TRANSLATE(‘RAMANA’.’MA’. it replaces with corresponding replace character. The second argument is the position of the first character to be output.Siva Kumar HVK TRANSLATE The function TRANSLATE takes three arguments: the target string. it replaces with corresponding replace string and if any one character is matching in the search string . the FROM string.STARTING_POSITION[. OUTPUT: RAM ANALYSIS It takes first 3 characters from first character 74 . The first argument is the target string.3) FROM DUAL. and the TO string. SYNTAX SUBSTR(STRING.

2) || SUBSTR(‘RAMANA’. OUTPUT: MANA ANALYSIS When third argument is missing. OUTPUT: MAN ANALYSIS It takes 3 characters from third position INPUT: SQL> SELECT SUBSTR(‘RAMANA’.Siva Kumar HVK INPUT: SQL> SELECT SUBSTR(‘RAMANA’.2) FROM DUAL. it takes all the character from starting position 75 .3.-2. OUTPUT: RANA ANALYSIS First two characters and last two characters are combined together as a single string INPUT: SQL> SELECT SUBSTR(‘RAMANA’.3) FROM DUAL.3) FROM DUAL.-2.2) FROM DUAL.1. OUTPUT: NA ANALYSIS You use a negative number as the second argument. the starting point is determined by counting backwards from the end. INPUT: SQL> SELECT SUBSTR(‘RAMANA’.

This example returns a number representing occurrence of O starting with the second the first INPUT SQL> SELECT INSTR(‘RAMANA’. Its first argument is the target string.Siva Kumar HVK INPUT: SQL> SELECT * FROM EMP WHERE SUBSTR(HIREDATE.4.’A’) FROM DUAL. INSTR To find out where in a string a particular pattern occurs.3). ANALYSIS Displays all the employees who joined in the current month SYSDATE is a single row function.3) = SUBSTR(SYSDATE. The second argument is the pattern to match. which gives the current date. use INSTR. The third and forth are numbers representing where to start looking and which match to report.4. OUTPUT 2 ANALYSIS Find the position of the first occurrence of letter A 76 .

INPUT SQL> SELECT INSTR(‘RAMANA’. it returns 0 (zero) when the given character is not found. SQL> SELECT INSTR (‘RAMANA’.’a’) FROM DUAL.Siva Kumar HVK INPUT SQL> SELECT INSTR(‘RAMANA’.’A’. which occurrence. OUTPUT 4 ANALYSIS • Find the position of the second occurrence of letter A from the beginning of the string.2) FROM DUAL. Fourth argument represents.3.1.’A’. • Third argument represents from which position.2) FROM DUAL. OUTPUT 0 ANALYSIS Function is case sensitive. OUTPUT 6 ANALYSIS Find the position of the second occurrence of letter A from 3rd position of the string 77 .

Siva Kumar HVK Conversion Functions These functions provide a handy way of converting one type of data to another. like Date. or to include different formatting arguments. OUTPUT: SAL ---------800 1600 1250 2975 1250 2850 2450 3000 5000 1500 1100 950 3000 1300 TO_CHAR(SAL) ---------------------------------------800 1600 1250 2975 1250 2850 2450 3000 5000 1500 1100 950 3000 1300 ANALYSIS After conversion. They are mainly useful for changing date formats and number formats. So we can say that it is a string. The following example illustrates the primary use of TO_CHAR: INPUT: SQL> SELECT SAL. 78 . into a character. TO_CHAR(SAL) FROM EMP. TO_CHAR The primary use of TO_CHAR is to convert a number into a character. Converted information is left aligned. Different Implementations may also use it to convert other data types.

TO_CHAR(SYSDATE.’DD-MON-YY’) FROM DUAL. OUTPUT: SYSDATE --------24-MAR-07 TO_CHAR(SYSDATE.TO_CHAR(SYSDATE.'DD/MM/YYYY') -----------------------------24/03/2007 ANALYSIS Convert the default date format to DD/MM/YYYY format INPUT: SQL> SELECT SYSDATE.'DD-MON-YY') -----------------------------24-MAR-07 79 .Siva Kumar HVK The main usage of this function is. to change the date formats and number formats INPUT: SQL> SELECT SYSDATE.’DD/MM/YYYY’) FROM DUAL. OUTPUT: SYSDATE --------24-MAR-07 TO_CHAR(SYSDATE.

’DAY MONTH YEAR’) FROM DUAL. OUTPUT: SYSDATE --------24-MAR-07 ANALYSIS: TO_CHAR(SYSDATE.TO_CHAR(SYSDATE. OUTPUT: SYSDATE --------24-MAR-07 TO_CHAR(SYSDATE.Siva Kumar HVK Date Formats INPUT: SQL> SELECT SYSDATE.TO_CHAR(SYSDATE.'DY-MON-YY') -----------------------------SAT-MAR-07 DY displays the first 3 letters from the day name INPUT: SQL> SELECT SYSDATE.’DY-MON-YY’) FROM DUAL.'DAYMONTHYEAR') -----------------------------SATURDAY MARCH TWO THOUSAND SEVEN ANALYSIS: DAY gives the total day name MONTH gives the total month name YEAR writes the year number in words 80 .

------------------------------------------------------------------17-DEC-80 SEVENTEENTH DECEMBER NINETEEN EIGHTY 20-FEB-81 TWENTIETH FEBRUARY NINETEEN EIGHTY-ONE 22-FEB-81 TWENTY-SECOND FEBRUARY NINETEEN EIGHTY-ONE 02-APR-81 SECOND APRIL NINETEEN EIGHTY-ONE 28-SEP-81 TWENTY-EIGHTH SEPTEMBER NINETEEN EIGHTY-ONE 01-MAY-81 FIRST MAY NINETEEN EIGHTY-ONE 09-JUN-81 NINTH JUNE NINETEEN EIGHTY-ONE 09-DEC-82 NINTH DECEMBER NINETEEN EIGHTY-TWO 17-NOV-81 SEVENTEENTH NOVEMBER NINETEEN EIGHTY-ONE 08-SEP-81 EIGHTH SEPTEMBER NINETEEN EIGHTY-ONE 12-JAN-83 TWELFTH JANUARY NINETEEN EIGHTY-THREE 03-DEC-81 THIRD DECEMBER NINETEEN EIGHTY-ONE 03-DEC-81 THIRD DECEMBER NINETEEN EIGHTY-ONE 23-JAN-82 TWENTY-THIRD JANUARY NINETEEN EIGHTY-TWO ANALYSIS: Converts all hire dates in EMP table into Words 81 .'DDSPTHMONTHYEAR') --------.------------------------------------------------------------------24-MAR-07 TWENTY-FOURTH MARCH TWO THOUSAND SEVEN ANALYSIS: DD gives the day number DDSP Writes day number in words TH is the format. OUTPUT: HIREDATE TO_CHAR(HIREDATE.’DDSPTH MONTH YEAR’) FROM DUAL.'DDSPTHMONTHYEAR') --------.’DDSPTH MONTH YEAR’) FROM EMP.Siva Kumar HVK INPUT: SQL> SELECT SYSDATE. Depends upon the number it gives either ST / RD/ST/ND format INPUT: SQL> SELECT HIREDATE. OUTPUT: SYSDATE TO_CHAR(SYSDATE.TO_CHAR(HIREDATE.TO_CHAR(SYSDATE.

’Q’) FROM DUAL.’Q’) FROM DUAL.’W’) -----------------------------4 82 .’Q’) -----------------------------1 INPUT: SQL> SELECT TO_CHAR(TO_DATE(’10-SEP-2005’).Siva Kumar HVK INPUT: SQL> SELECT SYSDATE. which converts given string into date type INPUT: SQL> SELECT SYSDATE. OUTPUT: SYSDATE --------24-MAR-07 ANALYSIS: Gives in the quarter the given date falls TO_CHAR(SYSDATE. OUTPUT: TO_CHAR(TO_DATE('10-SEP-2005').'Q') ---------------------------------------3 ANALYSIS: To_date is data conversion function.TO_CHAR(SYSDATE.’W’) FROM DUAL. OUTPUT: SYSDATE --------24-MAR-07 ANALYSIS: Gives the week number in the current month ( In which week given date falls in the current month) TO_CHAR(SYSDATE.TO_CHAR(SYSDATE.

’WW’) FROM DUAL.Siva Kumar HVK INPUT: SQL> SELECT SYSDATE.’HH:MI:SS AM’) FROM DUAL. OUTPUT: SYSDATE TO_CHAR(SYSDATE) -----------------------------------24-MAR-07 12 ANALYSIS: Returns no. OUTPUT: TO_CHAR(SYS ----------08:40:17 PM ANALYSIS: HH returns Hours MI returns Minutes SS returns Seconds } } Returns time from current date } INPUT: SQL> SELECT TO_CHAR(SYSDATE.’HH24:MI:SS’) FROM DUAL. OUTPUT: TO_CHAR( -------20:43:12 ANALYSIS: HH24 returns Hours in 24 hour format MI returns Minutes SS returns Seconds } } Returns time from current date } 83 .TO_CHAR(SYSDATE. INPUT: SQL> SELECT TO_CHAR(SYSDATE. of weeks worked during the year.

'99.’L99.00 ANALYSIS: Converts the given number into comma format with two decimal places INPUT: SQL> SELECT TO_CHAR(12567.567.99') ----------------------------12.567.00 ANALYSIS: Display the local currency symbol 84 .99') ----------------------------$12.Siva Kumar HVK INPUT: SQL> SELECT TO_CHAR(12567.’99.99’) FROM DUAL.999.999. OUTPUT: TO_CHAR(12567.999. OUTPUT: TO_CHAR(12567.'L99.999.99’) FROM DUAL.

OUTPUT: TO_CHAR(-12567.99PR’) FROM DUAL.99PR') ----------------------------------<$12.'L99.Siva Kumar HVK INPUT: SQL> SELECT TO_CHAR(-12567.00> ANALYSIS: PR Parenthesis negative number 85 .999.’L99.999.567.

So we can say that it is a number. and of course. Converted information is right aligned. TO_NUMBER((TO_CHAR(SAL)) FROM EMP. and most major implementations of SQL have functions to cope with these concepts. For example: INPUT: SQL> SELECT SAL. It demonstrates the time and date functions. it converts a string into a number.Siva Kumar HVK TO_NUMBER TO_NUMBER is the companion function to TO_CHAR. 86 . OUTPUT: SAL TO_NUMBER(TO_CHAR(SAL)) ---------.----------------------800 800 1600 1600 1250 1250 2975 2975 1250 1250 2850 2850 2450 2450 3000 3000 5000 5000 1500 1500 1100 1100 950 950 3000 3000 1300 1300 ANALYSIS After conversion. Date and Time Functions We live in a civilization governed by times and dates.

say a customer deposited some amount on a particular date for a period of 6 months.Siva Kumar HVK ADD_MONTHS This function adds a number of months to a specified date. To find the maturity date of the deposit INPUT: SQL> SELECT ADD_MONTHS (SYSDATE. 6) MATURITY_DATE FROM DUAL.33*12) RETIRE_DATE FROM EMP. For example. 33 years of service from date of join is retirement date LAST_DAY 87 . OUTPUT: MATURITY_DATE -------------------24-SEP-07 ANALYSIS It adds 6 months to the system date INPUT: SQL> SELECT HIREDATE. ADD_MONTHS(HIREDATE. OUTPUT: HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 09-DEC-82 17-NOV-81 08-SEP-81 12-JAN-83 03-DEC-81 03-DEC-81 23-JAN-82 RETIRE_DATE --------------17-DEC-13 20-FEB-14 22-FEB-14 02-APR-14 28-SEP-14 01-MAY-14 09-JUN-14 09-DEC-15 17-NOV-14 08-SEP-14 12-JAN-16 03-DEC-14 03-DEC-14 23-JAN-15 ANALYSIS Find the retirement date of an employee Assume.

Siva Kumar HVK LAST_DAY returns the last day of a specified month. you need to know what the last day of the month INPUT: SQL> SELECT LAST_DAY(SYSDATE) FROM DUAL. OUTPUT: ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER EXPERIENCE ---------26.4917795 25.3089838 25.545543 24.7928548 24.3546827 25.8976935 25.2014569 25.2713494 26.171887 ANALYSIS Finds number of months between sysdate and hiredate .MONTHS_BETWEEN(SYSDATE. Result is divided with 12 to get the experience 88 .0912419 25. For example.0966182 26.2928548 25.9783387 25. OUTPUT: LAST_DAY(SYSDATE) ------------------------31-MAR-07 ANALYSIS Find the last date of the month MONTHS_BETWEEN Used to find the number of months between two given months INPUT: SQL> SELECT ENAME.HIREDATE)/12 EXPERIENCE FROM EMP.3089838 25.

Here are the time zones you can use with this function: Abbreviation Time Zone AST or ADT Atlantic standard or daylight time BST or BDT Bering standard or daylight time CST or CDT Central standard or daylight time EST or EDT Eastern standard or daylight time GMT Greenwich mean time HST or HDT Alaska-Hawaii standard or daylight time MST or MDT Mountain standard or daylight time NST Newfoundland standard time PST or PDT Pacific standard or daylight time YST or YDT Yukon standard or daylight time You can adjust your time like this: INPUT SQL> select TO_CHAR(new_time(LOCALTIMESTAMP.'EsT'.'DD/MM/Y YYY HH : MI :SS PM') from DUAL.'PDT'). with no time zone information shown INPUT SQL> SELECT LOCALTIMESTAMP FROM DUAL. OUTPUT TO_CHAR(NEW_TIME(LOCALTIM ------------------------25/03/2007 04 : 32 :55 PM 89 .312000 PM NEW_TIME This function is used to adjust the time according to the time zone you are in.02.21.Siva Kumar HVK LOCALTIMESTAMP Returns Local timestamp in the active time zone. OUTPUT LOCALTIMESTAMP -----------------------------------25-MAR-07 06.

OUTPUT: HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 09-DEC-82 17-NOV-81 08-SEP-81 12-JAN-83 03-DEC-81 03-DEC-81 23-JAN-82 NEW_TIME( --------16-DEC-80 19-FEB-81 21-FEB-81 01-APR-81 27-SEP-81 30-APR-81 08-JUN-81 08-DEC-82 16-NOV-81 07-SEP-81 11-JAN-83 02-DEC-81 02-DEC-81 22-JAN-82 ANALYSIS Like magic.'PDT') from emp. 90 .Siva Kumar HVK INPUT: SQL> select hiredate. new_time(hiredate. all the times are in the new time zone and the dates are adjusted.'EsT'.

EXTRACT We can use Extract function in the place of to_char function from Oracle 9i.Siva Kumar HVK NEXT_DAY NEXT_DAY finds the name of the first day of the week that is equal to or later than another specified date. It display the date of the next coming Monday. SELECT EXTRACT(MONTH FROM SYSDATE) FROM DUAL. March 24. SELECT EXTRACT(DAY FROM SYSDATE) FROM DUAL SELECT EXTRACT(YEAR FROM SYSDATE) FROM DUAL 91 .’MONDAY’) FROM DUAL. 2007. INPUT: SQL> SELECT NEXT_DAY(SYSDATE. OUTPUT: NEXT_DAY( --------26-MAR-07 ANALYSIS If the sysdate is Saturday.

Both were introduced in Oracle9i Database. and both conform to the ISO SQL standard.to_date('10-NOV-2007')) day to second from dual OUTPUT +000000009 11:04:07 Analysis Find the difference with days and time. INTERVAL YEAR to MONTH Allows you to define and interval of time in terms of years and months INTERVAL DAY TO SECOND Allows you to define an interval of time in terms of days.Siva Kumar HVK Interval Data types (Only from 9i) Oracle supports two interval datatypes. minutes and seconds (including fractional seconds). Example select (sysdate . Example Select (sysdate . No of years and months between both the dates.to_date('10-jan-2004')) year to month from dual OUTPUT +000000003-10 Analysis Returns the difference. For sysdate it takes 0.00 hrs as starting time 92 . hours.

RR returns the current century. to_char(to_date('14-oct-18'. If the Current year is in the first half of the century ( years 0 through 49).-------------------19/11/2007 1988 2018 When we reach the year 2050. to_char(to_date('14-oct-88'. RR returns the previous century. RR will interpret the same dates differently current date Year 88 year ------------------------.'yyyy') "Year 88".We can also change the default format for a given session using the ALTER SESSION command SQL> ALTER SESSION SET NLS_DATE_FORMAT = ‘DD/MM/YYYY’.e.-------------------19/11/2050 2088 2118 93 . from 50 through 99).-------------------.Siva Kumar HVK Note :.-------------------. SQL> SELECT SYSDATE FROM DUAL: Interpreting Two-digit Years Oracle provides the RR format element to interpret two-digit years.'yyyy') "year 18" from dual OUTPUT current date Year 88 year 18 ------------------------.'dd-mon-rr'). from 0 through 49). For example select to_char(sysdate.'dd/mm/yyyy') "current date". then: • • If you enter a date in the first half of the century (i.e. If you enter a date in the latter half of the century (i.'dd-mon-rr').

'year') from dual. • SELECT NUMTOYMINTERVAL(10.'year') from dual.999999999 94 .’MONTH’) FROM DUAL.5.'YEAR') ----------------------------------------------------------------------+000000010-06 SQL> select numtoyminterval (10.3. SQL> select numtoyminterval (10. NUMTOYMINTERVAL (10.5.Siva Kumar HVK Going from Numbers to Intervals The NUMTOYMINTERVAL and NUMTODSINTERVAL functions allow you to convert a single numeric value to one of the interval data types.999.’DAY’) FROM DUAL. Name Description Some number of years ranging from 1 through YEAR MONTH DAY HOUR MINUTE SECOND 999.999 Some number Some number Some number Some number of of of of months ranging from 0 through 11 days ranging from 0 through 999.5.3.'YEAR') ----------------------------------------------------------------------+000000010-03 Try the following formats SELECT NUMTOYMINTERVAL(10.999 hours ranging from 0 through 23 minutes ranging from 0 through 59 • Some number of seconds ranging from 0 through 59.999. The function NUMTOYMINTERVAL (pronounced “ num to Y M interval”) converts a numeric value an interval of type INTERVAL YEAR TO MONTH. NUMTOYMINTERVAL (10.5.

’minute’) from dual.00.Siva Kumar HVK NUMTODSINTERVAL This function allows converting a single numeric value to one of the interval data types.000000 ANALYSIS Oracle automatically taken care of normalizing the input value of 1440 minutes to an interval value of 1 day. This function (pronounced “num to D S interval”) likewise converts a numeric value to an interval of type INTERVAL DAY TO SECOND. Example SQL> select NUMTODSINTERVAL(1440. OUTPUT +01 00:00. 95 .

2.9.Siva Kumar HVK Miscellaneous Functions Here are three miscellaneous functions you may find useful. Assume there is a student table ROLLNO 1 2 3 4 NAME RAVI KRIS BABU ANU STUDENT SUB1 SUB2 55 22 78 55 55 22 44 55 SUB3 86 65 44 66 SUB4 45 12 77 88 96 .67) FROM DUAL. GREATEST and LEAST INPUT: SQL> SELECT GREATEST(10. WHERE AS MAX TAKES VALUES FROM DIFFERENT ROWS FROM A COLUMN. OUTPUT: GREATEST --------83 ANALYSIS Displays the greatest of the given set of values Difference between GREATEST AND MAX IS 1) GREATEST IS SINGLE ROW FUNCTION. MAX IS A GROUP FUNCTION 2) GREATEST TAKES VALUES FROM DIFFERENT COLUMNS FROM EACH ROW.1.83.

OUTPUT: USER -------SCOTT ANALYSIS Displays the current sessions user name We can also display username using environment command SQL> SHOW USER 97 .SUB3.SUB2.SUB3.Siva Kumar HVK To find the greatest and Least Marks INPUT: SQL> SELECT NAME.SUB1. LEAST(SUB1.SUB4) GREATEST_MARK. SUB1 SUB2 55 78 55 44 22 55 22 55 SUB3 SUB4 86 65 44 66 45 12 77 88 RAVI KRIS BABU ANU GREATEST MARK 86 78 77 88 LEAST MARK 22 12 22 44 INPUT: SQL> SELECT USER FROM DUAL.SUB3.SUB4) LEAST_MARK FROM STUDENT OUTPUT: RNO NAME 1 2 3 4 USER USER returns the character name of the current user of the database.SUB2. SUB4. GREATEST(SUB1.SUB2.

If column1 has a value of anything other than value1 or value2.THEN statement in a procedural programming language. The standard language of SQL lacks procedural functions that are contained in languages such as COBOL and C. 98 . then display output2 instead of the column's current value. output3) The syntax example performs the DECODE function on column1. value2. then display output3 instead of the column's current value. SYNTAX: DECODE (column1. The DECODE statement is similar to an IF. value1.. DECODE is often able to fill the gap between SQL and the functions of a procedural language. output2. output1. Where flexibility is required for complex reporting needs. If column1 has a value of value1..Siva Kumar HVK The DECODE Function The DECODE function is one of the most powerful commands in SQL*Plus--and perhaps the most powerful. then display output1 instead of the column's current value. If column1 has a value of value2.

OFFICER S.’EXEC’.’CLERK’.OFFICER EXEC EXEC PM EXEC ANALYSIS When JOB has a value CLERK .’ANALYST’.’MANAGER’. then display EXEC instead of CLERK When JOB has a value SALESMAN . DECODE(JOB. ‘S.’SALESMAN’. then display S. OUTPUT ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB --------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK PROMOTION --------EXEC S.’VP’. then display VP instead of MANAGER OTHERWISE DISPLAY SAME JOB 99 .OFFICER’.OFFICER instead of SALESMAN When JOB has a value ANALYST .Siva Kumar HVK INPUT SQL> SELECT ENAME.OFFICER VP VP PM PRESIDENT S.JOB) PROMOTION FROM EMP.OFFICER VP S. then display PM instead of ANALYST When JOB has a value MANAGER . JOB.’PM’.

DECODE(SEX.3.25.’MANAGER’.’MALE’.5 SALESMAN 1250 1500 MANAGER 2850 3705 MANAGER 2450 3185 ANALYST 3000 3750 PRESIDENT 5000 5000 SALESMAN 1500 1800 CLERK 1100 1210 CLERK 950 1045 ANALYST 3000 3750 CLERK 1300 1430 ANALYSIS When JOB has a value CLERK .SAL.’ANALYST’. SEX.’ before the name based on their Gender 100 .Siva Kumar HVK To give increments designations to the employees based on their INPUT SQL> SELECT ENAME.SAL) NEW_SAL FROM EMP.’MR.SAL*1.’||ENAME) FROM EMP.SAL*1. then giving 10% increment When JOB has a value SALESMAN . then giving 25% increment When JOB has a value MANAGER . then giving 30% increment OTHERWISE no increment Assume there is a table with empno.SAL*1. then giving 20% increment When JOB has a value ANALYST .’SALESMAN’. ANALYSIS Adding Mr.1.’CLERK’.’||ENAME. OUTPUT ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB SAL NEW_SAL --------.ename.2.JOB. SAL*1.---------CLERK 800 880 SALESMAN 1600 1920 SALESMAN 1250 1500 MANAGER 2975 3867.’ or ‘Ms.---------.DECODE(JOB.sex INPUT SQL> SELECT ENAME. ‘MS.

you can use the CASE function in place of DECODE. The CASE function uses the keywords when. CASE JOB WHEN 'MANAGER' then 'VP' WHEN 'CLERK' THEN 'EXEC' WHEN 'SALESMAN' THEN 'S.OFFICER VP S.OFFICER S.OFFICER EXEC EXEC ANALYST EXEC ANALYSIS Works similar to that of DECODE 101 .OFFICER' ELSE JOB END FROM EMP. Example SQL> SELECT JOB.OFFICER VP VP ANALYST PRESIDENT S. else. which may make the resulting code easier to follow than an equivalent DECODE. then. JOB --------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK CASEJOBWH --------EXEC S. and end to indicate the logic path followed.Siva Kumar HVK CASE As of Oracle 9i.

this function is equal to substitute. it can be used with CHAR.---------. another column. SAL + COMM TOTAL FROM EMP. but the value and substitute must be the same data type. substitute) INPUT SQL> SELECT EMPNO. this function is equal to value.SAL. DATE.---------7369 800 7499 1600 300 1900 7521 1250 500 1750 7566 2975 7654 1250 1400 2650 7698 2850 7782 2450 7788 3000 7839 5000 7844 1500 0 1500 7876 1100 7900 950 7902 3000 7934 1300 ANALYSIS Arithmetic operation is possible only when value is there in both columns 102 . NVL is not restricted to numbers.Siva Kumar HVK NVL If the value is NULL. SYNTAX NVL(value.---------. Substitute can be a literal number. OUTPUT EMPNO SAL COMM TOTAL ---------. or a computation. If the value is not NULL. and other data types.COMM. VARCHAR2.

INPUT SQL>SELECT DEPTNO.0) TOTAL FROM EMP. OUTPUT DEPTNO SUM(SAL) RATIO_TO_REPORT(SUM(SAL))OVER() ---------.Siva Kumar HVK INPUT SQL> SELECT EMPNO.COMM.---------. 103 .---------7369 800 800 7499 1600 300 1900 7521 1250 500 1750 7566 2975 2975 7654 1250 1400 2650 7698 2850 2850 7782 2450 2450 7788 3000 3000 7839 5000 5000 7844 1500 0 1500 7876 1100 1100 7900 950 950 7902 3000 3000 7934 1300 1300 ANALYSIS Using NVL.323858742 ANALYSIS RATIO_TO_REPORT FUNCTION FINDS THE SALARY RATIO OF THAT DEPARTMENT OVER THE TOTAL SALARY OF ALL THE EMPLOYEES.RATIO_TO_REPORT(SUM(SAL)) OVER() FROM EMP GROUP BY DEPTNO.301464255 20 10875 . OUTPUT EMPNO SAL COMM TOTAL ---------. we are substituting 0 if COMM is NULL. SAL + NVL(COMM.SUM(SAL).374677003 30 9400 .---------.SAL.------------------------------10 8750 .---------.

Siva Kumar HVK LENGTH Finds the length of the given information SQL> SELECT ENAME.LENGTH(SAL) FROM EMP. 104 . SQL> SELECT SAL. CAST Converts one type of information into another type SQL> SELECT 50 numb. ASCII Finds the ASCII value of the given character SQL> SELECT ASCII(‘A’) FROM DUAL.LENGTH(ENAME) FROM EMP. SQL> SELECT LENGTH(SYSDATE) FROM EMP. cast(50 as varchar2(2) value from dual.

___________ symbol is used to combine tow given strings What happens if “replace string” is not given for REPLACE function Can a number be converted to DATE? Convert the value of name in the EMP table to lower case letters Display the names of the employees who have more than 4 characters in the name. _____________ format option is used to get complete year spelled out in TO_CHAR function. Print *’s as number of thousands are there in the number Display the ename. print as NO COMM Add number of days to the given date Display the first and last two characters from a given name and combine them as a single string (Use only functions) Find the difference between two given dates Display all the names which contain underscore subtract number of months from given date 105 . comm. If the commission is NULL.Siva Kumar HVK Exercise _____________ function performs one to one character substitution.

I 106 .Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 2 3 3 Hrs Exercise Annexure Query .

Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 2 4 3 Hrs

Revision

107

Siva Kumar HVK Course Day Session Duration : : : : Oracle 3 1 3 Hrs

Topics Group by clause CUBE and ROLLUP functions Having clause Exercise

108

Siva Kumar HVK
Presentation

109

Siva Kumar HVK GROUP BY CLAUSE
Group by statement groups all the rows with the same column value. Use to generate summary output from the available data. Whenever we use a group function in the SQL statement, we have to use a group by clause.

INPUT SQL> SELECT JOB, COUNT (*) FROM EMP GROUP BY JOB; OUTPUT
JOB COUNT(*) --------- ---------ANALYST 2 CLERK 4 MANAGER 3 PRESIDENT 1 SALESMAN 4

ANALYSIS
Counts number of employees under each and every job. When we are grouping on job, initially jobs are placed in ascending order in a temporary segment. On the temporary segment, group by clause is applied, so that on each similar job count function applied.

INPUT SQL> SELECT JOB, SUM (SAL) FROM EMP GROUP BY JOB; OUTPUT
JOB SUM(SAL) --------- ---------ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600

ANALYSIS With each job, it finds the total salary

110

Siva Kumar HVK ERROR with GROUP BY Clause
Note : Only grouped columns allowed in the group by clause When ever we are using a group function in the SQL statement, we have to use group by clause.

INPUT SQL> SELECT JOB,COUNT(*) FROM EMP; OUTPUT SELECT JOB, COUNT (*) FROM EMP * ERROR at line 1: ORA-00937: not a single-group group function ANALYSIS This result occurs because the group functions, such as SUM and COUNT, are designated to tell you something about a group or rows, not the individual rows of the table. This error is avoided by using JOB in the group by clause, which forces the COUNT to count all the rows grouped within each job.

INPUT SQL> SELECT JOB,ENAME,COUNT(*) FROM EMP GROUP BY JOB; OUTPUT SELECT JOB,ENAME,COUNT(*) FROM EMP GROUP BY JOB * ERROR at line 1: ORA-00979: not a GROUP BY expression ANALYSIS In the above query, JOB is only the grouped column where as ENAME column is not a grouped column. What ever the columns we are grouping, the same column is allowed to display.

111

Siva Kumar HVK

INPUT SQL> SELECT JOB, MIN(SAL),MAX(SAL) FROM EMP GROUP BY JOB; OUTPUT
JOB MIN(SAL) MAX(SAL) --------- ---------- ---------ANALYST 3000 3000 CLERK 800 1300 MANAGER 2450 2975 PRESIDENT 5000 5000 SALESMAN 1250 1600

ANALYSIS

For displaying Total summary information from the table.

INPUT SQL> SELECT JOB, SUM(SAL),AVG(SAL),MIN(SAL),MAX(SAL) ,COUNT(*) FROM EMP GROUP BY JOB; OUTPUT
JOB SUM(SAL) AVG(SAL) MIN(SAL) MAX(SAL) COUNT(*) --------- ---------- ---------- ---------- ---------- ---------ANALYST 6000 3000 3000 3000 2 CLERK 4150 1037.5 800 1300 4 MANAGER 8275 2758.33333 2450 2975 3 PRESIDENT 5000 5000 5000 5000 1 SALESMAN 5600 1400 1250 1600 4

ANALYSIS With each job, finds the total summary information.

112

it passes corresponding salary as an argument to SUM() . Then group by clause groups similar designations.JOB. SUM(DECODE(DEPTNO.---------.JOB.SUM(DECODE(DEPTNO.SAL)) DEPT30. If DEPTNO=10. INPUT SQL> SELECT DEPTNO.10. OUTPUT DEPTNO ---------10 10 10 20 20 20 30 30 30 ANALYSIS JOB COUNT(*) --------.---------CLERK 1 MANAGER 1 PRESIDENT 1 CLERK 2 ANALYST 2 MANAGER 1 CLERK 1 MANAGER 1 SALESMAN 4 113 .COUNT(*) FROM EMP GROUP BY DEPTNO. then DECODE function (Single row function) applies on each and every row of that group and checks the DEPTNO.20.---------. OUTPUT JOB DEPT10 DEPT20 DEPT30 TOTAL --------. Department wise total salaries With a matrix style report.---------.SAL)) DEPT10. SUM(SAL) TOTAL FROM EMP GROUP BY JOB. SUM(DECODE(DEPTNO.SAL)) DEPT20.---------ANALYST 6000 6000 CLERK 1300 1900 950 4150 MANAGER 2450 2975 2850 8275 PRESIDENT 5000 5000 SALESMAN 5600 5600 ANALYSIS When we apply group by.30. INPUT SQL> SELECT JOB.Siva Kumar HVK To display the output Designation wise. initially all the designations are placed in ascending order of designations.

JOB. SKIP 1 used with BREAK to leave one blank line after completion of each Deptno.COUNT(*) FROM EMP GROUP BY DEPTNO.Siva Kumar HVK To display the DEPTNO only one time INPUT SQL> BREAK ON DEPTNO SKIP 1 SQL> SELECT DEPTNO. 2 2 1 1 1 4 To remove the given break . we have to use an Environment command SQL> CLEAR BREAK.JOB.---------10 CLERK 1 MANAGER 1 PRESIDENT 1 20 CLERK ANALYST MANAGER 30 CLERK MANAGER SALESMAN ANALYSIS Break is Environment command . which breaks the information on repetitive column and displays them only once.--------. 114 . OUTPUT DEPTNO JOB COUNT(*) ---------.

. ●ROLLUP grouping produces a result set containing the regular grouped rows and the subtotal values. ●CUBE grouping produces a result set containing the rows from ROLLUP and cross-tabulation rows The ROLLUP and CUBE operators are available only in Oracle8i and later releases.. Syntax SELECT [column.] group_function(column).Siva Kumar HVK Group by with ROLLUP and CUBE Operators ●Use Rollup or CUBE with Group by to produce super aggregate rows by cross-referencing columns. FROM table [WHERE condition] [GROUP BY [CUBE] group_by_expression] [HAVING having_expression] [ORDER BY column]. 115 .

Siva Kumar HVK CUBE function
We can use CUBE function to generate subtotals for all combinations of the values in the group by clause.( CUBE and ROLLUP are available only from 9i)

INPUT SQL> SELECT DEPTNO,JOB,COUNT(*) FROM EMP GROUP BY CUBE(DEPTNO,JOB); OUTPUT
DEPTNO JOB COUNT(*) ---------- --------- ---------14 CLERK 4 ANALYST 2 MANAGER 3 SALESMAN 4 PRESIDENT 1 10 3 10 CLERK 1 10 MANAGER 1 10 PRESIDENT 1 20 5 20 CLERK 2 20 ANALYST 2 20 MANAGER 1 30 6 30 CLERK 1 30 MANAGER 1 DEPTNO JOB COUNT(*) ---------- --------- ---------30 SALESMAN 4 ANALYSIS

Cube displays the out with all the permutation and combination of all the columns given a CUBE function.

116

Siva Kumar HVK ROLLUP FUNCTION
It is similar to that of CUBE function

INPUT SQL> SELECT DEPTNO,JOB,COUNT(*) FROM EMP GROUP BY ROLLUP(DEPTNO,JOB) OUTPUT
DEPTNO ---------10 10 10 10 20 20 20 20 30 30 30 30 JOB COUNT(*) --------- ---------CLERK 1 MANAGER 1 PRESIDENT 1 3 CLERK 2 ANALYST 2 MANAGER 1 5 CLERK 1 MANAGER 1 SALESMAN 4 6 14

117

Siva Kumar HVK HAVING CLAUSE
Whenever we are using a group function in the condition, we have to use having clause. Having clause is used along with group by clause. For example, to display Designation wise total salaries

INPUT SQL> SELECT JOB,SUM(SAL) FROM EMP GROUP BY JOB; OUTPUT
SQL> SELECT JOB,SUM(SAL) FROM EMP GROUP BY JOB; JOB SUM(SAL) --------- ---------ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600

To Display only those designations, whose total salary is more than 5000

INPUT SQL> SELECT JOB,SUM(SAL) FROM EMP WHERE SUM(SAL) > 5000 GROUP BY JOB; OUTPUT
SELECT JOB,SUM(SAL) FROM EMP WHERE SUM(SAL) > 5000 GROUP BY JOB * ERROR at line 1: ORA-00934: group function is not allowed here

ANALYSIS
Where clause doesn’t allow using group function in the condition. When we are using group function in the condition, we have to use having clause.

118

Siva Kumar HVK INPUT SQL> SELECT JOB,SUM(SAL) FROM EMP GROUP BY JOB HAVING SUM(SAL) > 5000; OUTPUT
JOB SUM(SAL) --------- ---------ANALYST 6000 MANAGER 8275 SALESMAN 5600

ANALYSIS
Displays all the designations whose total salary is more than 5000.

INPUT SQL> SELECT JOB,COUNT(*) FROM EMP GROUP BY JOB HAVING COUNT(*) BETWEEN 3 AND 5; OUTPUT
JOB COUNT(*) --------- ---------CLERK 4 MANAGER 3 SALESMAN 4

ANALYSIS
Displays all the designations whose number where employees between 3 and 5

119

Siva Kumar HVK INPUT
SQL> SELECT SAL FROM EMP GROUP BY SAL HAVING COUNT(SAL) > 1;

OUTPUT
SAL ---------1250 3000

ANALYSIS
Displays all the salaries, which are appearing more than one time in the table.

POINTS TO REMEMBER • WHERE clause can be used to check for conditions based on values of columns and expressions but not the result of GROUP functions. HAVING clause is specially designed to evaluate the conditions that are based on group functions such as SUM , COUNT etc. HAVING clause can be used only when GROUP BY clause is used.

120

Siva Kumar HVK ORDER OF EXECUTION Here are the rules ORCALE uses to execute different clauses given in SELECT command Selects rows based on Where clause Groups rows based on GROUP BY clause Calculates results for each group Eliminate groups based on HAVING clause Then ORDER BY is used to order the results Example INPUT SQL> SELECT JOB.SUM (SAL) FROM EMP WHERE JOB != ‘CLERK’ GROUP BY JOB HAVING SUM(SAL) > 5000 ORDER BY JOB DESC. 121 .

Siva Kumar HVK EXERCISE ANNEXURE – A QUERY 2 122 .

Siva Kumar HVK Course Day Session Duration : : : : Oracle 3 2 2 Hrs Topics Nested Sub Queries Single row Sub queries Multi Row Sub query Multi column Sub query Co-related Sub query Scalar Sub Queries ANY ALL and EXISTS Exercise 123 .

We can write different types sub queries Single row sub queries Multi row sub queries Multi column sub queries Correlated sub queries. 124 . Whenever particular information is not accessible through a single query. SYNTAX Select * FROM SOMETHING WHERE (SUBQUERY (SUBQUERY (SUBQUERY))). Sub queries can be nested as deeply as your implementation of SQL allows. then we have to write different queries one included in another.Siva Kumar HVK Presentation Nested Sub queries Nesting is the act of embedding a sub query within another sub query.

For example. who is drawing maximum salary? INPUT SQL> SELECT ENAME. To get the employee.SAL FROM EMP WHERE SAL = ( SELECT MAX(SAL) FROM EMP). HIREDATE FROM EMP WHERE HIREDATE = ( SELECT MAX(HIREDATE) FROM EMP). OUTPUT ENAME HIREDATE ---------. In nested queries.--------ADAMS 12-JAN-83 ANALYSIS Display the least experienced employee 125 . INPUT SQL> SELECT ENAME.Siva Kumar HVK Single row sub query A Sub query which returns only one value. OUTPUT ENAME -----------KING SAL ---------5000 ANALYSIS Right side query is called as child query and left side query is called parent query. child query executes first before executing parent query.

SAL FROM EMP WHERE SAL < (SELECT MAX(SAL) FROM EMP).Siva Kumar HVK INPUT SQL> SELECT ENAME. 126 . OUTPUT ENAME SAL ---------.---------SMITH 800 ALLEN 1600 WARD 1250 JONES 2975 MARTIN 1250 BLAKE 2850 CLARK 2450 SCOTT 3000 TURNER 1500 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300 ANALYSIS Display all the employees whose salary is less than the maximum salary of all the employees. Query To display all the employees whose salary lines between minimum and maximum salaries INPUT SQL> SELECT * FROM EMP WHERE SAL BETWEEN (SELECT MIN(SAL) FROM EMP) AND (SELECT MAX(SAL) FROM EMP).

we have to use IN operator for comparison. 127 . Multi row Sub queries A sub query. SQL> SELECT EMPNO. OUTPUT ENAME ---------. which returns more than one value.WARD MARTIN SCOTT FORD SAL --------1250 1250 3000 3000 ANALYSIS Displays all the employees who are drawing similar salaries When child query returns more than one value.SAL FROM EMP WHERE DEPTNO=30 AND SAL < (SELECT MAX (SAL) FROM EMP WHERE DEPTNO = 20). INPUT SQL>SELECT ENAME.SAL FROM EMP WHERE SAL IN(SELECT SAL FROM EMP GROUP BY SAL HAVING COUNT(*)> 1). Query Display all the employees from department 30 whose salary is less than maximum salary of department 20.ENAME.Siva Kumar HVK Display all the employees who are getting maximum commission in the organization SQL> SELECT * FROM EMP WHERE COMM = (SELECT MAX(COMM) FROM EMP).

---------KING 10 5000 SCOTT 20 3000 FORD 20 3000 BLAKE 30 2850 ANALYSIS Display all the employees who are drawing maximum salaries in each department DML STATEMENTS IN SUB QUERIES To modify the salary of an employee who is drawing minimum salary with the salary of the employee who is drawing maximum salary INPUT SQL> UPDATE EMP SET SAL = (SELECT MAX(SAL) FROM EMP) WHERE EMPNO = (SELECT EMPNO FROM EMP WHERE SAL = (SELECT MIN (SAL) FROM EMP)).ENAME.MAX(SAL) FROM EMP GROUP BY DEPTNO). SQL> SELECT EMPNO.SAL FROM EMP WHERE (DEPTNO. 128 .DEPTNO.---------.SAL)IN (SELECT DEPTNO. OUTPUT EMPNO ---------7839 7788 7902 7698 ENAME DEPTNO SAL ---------. ANALYSIS Identify the employee who is drawing minimum salary and update with the maximum salary of all the employees.Siva Kumar HVK Multi Column Sub Queries When sub queries returns values from different columns.

Inserts all the selected rows into EMP1 table.Siva Kumar HVK To insert selected rows from emp table to emp1 table INPUT SQL> INSERT INTO EMP1 SELECT * FROM EMP . ANALYSIS EMP1 is an existing table. 129 .

This continues until all rows of main query are retrieved 130 . depending upon the value passed by sub query.---------.---------SMITH 20 800 ALLEN 30 1600 WARD 30 1250 JONES 20 2975 MARTIN 30 1250 CLARK 10 2450 TURNER 30 1500 ADAMS 20 1100 JAMES 30 950 MILLER 10 1300 ANALYSIS Find department wise maximum salaries and display the employees whose salary is less than that value for each department Execution Sequence of steps in Correlated sub queries A row from main query is retrieved Executes sub query with the value retrieved from main query Sub query returns a value to main query Main query’s current row is either selected or not.Siva Kumar HVK CORRELATED SUB QUERIES A correlated sub query is a sub query that receives a value from the main query and then sends a value back to main query. EMPNO ---------7369 7499 7521 7566 7654 7782 7844 7876 7900 7934 ENAME DEPTNO SAL ---------. For example Display all the employees whose salary is less than maximum salary of each department SQL> SELECT EMPNO.DEPTNO.DEPTNO).SAL FROM EMP X WHERE SAL < (SELECT MAX(SAL) FROM EMP WHERE DEPTNO = X.ENAME.

deptno from emp e where exists (select 1 from emp where mgr = e. Find the deptnos which doesnt have any emps in it? A.sal).deptno). 3.SAL FROM EMP X WHERE &N = (SELECT COUNT(DISTINCT SAL) FROM EMP WHERE SAL >=X. job.deptno). OR select deptno.sal from emp e where e. 7.empno).SAL). 6. deptno from emp e where exists (select 1 from emp where mgr = e. Display the employees who have atleast one person reportig to them? A. select ename. 2. deptno from emp e where sal > (select avg(sal) from emp where deptno = e. Display the employees who are earning more than the avg salary in thier respective depts? A. select ename.empno. dname from dept d where not exists (select 1 from emp where deptno = d.sal from emp e where &n >= (select count(*) from emp where deptno = e.Siva Kumar HVK To display the nth highest paid employee INPUT SQL> SELECT EMPNO. e.ename. ename. e. Display all the employee details under the deptnos which have less than N number of employees in it? A.deptno).ENAME. A Few More Examples on Correlated Subqueries: 1.ename. 5. select empno. select e. OUTPUT EMPNO ---------7788 7902 ENAME SAL ---------. job. select distinct deptno. Display the employees who have no one reporting to? A.deptno). sal. select empno.---------SCOTT 3000 FORD 3000 ANALYSIS It selects each row from emp table from parent query and finds the distinct count for each salary whose salary >= the salary returned by main query.empno.sal<(select max(sal) from emp where deptno = e. sal. Display the employees who are not getting max sal in each dept? A.deptno. 4.sal from emp e 131 . Display the details of employee who is drawing nth max sal from emp table? A. ename.empno). deptno from emp e where &n = (select count(*) from emp where sal > x. select deptno.

SQL> SELECT SYSTIMESTAMP FROM DUAL. SQL>SELECT * FROM EMP E WHERE 25 < (SELECT COUNT(*) FROM EMP WHERE MGR = E. And the conditions which filter out the maximum records should be placed at the end after the joins as the parsing is done from BOTTOM to TOP.EMPNO) and SAL >=5000 AND JOB = 'MANAGER' SQL> SELECT SYSTIMESTAMP FROM DUAL.Siva Kumar HVK where exists (select 1 from emp where deptno=e.EMPNO) .ename / Least Efficient ( 156 Mill Sec) SQL>SELECT SYSTIMESTAMP FROM DUAL. 132 . SQL>SELECT * FROM EMP E WHERE SAL >=5000 AND JOB = 'MANAGER' AND 25 < (SELECT COUNT(*) FROM EMP WHERE MGR = E. Most Efficient (110 Mill Sec) SQL>SELECT SYSTIMESTAMP FROM DUAL.deptno group by deptno having count(1)<= &n) order by deptno. Table joins should be written first before any condition of WHERE clause.

The operator can be any one of the standard relational operators ( =. >=. 133 .SAL FROM EMP WHERE SAL > ANY(SELECT SAL FROM EMP). OUTPUT EMPNO ---------7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME SAL ---------.---------ALLEN 1600 WARD 1250 JONES 2975 MARTIN 1250 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 TURNER 1500 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300 ANALYSIS >ANY displays greater than any values in the list. <. <= . SYNTAX Operator ANY list Operator ALL list INPUT SQL> SELECT EMPNO.ENAME. !=) and list is a series of values. >.Siva Kumar HVK ANY And ALL Operators Both are used for comparing one value against a set of values.

---------SMITH 800 ALLEN 1600 WARD 1250 JONES 2975 MARTIN 1250 BLAKE 2850 CLARK 2450 SCOTT 3000 TURNER 1500 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300 ANALYSIS Less than ANY of the list of values INPUT SQL> SELECT EMPNO.SAL FROM EMP WHERE SAL >ALL(SELECT SAL FROM EMP).ENAME. OUTPUT no rows selected ANALYSIS Greater than Maximum of list 134 .ENAME.Siva Kumar HVK INPUT SQL> SELECT EMPNO.SAL FROM EMP WHERE SAL < ANY (SELECT SAL FROM EMP). OUTPUT EMPNO ---------7369 7499 7521 7566 7654 7698 7782 7788 7844 7876 7900 7902 7934 ENAME SAL ---------.

OUTPUT EMPNO ---------7369 7499 7521 7654 7844 7876 7900 7934 ENAME SAL ---------.ENAME.4000).---------SMITH 800 ALLEN 1600 WARD 1250 MARTIN 1250 TURNER 1500 ADAMS 1100 JAMES 950 MILLER 1300 ANALYSIS Less than minimum of List 135 . OUTPUT EMPNO ENAME SAL ---------.---------.4000).SAL FROM EMP WHERE SAL <ALL(3000.SAL FROM EMP WHERE SAL >ALL(3000.2000.ENAME.---------7839 KING 5000 ANALYSIS Greater than maximum of List INPUT SQL> SELECT EMPNO.Siva Kumar HVK INPUT SQL> SELECT EMPNO.2000.

EXISTS checks whether any row is existing in the sub query. OUTPUT EMPNO ---------7369 7499 7521 7566 7654 7698 7782 7788 7844 7876 7900 7902 7934 ENAME SAL MGR ---------.Siva Kumar HVK EXISTS And NOT EXISTS Operators These two operators are exclusively used in correlated sub query. ANY etc.---------.MGR = EMPNO). Remember The following important points to be remembered while dealing with sub queries Sub query can not use ORDER BY clause. because it doesn’t compare values of columns. It checks any row is retrieved from sub query or not.ENAME. and NOT EXISTS does the opposite. If any row is retrieved from sub query the EXISTS returns true otherwise it returns False. EXISTS is different from other operators like IN .MGR FROM EMP X WHERE EXISTS(SELECT MGR FROM EMP WHERE X. Because ORDER BY clause must be the last clause of SELECT BETWEEN … AND operator can not be used with Sub queries 136 . INPUT SQL> SELECT EMPNO.---------SMITH 800 7902 ALLEN 1600 7698 WARD 1250 7698 JONES 2975 7839 MARTIN 1250 7698 BLAKE 2850 7839 CLARK 2450 7839 SCOTT 3000 7566 TURNER 1500 7698 ADAMS 1100 7788 JAMES 950 7698 FORD 3000 7566 MILLER 1300 7782 Note :Use EXISTS in place of IN for Base Tables to improve the performance.SAL. instead.

Display the details of students who have paid the highest amount so far in their course. Display the details of subjects that have been taken by more than two students 137 . one employee is drawing minimum salary and is having some designation. Display the employees from other departments whose designation is matching with the designation of the above employee. Display the employees who reported to KING Display all the employees whose salary is less than the minimum salary of MANAGERS. Display all the employees whose salary is within ±1000 from the average salary of all the employees.Siva Kumar HVK Exercise In department 20.

Siva Kumar HVK Course Day Session Duration : : : : Oracle 3 3 2 Hrs Exercise Annexure Query III 138 .

Siva Kumar HVK Course Day Session Duration : : : : Oracle 3 4 1 Hrs Revision / Doubts 139 .

Siva Kumar HVK Course Day Session Duration : : : : Oracle 4 1&2 5 Hrs Topics Integrity Constraints DDL and DML commands Transactional Control statements Referential Integrity constraints Exercise 140 .

If constraint is not satisfied the operation will fail. deleted or updated. 141 . Constraint Guidelines Name a constraint or the Oracle server generates a name by using the SYS_Cn format Create a constraint either: . Constraints are normally defined at the time of creating table.Siva Kumar HVK Presentation INTEGRITY CONSTRAINTS Constraints are used to implement standard rules such as uniqueness in the key filed and business rule such as AGE column should contain a value between 15 and 60 etc. or .At the same time as the table is created. Oracle server makes sure that the constraints are not violated whenever a row is inserted. Define a constraint at the column or table level. View a constraint in the Data dictionary .After the table has been created. But it is also possible to define constraints after the table is created.

A typical example is PRIMARY KEY constraint when a single column is the primary key of the table. if so. It may consist of more than one column. 142 . UNIQUE + NOT NULL = PRIMARY KEY • Automatically creates unique index to enforce uniqueness. A typical example is PRIMARY KEY constraint that is used to define composite primary key. it is called as composite primary key. at which it is defined. There can be only one primary key in a table. It may refer to more than one column of the table. It defines a rule for a single column. Various types of Integrity constraints PRIMARY KEY UNIQUE NOT NULL CHECK PRIMARY KEY It is used to uniquely identify rows in a table.Siva Kumar HVK TYPES OF CONSTRAINTS Constraints are classified into two types Table Constraints Column Constraints Table Constraint A constraint given at the table level is called as Table Constraint. ( It maintains uniqueness in the data and null values are not acceptable).e. It cannot refer to column other than the column. Column Constraint A constraint given at the column level is called as Column constraint. i.

Pseudocolumns are not actual columns in a table but they behave like columns. not at the table level. • Oracle automatically creates a unique index for the column. If the UNIQUE constraint comprises more than one column. no two rows of table can have duplicate values in a specified column or set of columns. the group of columns is called a composite unique key. However. For example. you cannot insert into.USER functions . or delete from a pseudocolumn. NOT NULL Uniqueness not maintained and null values are not acceptable. Defines a condition that each row must satisfy The following expressions are not allowed . Note: The NOT NULL constraint can be specified only at the column level.References to CURRVAL.that is. The column (or set of columns) included in the definition of the UNIQUE key constraint is called the unique key. CHECK Defines the condition that should be satisfied before insertion and updating is done.Calls to SYSDATE.Queries that refer to other values in other rows Note: . Maintains unique and NULL values are Example : EmailID A UNIQUE key integrity constraint requires that every value in a column or set of columns (key) be unique.UID. you can select clause from pseudo columns. 143 . update.Siva Kumar HVK UNIQUE acceptable. NEXTVAL and ROWNUM pseudocolumns .

Example : SQL>CREATE TABLE EMPL47473 (EMPNO NUMBER(3)CONSTRAINT PK_EMPL47473_EMPNO PRIMARY KEY. There is no need to save explicitly.e. Drop DDL STATEMENTS COMMITS AUTOMATICALLY. Create Table CREATE TABLE <TABLE-NAME> (COLUMN DEFINITION1. Syntax :Column Def : <Name> Data type [Default Value] [constraint <name> constraint type] Note: = Min. “-“ i. GENDER CHAR(1) CONSTRAINT CHK_EMPL47473_GENDER CHECK(UPPER (GENDER) IN (‘M’. DESIGNATION VARCHAR2 (15). 144 .’F’)). “#”.2) CHECK (SALARY BETWEEN 10000 AND 70000)). Alter. EMAIL_ID VARCHAR2 (30) UNIQUE.# are used mainly for system tables. SALARY NUMBER (7. Column in a table = 1 Max.Siva Kumar HVK DDL (Data Definition language) Create. Columns in a table = 1000 Rules: 1. COLUMN DEFINITION2). $. ENAME VARCHAR2 (10) NOT NULL. They can’t consist of any special characters other than “$”. A table or a column name must never start a number but they can contain numbers in them 2.

Select statement is used to view the constraints defined on the table 145 .------------------------------------------------------SYS_C003018 C "ENAME" IS NOT NULL CHK_EMPL47473_GENDER SYS_C003020 PK_EMPL47473_EMPNO ANALYSIS C C P UPPER (GENDER) IN ('M'. Tables defined by a user are stored in a data dictionary table USER_TABLES SQL> DESCRIBE USER_CONSTRAINTS SQL> SELECT CONSTRAINT_NAME.Siva Kumar HVK Note : Constraint name is useful for manipulating the given constraint When the constraint name is not given at the time of defining constraints. system creates a constraint with the name SYS_Cn. SEARCH_CONDITION FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'EMPL47473'. USER_CONS_COLUMNS. Constraints defined on a particular table are store in a data dictionary table USER_CONSTRAINTS.'F') SALARY BETWEEN 10000 AND 70000 SYS_C003022 Describe displays structure of the data dictionary table. OUTPUT CONSTRAINT_NAME CONSTRAINTTYPE SEARCH_CONDITION ---------------------------. CONSTRAINT_TYPE.

Siva Kumar HVK SQL> DESCRIBE USER_CONS_COLUMNS SQL> SELECT CONSTRAINT_NAME.---------------------------GENDER EMPNO ENAME SALARY EMAIL_ID ANALYSIS Describe displays structure of the data dictionary table. OUTPUT CONSTRAINT_NAME --------------------------------CHK_EMPL47473_GENDER PK_EMPL47473_EMPNO SYS_C003018 SYS_C003020 SYS_C003022 COLUMN_NAME . Select statement is used to view the constraints defined on the column 146 .COLUMN_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME = 'EMPL47473'.

Other constraints are removed only by referring constraint name. SQL> ALTER TABLE EMPL47473 DROP COLUMN PINCODE. SQL> ALTER TABLE EMPL47473 MODIFY (ENAME CHAR (15). DOJ DATE. 147 . ANALYSIS To remove the primary key from table.PINCODE VARCHAR2(7)).for modifying the structure of columns . ANALYSIS To add primary key in the table without constraint name. It creates constraint name with SYS_Cn. INPUT SQL>ALTER TABLE EMPL47473 ADD PRIMARY KEY(EMPNO).for renaming the column name ( Only from 9i) SQL> ALTER TABLE EMPL47473 ADD (ADDRESS VARCHAR2 (30).2)). SQL> ALTER TABLE EMPL47473 RENAME COLUMN ENAME TO EMPNAME Note: This command is also useful for manipulating constraints INPUT SQL> ALTER TABLE EMPL47473 DROP PRIMARY KEY. ADD MODIFY DROP RENAME .ADDRESS).Siva Kumar HVK ALTER TABLE Used to modify the structure of a table SYNTAX ALTER TABLE <TABLENAME> [ ADD | MODIFY | DROP | RENAME] ( COLUMN(S)).for adding new columns into the table . SQL> ALTER TABLE EMPL47473 DROP (DESIGNATION. SALARY NUMBER (8.for removing a column in the table ( 8i) .

&SALARY).COLUMNNAME. ‘RAMESH_B@YAHOO.’&DOJ’).SALARY) VALUES(101.SALARY) VALUES(&EMPNO. OR SQL> INSERT INTO EMPL47473(EMPNO. TO INSERT SPECIFIED COLUMNS IN THE TABLE SQL> INSERT INTO EMPL47473(EMPNO.’RAVI’.’&EMAIL_ID’. OR SQL> INSERT INTO EMPL47473 VALUES(&EMPNO .….Siva Kumar HVK INPUT SQL>ALTER TABLE EMPL47473 ADD CONSTRAINT PK_EMPL47473_EMPNO PRIMARY KEY(EMPNO).’RAVI’. ’&EMPNAME’.’&GENDER’. ANALYSIS To add primary key in the table with constraint name DATA MANIPULATION INSERTING ROWS SYNTAX INSERT INTO TABLENAME [ COLUMNNAME.COM’.’10-JAN-2001’).EMPNAME.’M’.EMPNAME.5000.] VALUES(VALUE1 VALUE2 VALUE3 ) SQL> INSERT INTO EMPL47473 VALUES(101.’7EMPNAME’. ANALYSIS We can’t skip primary key and NOT NULL columns 148 . 5000).&SALARY.

Changes made on the database are recorded only in the shadow page. SAVEPOINT We can use save points to roll back portions of your current set of transactions For example SQL> INSERT INTO EMPL47473 VALUES(105.5000.’M’. ‘LATHA_D@YAHOO.COM’. ‘KIRAN_B@YAHOO. SQL>ROLLBACK.’LATHA’. For saving the information we have to use a command COMMIT.COM’.’10-JAN-2001’). ANALYSIS Information from shadow page flushed back to the table and shadow page gets destroyed automatically. SQL> SAVEPOINT A SQL> INSERT INTO EMPL47473 VALUES(106. SQL> SAVEPOINT B 149 .’15-JAN-2002’).’KIRAN’.5000.SAVEPOINT ( Called as Transactional processing statements) SQL>COMMIT.Siva Kumar HVK Note :. ROLLBACK.’F’. ANALYSIS Shadow page destroys automatically without transferring the information back to the table.

When we SELECT data from the table SQL> SELECT * FROM EMPL47473.COM 5000 10-JAN-01 LATHA_D@YAHOO. such as a computer failure. Now roll back just the last insert: SQL> ROLLBACK TO B.’15-JAN-2002’).COM 5000 15-JAN-02 RADHA_V@GMAIL. or quit.’F’. even without your instructing it to.15000. and you experience serious difficulties. 150 .Siva Kumar HVK SQL> INSERT INTO EMPL47473 VALUES(107. exit (the equivalent to exit). EMPNO ------105 106 107 EMPNAME ---------KIRAN LATHA RADHA G M F F EMAIL_ID SALARY DOJ -----------------. updates or deletes. but not yet explicitly or implicitly committed them. If the machine or database goes down.’RADHA’. automatically commits. ‘RADHA_V@GMAIL. IMPLICIT COMMIT The actions that will force a commit to occur.COM 15000 15-JAN-02 The output shows the three new records we’ve added . Note : Rollback works only on uncommitted data A DDL transaction after a DML transaction. AUTO ROLLBACK If you’ve completed a series of inserts. We can use an Environment command SET VERIFY OFF to remove the old and new messages while inserting data.---------. any DDL command forces a commit.--------KIRAN_B@YAHOO.COM’. it does this as cleanup work the next time the database is brought back up. Oracle automatically roll back any uncommitted work.

By issuing frequent COMMIT statements. the performance of the program is enhanced & its resource requirements are minimized as COMMIT frees up the following resources: Information held in the rollback segments to undo the transaction if necessary. All locks acquired during statement processing Space in the redo log buffer cache Overhead associated with any internal Oracle mechanisms to manage the resources in the previous three items.Siva Kumar HVK ISSUE Frequent commit statements Whenever possible. issue frequent COMMIT statements in all your programs. 151 .

’CLERK’. SQL> UPDATE EMP47473 SET SAL = SAL*1.Siva Kumar HVK CREATING A TABLE FROM ANOTHER TABLE SYNTAX CREATE TABLE <TABLENAME> AS SELECT <COLUMNS> FROM <EXISTING TABLE> [WHERE <CONDITION>].SAL*1.1.ENAME. SQL> COMMIT / ROLLBACK. ANALYSIS To give uniform increments to all the employees SQL> UPDATE EMP47473 SET SAL = DECODE (JOB. column2 = expression WHERE <condition>. To add a new column in the table SQL> ALTER TABLE EMP47473 ADD(SEX CHAR(1)).SAL*1.SAL. ‘SALESMAN’.2. 152 .1.15).JOB FROM EMP. Example SQL> CREATE TABLE EMP47473 AS SELECT EMPNO. SQL> COMMIT / ROLLBACK.SAL*1. SQL> SELECT * FROM EMP47473. UPDATING ROWS This command is used to change the data of the table SYNTAX UPDATE <TABLENAME> SET column1 = expression.

’MILLER’.’Mr.’BLAKE’). SQL> COMMIT / ROLLBACK. SQL> COMMIT / ROLLBACK.’||ENAME. or Ms. Before the existing name as per the SEX value 153 . SQL> COMMIT / ROLLBACK.’M’.’||ENAME). SQL> UPDATE EMP47473 SET SEX = ‘F’ WHERE SEX IS NULL. SQL> SELECT * FROM EMP47473. ANALYSIS ADD Mr.Siva Kumar HVK SQL> UPDATE EMP47473 SET SEX = ‘M’ WHERE ENAME IN (‘KING’. SQL> UPDATE EMP47473 SET ENAME = DECODE(SEX.’Ms. SQL> SELECT * FROM EMP47473 .

It is a DDL statement. SQL> COMMIT | ROLLBACK. It removes the data along with table definitions and the table. it automatically commits. SQL> DELETE FROM EMP47473 WHERE SEX = ‘M’. 154 . Once the table is truncated.Siva Kumar HVK DELETING ROWS - SYNTAX DELETE FROM <TABLENAME> WHERE <CONDITION>. TRUNCATING A TABLE SYNTAX TRUNCATE TABLE <TABLENAME> Note : Removes all the rows from table. It is a DDL statement Droping a table SYNTAX DROP TABLE <TABLENAME> Note : Table is dropped permanently. Deleting specified rows is Not possible.

Siva Kumar HVK Adding comments to a table You can add comments up to 2000 bytes about a column.column IS ‘text’ . view by using the COMMENT statement. The comment is stored in the data dictionary and can be viewed in one of the following data dictionary views in the COMMENTS column: ALL_COL_COMMENTS USER_COL_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS Syntax COMMENT ON TABLE table | COLUMN table. table. 155 .

Siva Kumar HVK REFERENTIAL INTEGRITY CONSTRAINTS This constraint is useful for maintaining relation with other table. dno) Deptno of Department47473 is a primary key Empno of Employee47473 is a primary key Dno of Employee47473 is a reference key 156 . Various referential integrity constraints we can use in Oracle are Foreign Key References On delete cascade On Delete Set NULL Foreign Key: Defines the column in the child table at the table constraint level References table Identifies the table and column in the parent Reference key accepts NULL and duplicate values. ename. Example Department47473 (Deptno . On delete cascade Deletes the dependent rows in the child table when a row in the parent table is deleted. salary. dname) Employee47473 (Empno. On Delete Set NULL Converts dependent foreign key values to null.

itemno number (3) references itemmaster (itemno). dno number(3) references department47473(deptno) on delete cascade). stock number (3) check (stock > 0)). ename varchar2(10) Not null. quantity number (3) check (quantity > 0). itemno)). salary number(7. SQL>Create table itemtran (trnno number (3). 157 .’I’)). SQL>Create table itemmaster (itemno number (3) primary key. primary key (trnno.Siva Kumar HVK Solution SQL>Create table department47473 (deptno number(3) primary key. SQL>Create table employee47473(empno number(3) primary key. Itemno Trnno Itemmaster itemname stock Itemtran itemno trndate trntype quantity Assume the case where with each transaction customer orders more than one item. dname varchar2(20) Not null). Assume the case where supermarket selling various items and customers order the items. itemname varchar2 (10). trndate date.2) check(salary > 0). trntype char (1) check (upper (trntype) in (‘R’.

Note : It is not possible to enable using cascade 158 .Siva Kumar HVK DROP TABLE <TABLENAME> CASCADE CONSTRAINTS ANALYSIS Dropping the table along with constraints ALTER TABLE <tablename> DROP PRIMARY KEY CASCADE. ANALYSIS Removing the primary key along with Reference key ALTER TABLE <TABLENAME> DISABLE PRIMARY KEY ALTER TABLE <tablename> DISABLE PRIMARY KEY CASCADE.

into which the students are joining for various courses ( Also. attributes and define them with relations 159 . assume the case where same student can join in more than one course) The students may pay the fee in installments • Identify the tables.Siva Kumar HVK Exercise • Consider a training institute conducting different courses.

Siva Kumar HVK Course Day Session Duration : : : : Oracle 4 3 2 Hrs Topics Joins 160 .

Siva Kumar HVK
Presentation

JOINS Objectives
Join will enable you to gather and manipulate data across several tables. By One of the most powerful features of SQL is its capability to gather and manipulate data from across several tables. Without this feature you would have to store all the data elements necessary for each application in one table. Without common tables you would need to store the same data in several tables.

Objectives After completing this lesion, you should be able to do the following. ■ Write SELECT statements to access data from more than one table using equality and nonequality join. ■ View Data that generally does not meet condition by using outer joins ■ Join a table itself by using self join a join

161

Siva Kumar HVK TYPES OF JOINS Oracle Proprietary Joins(8i and prior) ●EquiJoin ●Non-equi join ●Outer join ●SelfJoin SQL:1999 Compliant Joins: ● Cross Joins ● Natural Joins ● Using caluse ● Full or two sided outer join ● Arbitrary join conditions For Outer joins

Types of Joins
The Oracle 9i database offers join syntax that is SQL: 1999 compliant. Prior to 9i release, the join syntax was different from the ANSI standards. The new SQL: 1999 compliant join syntax does not offer any performance benefits over the Oracle proprietary join syntax that existed in prior releases.

162

Siva Kumar HVK

Joining tables using Oracle Syntax
Use a join to query data from more than one table SELECT Table1.column1, table2.column2

FROM table1,table2 WHERE table1.column1 = table2.column2;
• Write the join condition in the WHERE clause. Prefix the column name with table name when the same column name appears in more than one table.

Guidelines • When writing a SELECT statement that joins tables, precede the common column name with the table name for clarify and to enhance database access. If the same column name appears in more than one table, the column name must be prefixed with the table name. To join n tables together, you need a minimum of n-1 join conditions. This rule many not apply if your table has a concatenated primary key, in which case more than one column is required to uniquely identify each row.

• •

163

Siva Kumar HVK

What is An Equi Join?

Departments

Employees

164

Siva Kumar HVK Equi join
Extracting the information from more than one table by comparing ( = ) the common information. Note : Equi Joins are also called as simple joins or Inner Joins

To display common column information

SQL> SELECT EMPNO,ENAME,JOB,SAL,DNAME FROM EMP,DEPT WHERE EMP.DEPTNO = DEPT.DEPTNO;
OUTPUT
EMPNO ---------7782 7839 7934 7369 7876 7902 7788 7566 7499 7698 7654 7900 7844 7521 ENAME ---------CLARK KING MILLER SMITH ADAMS FORD SCOTT JONES ALLEN BLAKE MARTIN JAMES TURNER WARD JOB SAL DNAME --------- ---------- ---------MANAGER 2450 ACCOUNTING PRESIDENT 5000 ACCOUNTING CLERK 1300 ACCOUNTING CLERK 800 RESEARCH CLERK 1100 RESEARCH ANALYST 3000 RESEARCH ANALYST 3000 RESEARCH MANAGER 2975 RESEARCH SALESMAN 1600 SALES MANAGER 2850 SALES SALESMAN 1250 SALES CLERK 950 SALES SALESMAN 1500 SALES SALESMAN 1250 SALES

ANALYSIS Efficiency is more when we compare the information from lower data table(master table) to Higher data table( child table). When Oracle processes multiple tables, it uses an internal sort/merge procedure to join those tables. First, it scans & sorts the first table (the one specified last in FROM clause). Next, it scans the second table (the one prior to the last in the FROM clause) and merges all of the retrieved from the second table with those retrieved from the first table. It takes around 0.96 seconds

165

losal and g.EMP WHERE EMP.ENAME. INPUT SQL> select empno.DEPTNO = DEPT.Siva Kumar HVK SQL> SELECT EMPNO.hisal / ANALYSIS Displays all the employees whose salary lies between any pair of low and high salary ranges.DEPTNO. OUTPUT DEPTNO DNAME LOC ---------.grade.losal.09 seconds So.sal between g. Non-Equi joins Getting the information from more than one table without using comparison (=) operator.SAL. Efficiency is less.DNAME FROM DEPT. ANALYSIS Here driving table is EMP. INPUT SQL> SELECT * FROM DEPT WHERE DEPTNO NOT IN (SELECT DISTINCT DEPTNO FROM EMP).hisal from salgrade g.sal.JOB.emp e where e.-------------------------40 OPERATIONS BOSTON ANALYSIS Displays the details of the department where there are no employees 166 . It takes around 26.ename.

SQL> SELECT DEPTNO FROM DEPT MINUS SELECT DEOTNO FROM EMP. 167 . SQL> SELECT DEPTNO FROM DEPT UNION SELECT DEOTNO FROM EMP. SQL> SELECT DEPTNO FROM DEPT UNION ALL SELECT DEOTNO FROM EMP.Siva Kumar HVK We can also get above output using relational algebra operators.

ENAME. OUTPUT EMPNO ---------7782 7839 7934 7369 7876 7902 7788 7566 7499 7698 7654 7900 7844 7521 ENAME JOB SAL DNAME ---------.Siva Kumar HVK OUTER JOIN It is a join.DNAME FROM DEPT.------------CLARK KING MILLER SMITH ADAMS FORD SCOTT JONES ALLEN BLAKE MARTIN JAMES TURNER WARD MANAGER PRESIDENT CLERK CLERK CLERK ANALYST ANALYST MANAGER SALESMAN MANAGER SALESMAN CLERK SALESMAN SALESMAN 2450 5000 1300 800 1100 3000 3000 2975 1600 2850 1250 950 1500 1250 ACCOUNTING ACCOUNTING ACCOUNTING RESEARCH RESEARCH RESEARCH RESEARCH RESEARCH SALES SALES SALES SALES SALES SALES OPERATIONS 168 .SAL.--------.DEPTNO(+). It is represented by +. which forcibly joins multiple tables even without having the common information.EMP WHERE DEPT.---------. SQL> SELECT EMPNO.JOB.DEPTNO = EMP.

Siva Kumar HVK LEFT. SQL> SELECT EMPNO.-----------MILLER KING CLARK FORD ADAMS SCOTT JONES SMITH JAMES TURNER BLAKE MARTIN WARD ALLEN CLERK PRESIDENT MANAGER ANALYST CLERK ANALYST MANAGER CLERK CLERK SALESMAN MANAGER SALESMAN SALESMAN SALESMAN 10 10 10 20 20 20 20 20 30 30 30 30 30 30 ACCOUNTING ACCOUNTING ACCOUNTING RESEARCH RESEARCH RESEARCH RESEARCH RESEARCH SALES SALES SALES SALES SALES SALES ANALYSIS Gets the common information. and forcibly joins from left side table to right side table.DEPTNO. you can tell Oracle to perform a LEFT. ENAME. JOB. 169 . RIGHT or FULL OUTER join. DEPT.DEPTNO. you can use the ANSI SQL standard syntax for outer joins.---------. EMPNO ----------7934 7839 7782 7902 7876 7788 7566 7369 7900 7844 7698 7654 7521 7499 ENAME JOB DEPTNO DNAME ---------. DNAME FROM EMP LEFT OUTER JOIN DEPT ON DEPT. RIGHT AND FULL OUTER JOIN As of Oracle 9i.--------. In the FROM clause.DEPTNO = EMP.

---------. OUTPUT EMPNO ---------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB DEPTNO DNAME --------.DEPTNO. SQL> SELECT EMPNO. 170 . DEPT. OUTPUT EMPNO ---------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB DEPTNO DNAME --------. and then forcibly joins from dept table to emp table. DNAME FROM DEPT LEFT OUTER JOIN EMP ON DEPT. ENAME.DEPTNO.DEPTNO.DEPTNO = EMP. JOB.DEPTNO. JOB. DNAME FROM DEPT RIGHT OUTER JOIN EMP ON DEPT. DEPT.-------------CLERK 20 RESEARCH SALESMAN 30 SALES SALESMAN 30 SALES MANAGER 20 RESEARCH SALESMAN 30 SALES MANAGER 30 SALES MANAGER 10 ACCOUNTING ANALYST 20 RESEARCH PRESIDENT 10 ACCOUNTING SALESMAN 30 SALES CLERK 20 RESEARCH CLERK 30 SALES ANALYST 20 RESEARCH CLERK 10 ACCOUNTING ANALYSIS Gets the common information from both tables. then forcibly joins from dept table to emp table. ENAME.---------.DEPTNO = EMP.Siva Kumar HVK SQL> SELECT EMPNO.-------------CLERK 20 RESEARCH SALESMAN 30 SALES SALESMAN 30 SALES MANAGER 20 RESEARCH SALESMAN 30 SALES MANAGER 30 SALES MANAGER 10 ACCOUNTING ANALYST 20 RESEARCH PRESIDENT 10 ACCOUNTING SALESMAN 30 SALES CLERK 20 RESEARCH CLERK 30 SALES ANALYST 20 RESEARCH CLERK 10 ACCOUNTING 40 OPERATIONS ANALYSIS Gets the common information from both tables.

6 sec) SELECT ENAME. 171 .MGR FROM EMP E WHERE 25 < (SELECT COUNT(*) FROM EMP WHERE MGR = E.-------------CLERK 20 RESEARCH SALESMAN 30 SALES SALESMAN 30 SALES MANAGER 20 RESEARCH SALESMAN 30 SALES MANAGER 30 SALES MANAGER 10 ACCOUNTING ANALYST 20 RESEARCH PRESIDENT 10 ACCOUNTING SALESMAN 30 SALES CLERK 20 RESEARCH CLERK 30 SALES ANALYST 20 RESEARCH CLERK 10 ACCOUNTING 40 OPERATIONS ANALYSIS Gets the common information from both tables. DEPT. DNAME FROM EMP RIGHT OUTER JOIN DEPT ON DEPT.MGR FROM EMP E WHERE SAL > 50000 AND JOB = ‘MANAGER’ AND 25 < (SELECT COUNT(*) FROM EMP WHERE MGR = E. ENAME.Siva Kumar HVK SQL> SELECT EMPNO.DEPTNO.EMPNO) AND SAL > 5000 AND JOB = ‘MANAGER’.6 Sec) SELECT ENAME.JOB. Least Efficient (Total CPU = 153. JOB.DEPTNO. OUTPUT EMPNO ---------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB DEPTNO DNAME --------. Position of Joins in where clause Table joins should be written first before any condition of WHERE clause. And the conditions which filter out the maximum records should be placed at the end after the joins as the parsing is done from BOTTOM to TOP For ex. Most Efficient (Total CPU time = 10. then forcibly joins from dept table to emp table.JOB.---------.EMPNO).DEPTNO = EMP.

SQL> SELECT WORKER.ENAME || ' IS WORKING UNDER ' || MANAGER.ENAME||'ISWORKINGUNDER'||MANAGE -------------------------------------SCOTT IS WORKING UNDER JONES FORD IS WORKING UNDER JONES ALLEN IS WORKING UNDER BLAKE WARD IS WORKING UNDER BLAKE JAMES IS WORKING UNDER BLAKE TURNER IS WORKING UNDER BLAKE MARTIN IS WORKING UNDER BLAKE MILLER IS WORKING UNDER CLARK ADAMS IS WORKING UNDER SCOTT JONES IS WORKING UNDER KING CLARK IS WORKING UNDER KING BLAKE IS WORKING UNDER KING SMITH IS WORKING UNDER FORD ANALYSIS It displays who is working under whom.Siva Kumar HVK SELF JOIN Joining the table from itself is called as self join. MGR number appearing against employee is the employee number of manager 172 . OUTPUT WORKER.ENAME FROM EMP WORKER. EMP MANAGER WHERE WORKER.MGR = MANAGER.EMPNO.

OUTPUT EMPNO ---------7782 7839 7934 7369 7876 7902 7788 7566 7499 7698 7654 7900 7844 7521 ENAME ---------CLARK KING MILLER SMITH ADAMS FORD SCOTT JONES ALLEN BLAKE MARTIN JAMES TURNER WARD JOB DEPTNO DNAME --------. INPUT SQL> SELECT EMPNO. To get the common information from two tables.-------------MANAGER 10 ACCOUNTING PRESIDENT 10 ACCOUNTING CLERK 10 ACCOUNTING CLERK 20 RESEARCH CLERK 20 RESEARCH ANALYST 20 RESEARCH ANALYST 20 RESEARCH MANAGER 20 RESEARCH SALESMAN 30 SALES MANAGER 30 SALES SALESMAN 30 SALES CLERK 30 SALES SALESMAN 30 SALES SALESMAN 30 SALES 173 .ENAME.DEPTNO. • If the columns having the same names have different data types.Siva Kumar HVK NATURAL AND INNER JOINS (Introduced in 9i) We can use natural keyword to indicate that a join should be performed based on all columns that have the same name in the two tables being joined.JOB.---------. For example.DNAME FROM DEPT 2 NATURAL JOIN EMP. Creating Natural Joins • The Natural join clause is based on all columns in the two tables that have the same name. an error is returned. • It selects rows from the two tables that have equal values in all matched columns.

■Do not use a table name or alias in the referenced columns ■The NATURAL JOIN and USING clauses are mutually exclusive. the NATURAL JOIN clause can be modified with USING clause to specify the columns that should be used for an equijoin. 174 . ■use the USING clause to match only one column when more than one column matches.Siva Kumar HVK Creating Joins with Using Caluse ■ If several columns have the same names but the data types do not match.

Siva Kumar HVK INNER JOIN Support for INNER join syntax was introduced in Oracle9i. DEPT. CROSS JOIN (CARTESIAN PRODUCT) Joining tables without giving proper join condition. 14 rows (emp table) X 4 rows(dept table) = 56 rows. inner joins are the default – they return the rows the two tables have in common.DEPTNO = DEPT. INPUT SQL> SELECT * FROM DEPT. DNAME FROM EMP INNER JOIN DEPT ON EMP. Note that they support ON clause. and are the alternative to outer joins. OR SQL> SELECT * FROM EMP CROSS JOIN DEPT. so that you can specify join criteria. ANALYSIS It multiplies the rows from both tables and displays the output i. ENAME.e. JOB.DEPTNO. SQL>SELECT EMPNO. 175 .DEPTNO.EMP.

Siva Kumar HVK Course Day Session Duration : : : : Oracle 4 4 1 Hrs EXERCISE ANNEXURE QUERY III 176 .

Siva Kumar HVK Course Day Session Duration : : : : Oracle 5 1 3 Hrs Topics Other Objects Sequence Object Views Indexes Synonyms 177 .

the sequence starts with 1. SYNTAX CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}].) CACHE n | NOCACHE specifies how many values the Oracle server preallocates and keep in memory (By default.Siva Kumar HVK Presentation OTHER OBJECTS SEQUENCE OBJECT Used to generate sequence (Unique) Integers for use of primary keys.) MINVALUE n specifies the minimum sequence value NOMINVALUE specifies a minimum value of 1 for an ascending sequence and – (10^26) for a descending sequence (This is the default option.) START WITH n specifies the first sequence number to be generated (If this clause is omitted. Sequence is the name of the sequence generator INCREMENT BY n specifies the interval between sequence numbers where n is an integer (If this clause is omitted.) CYCLE | NOCYCLE specifies whether the sequence continues to generate values after reaching its maximum or minimum value (NOCYCLE is the default Option.) MAXVALUE n specifies the maximum value the sequence can generate NOMAXVALUE specifies a maximum value of 10^27 for an ascending sequence and –1 for a descending sequence (This is the default option. the sequence increments by 1.) The value set must be less than MAXVALUE minus 178 . the Oracle server caches 20 values.

These sequences are stored in a data dictionary table USER_SEQUENCES. which gives the current value of the sequence object Assume there is a table 179 . This sequence object provides two public member functions NEXTVAL and CURRVAL NEXTVAL is a function which generate next value from sequence object CURRVAL is a function. CREATE SEQUENCE SQNO47473 START WITH 1 INCREMENT BY 1 MAVALUE 10 CACHE 3 CYCLE. Note: .Siva Kumar HVK Example CREATE SEQUENCE SQNO47473 START WITH 1 INCREMENT BY 1 MAXVALUE 10.

TO MODIFY THE SEQUNECE OBJECT SQL> ALTER SEQUENCE SQNO47473 INCREMENT BY 2 MAXVALUE 40.Siva Kumar HVK EMPNO SAMPLE47473 ENAME SAL To insert the values into the table SQL> INSERT INTO SAMPLE47473 VALUES(SQNO47473. ‘&ENAME’. VIEWS 180 . &SAL).NEXTVAL. Note : We can’t change starting value To remove the sequence object SQL> DROP SEQUENCE <SEQUENCE_NAME>.

COMPLEX view is a view.+Critical data in the base table is safeguarded as access to such data can be controlled. SYNTAX CREATE OR REPLACE [FORCE] VIEW <VIEWNAME> AS SELECT <COLUMNS> FROM <TABLE > [ WITH READ ONLY]. the base table should exist before the view is used. It is used to reduce the complexity of the query In Oracle Oracle we can create different types of views SIMPLE COMPLEX INLINE SIMPLE view is a view. However. Generally used in TOP N Analysis. The table on which a view is based is called as base table FORCE option allows view to be created even if the base table doesn’t exist. which is created using more than one table or using group functions INLINE view is a view.Siva Kumar HVK A view is an object. Changing Base Table through view 181 . • It is a named sub query in the FROM clause of the main query. which is created using sub query (it is not a schema object. which is a logical representation of a table A view contains no data on its own It is derived from tables Changes made in tables are automatically reflected in views As a view does not store any data the redundancy problem does not arise. which is created using only one base table.

Example SQL> CREATE OR REPLACE VIEW TESTVIEW47473 AS SELECT EMPNO.Siva Kumar HVK A view can also be used to change the data of base table A view can be used to delete.These views are stored in a data dictionary table USER_VIEWS 182 . However for each operation certain conditions are to be satisfied. Rules for deleting row The following should NOT be used in the query. Note: .SAL FROM EMP47473. More than one table GROUP BY clause GROUP Function DISTINCT clause Pseudo column ROWNUM Rules for updating rows The following are the rules that are to be satisfied to update base table through view. Rules for insertion of rows All the rules of UPDATE Al NOT NULL columns should be included in the view.ENAME. insert and update rows in the base table. All the rules of Delete are applicable The column being updated should not be derived from an expression.

Insertion and updation is not allowed into base table through view. It doesn’t allow you to update the condition column as well as it doesn’t allow you to insert the details of employees with DEPTNO other than 20. Such views are called as INLINE views. SQL> CREATE OR REPLACE VIEW CHKVIEW AS SELECT * FROM EMP WHERE DEPTNO = 20 WITH CHECK OPTION.-2) YEAR.SAL FROM EMP47473 WITH READ ONLY. To remove a view SQL> DROP VIEW <VIEWNAME>. ENAME. COUNT(*) NUMB FROM EMP47473 GROUP BY JOB. ANALYSIS View becomes a read only view WITH CHECK OPTION This option is used to prevent any changes to base table through view. They are by default read only.Siva Kumar HVK SQL> CREATE OR REPLACE VIEW TESTVIEW47473 AS SELECT EMPNO. SQL> CREATE OR REPLACE VIEW SIMPLEVIEW47473 AS SELECT SUBSTR(HIREDATE. We can also create a view using group functions. INDEX 183 .

Note :. an index in Oracle is a list of values of a column in the ascending order. SYNTAX CREATE [UNIQUE] INDEX index_name ON table(column1. I. Just like how book index is sorted in the ascending order of topics. It contains the values of the indexed column(s) in the ascending order along with address of each row. but WHERE clause doesn’t refer to indexed column. 184 .…). you never have to open or close an index.Siva Kumar HVK The concept indexing in Oracle is same as a book index.A UNIQUE index is automatically created when you use PRIMARY KEY and UNIQUE constraints An index can have up to 32 columns. An oracle index is a database object. When Oracle Does Not Use Index Oracle index is completely automatic.Indexes are stored in the data dictionary table USER_INDEXES. The following are the cases in which Oracle does NOT use index. Why to Use An INDEX INDEXES in ORACLE are used for two purposes To speed up data retrieval and thereby improving performance of query To enforce uniqueness Note :. Page number in book index is similar to ROWID if Oracle index.. The address of rows are obtained using ROWID pseudo column. Oracle server decides whether to use an index or not. SELECT doesn’t contain WHERE clause When the data size is less SELECT contains WHERE clause.column2.e.

Negative Side of an Index INDEX plays an important role in improving performance. A new row’s insertion will effect index and Oracle server implicitly updates index. But at the same time it may also degrade performance. FUNCTIONAL INDEX As of Oracle8i. because applications are not directly dependent on index. So this will put more burden on the machine if more number of indexes are created on a table. So. Removing an index doesn’t invalidate existing applications. if not designed carefully. we can create functional-based indexes. Having many indexes may have negative impact on the performance because whenever there is a change in the table.Siva Kumar HVK SELECT contains WHERE clause and WHERE clause uses indexed columns but indexed column is modified in the WHERE clause. information is placed in different ranges of indexes. we may store the information in any case. When we are storing alpha-numeric information. When we create index on such columns. we can convert them in to single case. SQL> CREATE INDEX IDX_NAME ON EMP(UPPER(ENAME)). but at the same time not having an index may effects performance. immediately index is to reflect that change. Dropping an Index SYNTAX DROP INDEX <INDEXNAME>. 185 . before creating index.

compute. A materialized view provides access to table data by storing the results of a query in a separate schema object. A materialized view log is located in the master database in the same schema as the master table. which does not take up any storage space or contain any data. ENAME FROM EMP. Example ROWID ROWNUM SYADATE NEXTVAL CURRVAL NULL LEVEL Are called as Pseudo-columns. Oracle Database creates one internal table and at least one index. Without a materialized view log.ENAME. ENAME.SAL FROM (SELECT EMPNO. and may create one view. TO DISPLAY 3 HIGHEST PAID EMPLOYEES SQL> SELECT ROWNUM. Oracle Database uses these objects to maintain the materialized view data. This process is called incremental or fast refresh. You must have the privileges necessary to create these objects. all in the schema of the materialized view. Oracle Database stores rows describing those changes in the materialized view log and then uses the materialized view log to refresh materialized views based on the master table.Siva Kumar HVK PSEUDO COLUMN A pseudo-column is a column that yields a value when selected but which is not an actual column of the table. Materialized Views: Materialized views are schema objects that can be used to summarize. SELECT ROWNUM. Usually. When you create a materialized view. EMPNO. Materialized View Log: When DML changes are made to master table data.EMPNO. A master table can have only one materialized view log defined on 186 . a fast refresh takes less time than a complete refresh. This process is called a complete refresh. Unlike an ordinary view. a materialized view contains the rows resulting from a query against one or more base tables or views. Oracle Database must re-execute the materialized view query to refresh the materialized view. and distribute data.SAL FROM EMP ORDER BY SAL DESC) WHERE ROWNUM <= 3. replicate.

Syntax: <USING INDEX | USING NO INDEX> Follow the Steps: 187 . Oracle Database can use this materialized view log to perform fast refreshes for all fast-refreshable materialized views based on the master table. Complete Clause The complete refresh re-creates the entire materialized view. NOCACHE specifies that the blocks are placed at the least recently used end of the LRU list. The default index is used to speed up incremental (FAST) refresh of the materialized view. COMPLETE. BUILD: Specifies when to populate the materialized view. or FORCE). You should create a materialized view log for the master tables if you specify the REFRESH FAST clause. This attribute is useful for small lookup tables. If you request a complete refresh. FORCE is the default. USING INDEX If USING INDEX is not specified. Oracle performs a complete refresh even if a fast refresh is possible. If you do not specify a refresh method (FAST. Syntax: <CACHE | NOCACHE> REFRESH MODES FAST Clause The FAST refreshes use the materialized view logs (as seen above) to send the rows that have changed from master tables to the materialized view. CACHE specifies that the blocks retrieved for this table are placed at the most recently used end of the least recently used (LRU) list in the buffer cache when a full table scan is performed. then default tablespace values are used. To fast refresh a materialized join view. Syntax: CREATE MATERIALIZED VIEW <[schema. Oracle performs a fast refresh if possible. Specify IMMEDIATE to indicate that the materialized view is to be populated immediately. you must create a materialized view log for each of the tables referenced by the materialized view.]name> [LOGGING] [CACHE] [TABLESPACE <tablespace_name>] BUILD IMMEDIATE [REFRESH <FAST | FORCE | COMPLETE>] [ON <COMMIT | DEMAND>] [<USING INDEX | USING NO INDEX>] [START WITH <date> NEXT <date_calculation>] [FOR UPDATE] [STORAGE CLAUSE] AS (<SQL statement>). otherwise complete refresh. Force Clause When you specify a FORCE clause.Siva Kumar HVK it. CACHE: For data that will be accessed frequently.

Create a force materialized view as follows: create materialized view emp_2mv build immediate refresh force on demand with primary key as select * from emp_2. Select * from emp_2v. Without commit statement first check the normal view. 5. rowid. query from user_snapshots where regexp_like(name. Update the view as follows update emp_2 set mgr = 7788 where empno = 2345. Desc user_snapshots. Update any row and check for changes. now create a log on the table. 3. 7. '[eE][mM][pP][_]'). Try to create a materialized view as follows on the same table(cannot create a refresh FAST materialized view without creating log on the table). 188 . update emp_2 set mgr = 3456 where empno = 2345. it didn’t get updated the changes till the commit statement. Check the definition of materialized views in USER_SNAPSHOTS data dictionary table. Inference: As the materialized view definition is ON COMMIT. 8. 2. issue the select statement on materialized view too. select name. Create a normal view on emp_2. issue the COMMIT statement and check the emp_2mv. drop all the materialized view logs and views on the table emp_2. Observe the change. 9. create materialized view log on emp_2 with primary key. CREATE MATERIALIZED VIEW emp_2mv BUILD IMMEDIATE REFRESH FAST ON COMMIT AS SELECT * FROM emp_2. create or replace view emp_2v as select * from emp_2. Now. So. create materialized view log on emp_2 with primary key. 4. Now. Create materialized view log afresh with primary key.Siva Kumar HVK 1. Now repeat the 2nd step. Now. Find the difference that materialized view doesn’t updates the changes. Select * from emp_2mv. 6.

02am. Now.01. execute dbms_mview. 189 . observe the changes in materialized view. create materialized view emp_2mv refresh complete start with sysdate next sysdate+1/24*60*30 as select * from emp_2. Below is the example which refreshes the materialized view data every day at night 12. Use DBMS_MVIEW. We can automate the process of refreshing materialized view at some time in a day or weekly. There would not be any changes.REFRESH built-in package to refresh the materialized view.Siva Kumar HVK select * from emp_2mv.refresh(‘emp_2mv’).

Siva Kumar HVK Exercise 1) Display the string SATYAM in the format S A T Y A M 2) Display only even rows from the table 3) Display one year calendar 4) Display how many a’s are there in the given string 5) Remove duplicate rows from the given table Empno ename 1 x 2 y 3 z 1 x 3 z 6) Find out how many columns are there in a given table(Use the data dictionary table USER_TAB_COLUMNS) Course : Oracle 190 .

Siva Kumar HVK Day Session Duration : : : 5 2 2 Hrs Topics Advanced Queries Analytical Queries Presentation 191 .

6 1 855945.6 1 855945. In the example. percentiles.68 9 129461.6 4 641959. see the ranks between 1 and 4. There is a gap between ranks. SAL FROM EMP.32 6 184563. Oracle has embedded analytical functions in SQL statement to cater to most of the requirements of data mining.---------1 855945.88 10 111807.24 7 153802. For example.6 11 66870.Siva Kumar HVK ANALYTICAL QUERIES Analytical functions are used mainly for the analysis of data as required by decision-making managers.2 5 196867. and n-tiles of the values in a result set. These functions are listed below Ranking For calculating ranks. DENSE_RANK 192 . to find out top three salaried employees SQL> SELECT RANK() OVER(ORDER BY SAL DESC) DEFAULT_RANK. DEFAULT_RANK SAL -----------.91 ANALYSIS When different employees salary is same.77 12 10000 13 6810. they get the same rank.68 7 153802.

6 8 66870.68 6 129461.88 7 111807.---------1 855945.6 2 641959.24 5 153802. SQL> SELECT DENSE_RANK() OVER(ORDER BY SAL DESC) DEFAULT_RANK.Siva Kumar HVK The main difference between RANK () and DENSE_RANK () is that in the DENSE_RANK () there is no gap between ranks.6 1 855945.91 ROW_NUMBER 193 .6 1 855945. DEFAULT_RANK SAL -----------. SAL FROM EMP.68 5 153802.77 9 10000 10 6810.32 4 184563.2 3 196867.

91 2 2 10000 3 3 66870.6 194 .68 8 8 184563. ROW_NUMBER() OVER(ORDER BY SAL) RW_NUM.32 10 10 641959.---------1 1 6810.24 9 9 196867.SAL FROM EMP OUTPUT DEFAULT_RANK RW_NUM SAL -----------.77 4 4 111807.Siva Kumar HVK The function row number assigns unique rank to each row even if they are having the same value of order by expression. The rows will get the same rank if their order by expression has the same value.88 6 6 153802.6 5 5 129461.---------.2 11 11 855945.6 11 13 855945. INPUT SQL> SELECT RANK() OVER(ORDER BY SAL) DEFAULT_RANK.6 11 12 855945.68 6 7 153802.

if value matches. This is like a complement of the NVL function.'MANAGER') FROM EMP. OUTPUT ENAME --------------ss ss allen WARD JONES MARTIN BLAKE CLARK SCOTT TURNER ADAMS JAMES FORD phani JOB COMM NULLIF(JO --------.Siva Kumar HVK NULLIF FUNCTION This function produces NULL value if the expression has a specified value.5 SALESMAN SALESMAN 1244. NVL2 Function 195 .COMM. It produces NULL value if the expression has a specified value. NVL() substitute value.--------CLERK 1234 CLERK SALESMAN 746. Where as NULLIF produces NULL. INPUT SQL> SELECT ENAME.JOB.NULLIF(JOB.---------.16 SALESMAN MANAGER SALESMAN 3483.65 SALESMAN MANAGER MANAGER ANALYST ANALYST SALESMAN 0 SALESMAN CLERK CLERK CLERK CLERK ANALYST ANALYST se 20000 se ANALYSIS It is just opposite to NVL(). if its is NULL.

INPUT SQL> SELECT COMM.expr2.COMM.0) ---------. The expr1 can have any data type.0) FROM EMP.NVL2(COMM. OUTPUT COMM NVL2(COMM. The arguments expr2 and expr3 can have any datatype except LONG. Syntax NVL2(expr1. expr1 can never be returned.COMM. NVL2 returns expr2.----------------0 300 300 500 500 0 1400 1400 0 0 0 0 0 0 0 0 0 0 Coalesce Function This function takes n arguments and produces first argument. If expr1 is NULL . either expr2 or expr3 will be returned. which is having the first NOT NULL value.expr3) In NVL2. NVL2 returns expr3.Siva Kumar HVK It is an extended form of NVL. If expr1 is not NULL. 196 .

ENAME COMM --------------ss ss 1234 allen 746.65 BLAKE CLARK SCOTT TURNER 0 ADAMS JAMES FORD phani 20000 SAL DEPTNO MGR COAL ---------. Using this facility you Load data in multiple tables in single insert statement Load multiple rows in the same table in single insert statement Load data conditionally in the table. DEPTNO.24 30 7698 0 129461.88 111807.5 153802.68 30 7698 3483.---------6810. Multiple insert statement There are four types of multiple inert statements Unconditional insert statement Pivoting insert statement Conditional insert statement Insert first statement Unconditional Insert Statement 197 .16 20 7839 855945.---------.32 30 7698 746.65 855945.6 30 7839 855945.16 JONES 855945.6 10 7839 855945. MGR.2 20 7566 641959.68 30 7698 1244.Siva Kumar HVK SQL> SELECT ENAME. COMM.6 855945.6 153802.---------. SAL.6 30 7698 111807.88 20 7788 129461.6 641959.6 66870.77 20 7566 66870. MGR) COAL FROM EMP.91 20 7902 1234 196867.6 MARTIN 3483.77 10000 90 9822 20000 Multiple Insert and Merge statements Oracle 9i provides enhanced facility of loading data in the table using select statement. DEPTNO.5 WARD 1244. COALESCE (COMM.2 184563. SAL.

pname = s.deptno from emp 198 .ename.sal.pname and s.job.deptno We can load the data conditionally into three tables by using following statement SQL> insert all When deptno = 10 then Insert into table1 values(empno.cost) Select p.course.sal.job.ename.deptno).software s.job. Assume there are three tables with structure (table1.deptno). Conditional Insert statement It inserts the data into the table only when condition is satisfied. Select empno. When deptno = 20 then Insert into table2 values(empno.salary) Into example2 values(pname.course.course.sal.ename.pname. When deptno = 30 then Insert into table3 values(empno.sal.Siva Kumar HVK This statement enables to you insert data in multiple tables using a single insert statement.title. To understand this query consider the three tables from Annexure To insert the data into two tables Example1(pname.cost.salary) Example2(pname. studies st Where p.sal.cost) Insert all Into example1 values(pname.table2.title.pname = st.ename.ename.job.title.salary from programmer p.pname.table3) Empno.deptno).

deptno).ename. When deptno = 30 then Insert into values(empno.sal. table1 table2 table3 The difference between Insert First and Insert All is that in the formar at the most one row is inserted into the table while latter rows may be inserted into multiple tables.job.job.sal.deptno from emp. When deptno = 20 then Insert into values(empno.deptno).ename.sal.ename. Select empno.deptno). 199 .ename.job.Siva Kumar HVK Insert First statement Insert first When deptno = 10 then Insert into values(empno.sal.

A process or user instigates explicit locks.Siva Kumar HVK Course Day Session Duration : : : : Oracle 5 3 2 Hrs Topics Locking Mechanisms Object Privileges Security Synonyms Exercise Presentation LOCKING MECHANISMS To ensure data integrity oracle uses locks. Can be either table or row level. Oracle will lock any resource when it detects a valid attempt to update the resource. 200 . DML locks may be implicit or explicit. Locks are used to prevent destructive interaction between processes accessing the same resource. Dictionary locks are always implicit.used to protect data. Implicit locks are undertaken by Oracle. Oracle uses two locking types DML locks . Dictionary locks – used to protect the database structure Locks may be explicit or implicit.

Deletes and inserts use this lock mode. Updates. With this SELECT we lock all the rows in the result set for later update. The NOWAIT keyword specifies that we don’t want the statement to wait until. They are EXCLUSIVE(X) SHARE(S) ROW SHARE(RS) ROW EXCLUSIVE (RX) LOCK ALLOWS QUERIES BUT NOTHING ELSE Lock allows queries but not updates Lock allows concurrent process access to table. Locking using SELECT for UPDATE SELECT * FROM EMP WHERE EMPNO = 7521 FOR UPDATE OF SAL NOWAIT. Now from SCOTT user . If X wants to lock the EMP table. if he tries to the lock the table. Scott has given some privileges on EMP table to X user. then he has to issue a command LOCK TABLE SCOTT. It results an error LOCK TABLE EMP IN EXCLUSIVE MODE NOWAIT * ERROR at line 1: ORA-00054: resource busy and acquire with NOWAIT specified 201 . Resource may not be locked exclusively. The OF keyword prefixes the column identification area which specifies which columns are going to be updated by us at a later date. and current locks on the table are removed. Locks are held until either a transaction is committed / rolled back. Same as row share but no share mode locking. Assume that there are two users SCOTT AND X In the Scott user there is one table with the name EMP.Siva Kumar HVK There are five locking modes.EMP IN EXCLUSIVE MODE NOWAIT. The FOR UPDATE tells Oracle to lock each row as it processes it. which is already locked by X LOCK TABLE EMP IN EXCLUSIVE MODE.

procedure.INDEX. Object Privileges System privileges Object privilege An object privilege is a right to perform a particular operation on an object. Unless otherwise specified. System privilege A system privilege is a right to perform certain operation in the system. VIEW. PROCEDURE. Object Privileges User owns the object that he/she creates. An object is a table. EXECUTE. if user wants to share his object with other users. PACKAGE AND OBJECT TYPE 202 .INSERT. For example. But. sequence. The following are the list of object privileges available in Oracle ALTER. function or package.FUNCTION.. he has to grant privileges on the object to other users. view. such as TABLE. only the owner and DBA can access the object. SEQUENCE. or to execute a particular type of SQL command such as CREATE TABLE.SELECT. the privilege to create a table is a system privilege.UPDATE DELETE These privileges are given on various objects. view etc. Privileges are classified into two categories depending upon what type of right they give to the user.Siva Kumar HVK SECURITY What is a privilege A privilege is a right to access an object such as a table.

-. Note :. he can select as well as update the information in EMP table.to grant privilege to all the users of the Example GRANT SELECT. SELECT * FROM SCOTT. REVOKE OBJECT PRIVILEGES To remove the given privileges.UPDATE ON EMP TO X.EMP. we can use REVOKE command REVOKE <PRIVILEGES> ON <OBJECT> FROM <USER>. 203 .EMP EMPNO = 7521. X user can modify only sal value in the EMP table.any object privileges -. SET SAL = 11000 WHERE Restricting privilege to certain columns GRANT UPDATE(SAL) ON EMP TO X. UPDATE SCOTT.Siva Kumar HVK SYNTAX GRANT <PRIVILEGES> | ALL [(COLUMN1.to grant all privileges -. So.COLUMN2)] ON <OBJECT> Privileges ALL PUBLIC system.X is a user Now from X user.

Creating private synonym.Siva Kumar HVK Using Synonyms To simplify accessing tables owned by other users. create a SYNONYM.EMP. CREATE SYNONYM EMPL FOR SCOTT. By creating a synonym you can avoid giving the owner name while accessing table of other users. A synonym is another name(alias) to a table or view. Now we can access EMP table which is there in SCOTT user using synonym EMPL as SQL> SELECT * FROM EMPL. PUBLIC SYNONYM EMPL FOR 204 . where as public synonym is created by only DBA using a keyword called public.EMP. SQL>CREATE SCOTT. We can create two types of synonyms Private Synonyms Public Synonyms Any user can create private synonym. Public Synonym Public synonym is available for all the users.

SQL*Loader is fully described in the Oracle Server Utilities User’s Guide. If you need to transfer local data to a remote database on some recurring basis. and the control file contains information about the data -. etc. State Name. mainframes. If you already have the data in some other format. and the number of State Residents Who Drink Bottled Water.Siva Kumar HVK Course Day Session Duration : : : : Oracle 5 4 1 Hrs Topic SQL*Loader Presentation What is SQL*Loader? SQL*Loader is Oracle’s utility program for loading data into an Oracle table. At the end of this document. you might want to use SQL*Loader. Getting Started. Most often. for example. SQL*Loader has lots and lots of options which can be used to handle various types of data and levels of complexity. This document is just about getting started. You’ve got 50 rows of data – each containing the State Abbreviation. SQL*Loader runs on Unix. an Example Say. SQL*Loader takes two input files – a control file and a data file – and loads the data into a single Oracle table. This document is just about running it from a Windows PC. 205 . it may be worthwhile to use SQL*Loader. The data file contains data. what to do if something goes wrong. it may be preferable to use SQL*Loader rather than something like FTP. Why Use SQL*Loader From Your PC? If you need to transfer quite a lot of data from your machine to an Oracle database table. an [optional] unofficial State Slogan.where to load it. there is a brief comparison of FTP versus SQL*Loader. that you’ve got an Excel spreadsheet with State data already in it. and PC’s.

Rose Bowl CA. Using any text editor.5 hit of Champions like.mystates table. State_Name. State_Slogan. another 2) Create your control file. Oxygen?". So.0 Again!.Colorado. 206 .90203049 proud of Bill. There are.3000 WI.' OPTIONALLY ENCLOSED BY '"' TRAILING NULLCOLS (EMPNO.csv that contains data like this: AR.csv step will optionally and automatically enclose that data in double quotes. ENAME INTEGER EXTERNAL) The REPLACE keyword says.California. the Save AS *.." There's also an INSERT [into empty table] and APPEND [to existing rows] option. In addition.Wisconsin. if any of the data elements already contain a comma.csv' REPLACE INTO TABLE EMPL FIELDS TERMINATED BY '. This will automatically put commas between each of the four data elements. you might have a file named C:\MyStates. The remote table is called sp.csv input file.ctl) containing these lines: LOADDATA INFILE 'C:\EMPLOYEE.Colorado has no state slogan. "remove any existing rows before starting the load. it was not necessary to further describe them – character is the default. Notice there is some missing data in the data file -.) Here’s what you do: 1) Create your data file. lots of available options described in the Utilities User’s Guide. Because the first three items are of character datatype.Arkansas."Dude? You want. The fourth column is numeric data – it totals the number of state residents who drink bottled water. This is easy.Siva Kumar HVK (Is 50 rows of data really sufficient to justify this exercise? That’s debatable. The INTEGER EXTERNAL describes the datatype in the C:\mystates. State_Abbrev. The TRAILING NULLCOLS statement handles the missing data. after your Save AS command. it tells SQL*Loader to load any missing data as NULL values. but let’s say you’ve thought it over and you DO want to SQL*load your data into a 4-column Oracle table at UW-Stevens Point. create a file (say.csv) file. as we said earlier. Save your Excel spreadsheet data AS a Comma-Separated-Variable (*. C:\mystates.We are sure CO.mystates. and Nbr_Residents_WDBW are the actual column names defined in the sp.

it’s probably already there. This log file will contain information about how many rows were loaded. You must have the target database (say.Siva Kumar HVK 3) Create a table with the name referred in ctl file with required columns 4)Run Prerequisites: • SQL*Loader You must have SQL*Loader and SQL*Net installed on your machine. You can look for it in your ORAWIN95 or ORANT \BIN directory. you can get the Oracle Client Software installation CD and install "UTILITIES".exe. In the example below we assume that user SCOTT with password TIGER has appropriate authorization. 207 . or DELETE and INSERT if you're using the REPLACE option in the control file. execute SQL*Loader as follows: sqlldr scott/tiger@ELTP control=C:\mystates.exe or sqlldr80. look in the file C:\mystates. The SQL*Loader program may have a version number included as part of its name. This is pretty standard stuff. Or maybe it will be just sqlldr. If it's not installed.ctl When the load completes.ora file.mystates table (INSERT. • • At an MS-DOS prompt (or the Start. and other information that may be useful to reassure or debug. how many rows -. You must have authorization to modify the sp.exe.were NOT loaded. something like sqlldr73. it’s called ‘ELTP’) configured as SQL*Net service in your local tnsnames.if any -.log. Run menu) .

save them individually using a different file name for each. 5. and then exit Microsoft Excel. On the File menu. click the Microsoft Office Button. d. Edit the CSV File in Microsoft Word 1. 3. 2. 4. 2.csv may contain features that are incompatible with CSV (comma delimited). Note In Word 2007. Note You may be prompted to save the file again. type a name for your CSV file (for example. Address. and then click Open. click CSV (Comma delimited) (*. you can click Yes. Click OK when you receive the following message: The selected file type does not support workbooks that contain multiple sheets.csv). In the Files of type box. In the Save as type box. click Options. When you are prompted. click Close. Then save a copy in the latest Excel format. On the Tools menu. click Help. • To save only the active sheet. and then click Save. Click the CSV file that you saved in step 4 of the "Edit the Excel Worksheet" section. Do you want to keep the workbook in this format? • To keep this format. Note In Excel 2007. and then click Open. or select a file type that supports multiple sheets. In the Save As dialog box: a. click Yes. click Save As. 3.*). In the File name box. and then click Save As. Click Yes when you receive the following message: Address. Start Microsoft Word. Microsoft Word). click All Files (*. b. Note In Word 2007. click OK. click Open. skip this step.csv). Note In Excel 2007. and then exit Excel. which leaves out any incompatible features. the Excel worksheet contains the following address information: A B 1 2 3 ravi kris babu 1. On the File menu. • To preserve the features. click the Microsoft Office Button. • To see what might be lost.Siva Kumar HVK How to convert Excel Sheet into CSV(Comma separated variable) file This article describes how to convert a single column of addresses in a Microsoft Excel worksheet into a comma-separated value (CSV) file that you can import into another program (for example. 208 . c. • To save all sheets. repeat steps c and d. On the File menu. click No. Note For the address example in this article. and then click Exit Excel. click the Microsoft Office Button. click Close.

click to select the All check box. Note In Word 2007.Siva Kumar HVK On the View tab. and then click OK. 209 . and then click Word Options. Click Paragraph marks under the Always show these formatting marks on the screen. Click Display. c. follow these steps: a. b. Click the Microsoft Office Button.

we can query our data from a point in time before we or any other users made permanent changes to it.--------------. of course. and EXECUTE privilege on DBMS_FLASHBACK. Oracle will create as many or as few as are required to satisfy our transaction workloads. undo_tablespace=[undo tablespace name] (set in pfile/spfile). This parameter specifies the number of seconds that Oracle should retain undo data for us. within system limits. we know these segments as "undo segments" and under automatic management. table_name. Sample data For our sample data we will create a test table and copy a few rows and columns of ALL_TABLES as follows. From 9i. we require the following system elements: • • • • undo_management=auto (set in pfile/spfile). SQL> SELECT * FROM t. either by SCN (System Change Number) or by timestamp. whereby Oracle manages our rollback segments for us. tablespace_name 4 FROM all_tables 5 WHERE ROWNUM <= 5. SQL> CREATE TABLE temp 2 AS 3 SELECT owner.Siva Kumar HVK Flashback Query Flashback query in oracle 9i Release 1 Flashback query is a new feature of Oracle 9i. In other words.-------------------SYS SEG$ SYSTEM SYS CLU$ SYSTEM SYS OBJ$ SYSTEM SYS FILE$ SYSTEM 210 . undo_retention=n (set in pfile/spfile. OWNER TABLE_NAME TABLESPACE_NAME --------------. Requirements To be able to use flashback query. where n is a positive number of seconds). it enables us to query our data as it existed in a previous state. Flashback query enables us to query the undo segments directly. This is. these being the size of the undo tablespace and a new parameter named undo_retention. Table created. Flashback query works in tandem with another new feature of Oracle 9i. FLASHBACK or FLASHBACK ANY system privilege. automatic undo management (AUM).

For finer grain control of Flashback. You can use Flashback to restore deleted e-mail by re-inserting the deleted message into the current message box. You can use PL/SQL cursors opened before disabling Flashback to perform DML. This is different from two phase commit(2PC) and the ability to rollback a change. The flashback is session based and can restore to an SCN that is passed as an argument.Siva Kumar HVK SYS COL$ SYSTEM 5 rows selected. Under Automatic Undo Management (AUM) mode. Packaged applications such as e-mail and voicemail. the system retains enough undo information to regenerate the older versions of the data. An SCN identifies the exact version of the database. DML and DDL operations and distributed operations are not allowed while a session is running in Flashback mode. Different concurrent sessions (connections) in the database can perform Flashback to different wall-clock times or SCNs. When enabling Flashback using a wall-clock time. you can use retention control to control how far back in time to go for the version of the database you need. SCNs allow recovery to a specific change. SCN (System Change Number) is an oracle internal numbering scheme that identifies changes to the database. If you need to perform a Flashback over a 24-hour period. you can recover the deleted rows. DBMS_FLASHBACK can be used within logon triggers to enable Flashback without changing the application code. If you accidentally delete rows from a table. you can enable an SCN. SYSDATE will not be affected. as each SCN is unique and acts as an identifier for point-in-time recovery PL/SQL cursors opened in Flashback mode return rows as of the flashback time or SCN. You can perform data analysis or data modeling to track seasonal demand. In a Flashback-enabled session. since flashback can happen even if a commit has been done. You may want to use DBMS_FLASHBACK for the following reasons: • • • Self-service repair. 211 . This way. Decision support system (DSS) and online analytical processing (OLAP) applications. the database chooses an SCN that was generated within five minutes of the time specified. the DBA should set the undo retention parameter to 24 hours. it will continue to provide the current time. DBMS_FLASHBACK Package The DBMS_FLASHBACK package provides the ability to restore specific data according to an SCN(System Change Number) captured by a snapshot.

PL/SQL procedure successfully completed. before we changed the TABLESPACE_NAME to lower-case).Siva Kumar HVK SQL> SELECT DBMS_FLASHBACK. post-update form. SQL> COMMIT. We can now see the data in its current.-------------------SYS SEG$ SYSTEM SYS CLU$ SYSTEM SYS OBJ$ SYSTEM SYS FILE$ SYSTEM SYS COL$ SYSTEM 5 rows selected. SQL> SELECT * FROM temp.--------------.GET_SYSTEM_CHANGE_NUMBER AS scn 2 FROM dual. OWNER TABLE_NAME TABLESPACE_NAME --------------. 5 rows updated. SQL>exec DBMS_FLASHBACK. Commit complete. To leave "flashback query mode".ENABLE_AT_SYSTEM_CHANGE_NUMBER(5929 67). SQL> UPDATE temp SET tablespace_name = LOWER(tablespace_name). Now we can enable flashback query to the point in time before we changed our data (i. SQL> SELECT * FROM temp.-------------------SYS SEG$ system SYS CLU$ system SYS OBJ$ system SYS FILE$ system SYS COL$ system 5 rows selected. we must disable it using DBMS_FLASHBACK as follows.e. Once in "flashback query mode". SCN ---------592967 1 row selected. We can now see our data in its original state (i. OWNER TABLE_NAME TABLESPACE_NAME --------------.--------------. any queries we run will return data consistent with the SCN we enabled. 212 .e. using the earlier SCN). We can see this below.

Note: ALTER SESSION is simply a convenience to enable a consistent timestamp format mask without having to supply it explicitly. it is very useful. SQL> SELECT LOCALTIMESTAMP 2 FROM dual. such as data recovery. Oracle suggests that it is feasible to build flashback query capabilities into our applications. We might view this as a somewhat ambitious claim for the technology. In 9. SQL> UPDATE temp SET table_name = LOWER(table_name). Flashback Query in 9i release 2: AS OF [scn|timestamp] Oracle 9i Release 2 makes flashback query significantly easier by building the capability into the SQL FROM clause itself.DISABLE. it is invoked directly by this syntax. There are a number of uses for this feature. Furthermore using the Flashback Query. SQL> ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'DD-MONYYYY HH24:MI:SS. we'll use a timestamp (another new feature of Oracle 9i) instead of an SCN. SQL> SELECT * FROM temp. this is restricted to the period specified by undo_retention (with some variance depending on transaction loads).--------------.2. OWNER TABLE_NAME TABLESPACE_NAME --------------.750 1 row selected. PL/SQL procedure successfully completed.FF3'. In fact. but of course.-------------------SYS SEG$ system SYS CLU$ system SYS OBJ$ system SYS FILE$ system SYS COL$ system 5 rows selected. Flashback query does not need to be explicitly enabled and disabled via package calls. Session altered. LOCALTIMESTAMP -----------------------22-NOV-2002 21:31:01. adhoc change-tracking or point-in-time queries.Siva Kumar HVK SQL> exec DBMS_FLASHBACK. 213 . but as a short-term recovery mechanism. we can query our data AS OF TIMESTAMP or AS OF SCN directly.

but only once every five minutes.Siva Kumar HVK 5 rows updated. This makes flashback queries with timestamps subject to precision errors.750'). SQL> SELECT * 2 FROM temp AS OF TIMESTAMP TO_TIMESTAMP('22-NOV-2002 21:31:01.--------------. however. This is much easier! The extended FROM clause is simple and intuitive to use and is more likely to encourage developers to use flashback query. Using an SCN. We can see the effect of this in our 9. we can be more precise with our flashback query.--------------.-------------------SYS SEG$ SYSTEM SYS CLU$ SYSTEM SYS OBJ$ SYSTEM SYS FILE$ SYSTEM SYS COL$ SYSTEM 5 rows selected. We will take a guess that the SCN after our 9. A particularly good use for this is for resetting test data during development and unit-testing. SQL> COMMIT. SQL> SELECT * FROM temp.0 example update will be a few greater than before we began (there is no other activity on 214 . Commit complete.2 flashback query results above. It is also a good short-term recovery tool for rectifying minor mistakes. OWNER TABLE_NAME TABLESPACE_NAME --------------. OWNER TABLE_NAME TABLESPACE_NAME --------------.-------------------SYS seg$ system SYS clu$ system SYS obj$ system SYS file$ system SYS col$ system 5 rows selected.0 example. This tells us that the SCN that Oracle mapped to our timestamp is from a time before we ran the 9. Now we can invoke flashback query as of the timestamp prior to our update. flashback query timestamps are mapped to SCNs. A note on flashback precision As noted earlier. Our flashback query correctly returns the original upper-case TABLE_NAME data but it also returns the original upper-case TABLESPACE_NAME data also.

OWNER TABLE_NAME TABLESPACE_NAME --------------. Using this. we can either update the table from the flashback query source or we can delete the current data and insert the flashback data in much easier way. Using the SCN enabled us to be far more precise with our flashback query. lower-case TABLESPACE_NAME).-------------------SYS SEG$ system SYS CLU$ system SYS OBJ$ system SYS FILE$ system SYS COL$ system 5 rows selected.-------------------SYS SEG$ system SYS CLU$ system SYS OBJ$ system SYS FILE$ system SYS COL$ system 5 rows selected. 5 rows created. SQL> COMMIT. 215 .Siva Kumar HVK this test system). SQL> SELECT * FROM t AS OF SCN 592969. we will try a 9. Commit complete.2). OWNER TABLE_NAME TABLESPACE_NAME --------------.0 example) but before the second update (9.2 flashback query AS OF SCN. SQL> SELECT * FROM t. In the example below. Recovering data Using the AS OF syntax. 5 rows deleted. We can now see the data as it existed after the first update (9. SQL> INSERT INTO temp 2 SELECT * FROM temp AS OF SCN 592969.--------------.0 examples (i. we'll remove the current data and replace it with the data as it existed after our 9.e.--------------. SQL> DELETE FROM temp.

'Joe Johnson'. this simplicity of flashback query in 9i Release 2 makes this complex variant largely redundant. The sequence would be: enable flashback -> open flashback cursor -> disable flashback -> open current cursor -> fetch and compare data. 500000. Using the Flashback feature. 250000. this would only be possible in PL/SQL. user cannot perform DML or DDL operations. SYS cannot enable Flashback mode. In the 9i Release 1 variant of flashback query. 'Susie Tiger'. /* keep_scn is a temporary table to store scns that we are interested in. hiredate date). 8180 8181 DBMS_FLASHBACK Example The following example illustrates how Flashback can be used when the deletion of a senior employee triggers the deletion of all the personnel reporting to him. DBMS_FLASHBACK Error Messages Error 8182 8184 8183 8185 Description In Flashback mode. User cannot enable Flashback within an uncommitted transaction. '13-dec90'). execute dbms_flashback. null. employee_mgr number(5)constraint mgr_fkey references employee on delete cascade. /* Populate the company with employees */ insert into employee values (1. 10. Time specified is too old. insert into employee values (10. you can recover and re-insert the missing employees. */ create table keep_scn (scn number). User cannot enable Flashback within another Flashback session. 'John Doe'. 1. If we need to search for changes to specific columns. As stated throughout this article. User cannot begin read only or serializable transactions in Flashback mode. set echo on create table employee (employee_no number(5) primary key.Siva Kumar HVK Data changes between current and flashback data can be identified quite simply by set queries using MINUS/UNION. '12-aug84'). '5-jul-81'). 1000000. salary number. we can join the current and flashback datasets together (we can also use the 9i FULL OUTER JOIN for this purpose). employee_name varchar2(20). insert into employee values (20. 216 .disable. Invalid system change number specified.

begin select scn into restore_scn from keep_scn. 100000. 100000. insert into employee values (310. insert into employee values (220. 100. insert into keep_scn values (I). '3-feb-86'). /* Show the entire org */ select lpad(' '. commit. 2*(level-1)) || employee_name Name from employee connect by prior employee_no = employee_mgr start with employee_no = 1 order by level. dbms_flashback. 200000. /* Scott decides to retire but the transaction is done incorrectly */ delete from employee where employee_name = 'Scott Tiger'. 'Bob Smith'. / /* Show Scott's org */ select lpad(' '. '4-nov96'). '22mar-88'). begin I := dbms_flashback. 'Gary Smith'. execute dbms_flashback. insert into employee values (210.enable_at_system_change_number (restore_scn). /* notice that all of scott's employees are gone */ select lpad(' '.get_system_change_number. 'Scott Tiger'. /* Store this snapshot for later access through Flashback */ declare I number. 2*(level-1)) || employee_name Name from employee connect by prior employee_no = employee_mgr start with employee_no = 1 order by level. 'Jane Johnson'. 2*(level-1)) || employee_name Name from employee connect by prior employee_no = employee_mgr 217 . commit. 210. 75000. 'Charles Smith'. insert into employee values (300.Siva Kumar HVK insert into employee values (100. 'Nancy Doe'. 150000. 100. 100. commit. 210. /* Put back scott's organization */ declare restore_scn date. 65000. '18-sep93'). '3-may95').disable. 20. end. insert into employee values (200. '11apr-87').

employee_mgr. */ dbms_flashback.disable. 218 . employee_name. for c1_rec in c1 loop if (c1_rec. scotts_mgr number. c1_rec. employee_mgr into scotts_emp. */ open c1. */ fetch c1 into c1_rec. hiredate from employee connect by prior employee_no = employee_mgr start with employee_no = (select employee_no from employee where employee_name = 'Scott Tiger'). /* Open c1 with Flashback enabled. loop /* Note that all the DML operations inside the loop are performed with Flashback disabled. declare scotts_emp number. salary. /* Disable Flashback. cursor c1 is select employee_no. begin select employee_no.employee_no. scotts_mgr from employee where employee_name = 'Scott Tiger'. c1_rec is c1 % ROWTYPE.Siva Kumar HVK start with employee_no = (select employee_no from employee where employee_name = 'Scott Tiger') order by level. exit when c1%NOTFOUND.employee_name.employee_mgr = scotts_emp) then insert into employee values (c1_rec.

c1_rec.ENABLE_AT_TIME ( query_time IN TIMESTAMP).hiredate). end loop.employee_name. 219 . c1_rec. end if. / execute dbms_flashback. c1_rec.Siva Kumar HVK scotts_mgr.employee_no. end.hiredate). c1_rec. Syntax DBMS_FLASHBACK.salary. c1_rec.employee_mgr.salary. else if (c1_rec. end if.employee_no != scotts_emp) then insert into employee values (c1_rec. DBMS_FLASHBACK Subprograms ENABLE_AT_TIME Procedure This procedure enables Flashback for the entire session. The snapshot time is set to the SCN that most closely matches the time specified in query_time. c1_rec. disable.

ENABLE_AT_SYSTEM_CHANGE_NUMBER Procedure This procedure takes an SCN as an input parameter and sets the session snapshot to the specified number. it defaults to the beginning of the day.M. Using the TO_TIMESTAMP function: Example: execute dbms_flashback. The format depends on the NLS settings. Use the NLS format and supply a string. 2001. Syntax DBMS_FLASHBACK. 'DDMM-YYYY HH24:MI:SS')). If the time is omitted from query time. all queries return data consistent as of the specified wall-clock time or SCN. the time zone information is truncated.enable_at_time(TIMESTAMP '2001-01-09 12:31:00'). 220 . You provide the format you want to use. a version number for the database that is incremented on every transaction commit. Note that if the query time contains a time zone. In the Flashback mode. 12:00 A.ENABLE_AT_SYSTEM_CHANGE ( query_scn IN NUMBER). that is.enable_at_time(TO_TIMESTAMP('12-02-2001 14:35:00'. Parameters Parameter query_scn Description The system change number (SCN). 2:35 PM. This example shows the TO_TIMESTAMP function for February 12. A time stamp can be specified in the following ways: Using the TIMESTAMP constructor: Example: execute dbms_flashback.Siva Kumar HVK Parameters Parameter Description query_time This is an input parameter of type TIMESTAMP.

DISABLE Procedure This procedure disables the Flashback mode for the entire session. Syntax DBMS_FLASHBACK. Syntax DBMS_FLASHBACK. This helps you store specific snapshots.disable. Example The following example queries the salary of an employee.enable_at_time('30-AUG-2000').DISABLE. SELECT salary from emp where name = 'Joe' EXECUTE dbms_flashback. You can obtain the current change number and stash it away for later use. 2000: EXECUTE dbms_flashback. on August 30.GET_SYSTEM_CHANGE_NUMBER ( RETURN NUMBER). Joe. 221 .Siva Kumar HVK GET_SYSTEM_CHANGE_NUMBER Function This function returns the current SCN as an Oracle number datatype.

2) NUMBER(7.Siva Kumar HVK ANNEXURE Table : Studies NAME (PNAME) SPLACE COURSE NULL NOT NULL NOT NULL NOT NULL TYPE VARCHAR2(20) VARCHAR2(20) VARCHAR2(20) NAME STUDIED PLACE COURSE STUDIED TABLE : SOFTWARE NAME (PNAME) TITLE DEV_IN SCOST DCOST SOLD NULL ? NOT NULL NOT NULL NOT NULL TYPE VARCHAR2(20) VARCHAR2(20) VARCHAR2(10) NUMBER(7.2) NUMBER(4) NAME DEVELOPED PROJECT NAME LANGUAGE DEVELOPED SOFTWARE COST DEVELOPMENT COST NO OF SOFTWARE SOLD Data in Table : STUDIES PNAME ANAND ALTAF JULIANA KAMALA MARY NELSON PATRICK QADIR RAMESH REBECCA REMITHA REVATHI VIJAYA SPLACE SABHARI COIT BITS PRAGATHI SABHARI PRAGATHI SABHARI APPLE SABHARI BPILLANI BDPS SABHARI BDPS COURSE PGDCA DCA MCA DCP PGDCA DAP DCA HDCP PGDCA DCA DCS DAP DCA COST 45000 7200 22000 5000 4600 6200 5200 14000 4500 11000 6000 5000 48000 222 .

S/W CODE GENERATION READ ME BOMBS AWAY VACCINES HOTEL MANAGEMENT DEAD LEE PC UTILITIES TSR HELP PACKAGE HOSPITAL MANAGEMENT QUIZ MASTER ISR EDITION DEV_IN BASIC PASCAL COBOL DBASE ORACLE COBOL C++ ASSEMBLY C DBASE PASCAL C ASSEMBLY PASCAL BASIC C SCOST DCOST SOLD 399 7500 3000 9000 18000 4500 300 750 1900 12000 599 725 2500 1100 3200 900 6000 16000 3500 20000 85000 20000 1200 5000 3400 3500 4500 5000 6000 75000 2100 700 43 9 0 7 4 23 84 11 21 4 73 51 6 2 15 6 Data in Table : PROGRAMMER PNAME DOB DOJ S E X M M F F F M M M M F F F F PROF1 PROF2 SALARY ANAND ALTAF JULIANA KAMALA MARY NELSON PATRICK QADIR RAMESH REBECCA REMITHA REVATHI VIJAYA 21-APR-66 02-JUL-64 31-JAN-68 30-OCT-68 24-JUN-70 11-SEP-85 10-NOV-65 31-AUG-65 03-MAY-67 01-JAN-67 19-APR-70 02-DEC-69 14-DEC-65 21-APR-92 13-NOV-90 21-APR-90 02-JAN-92 01-FEB-91 11-OCT-89 21-APR-90 21-APR-91 28-FEB-91 01-DEC-90 20-APR-93 02-JAN-92 02-MAY-92 PASCAL CLIPPER COBOL C C++ COBOL PASCAL ASSEMBLY PASCAL BASIC C PASCAL FOXPRO BASIC COBOL DBASE DBASE ORACLE DBASE CLIPPER C DBASE COBOL ASSEMBLY BASIC C 3200 2800 3000 2900 4500 2500 2800 3000 3200 2500 3600 3700 3500 223 .Siva Kumar HVK TABLE : SOFTWARE PNAME ANAND ANAND JULIANA KAMALA MARY PATRICK QADIR QADIR QADIR RAMESH RAMESH REMITHA REMITHA REVATHI REVATHI VIJAYA TITLE PARACHUTES VIDEO TITLING PACK INVENTORY CONTROL PAYROLL PACKAGE FINANCIAL ACC.

Siva Kumar HVK QUERY – I Find out the selling cost average for packages developed in pascal. Find out the number of copies which should be sold in order to recover the development cost of each package. Display the details of packages for which development cost have been recovered. which have not been sold so far? Find out the cost of the software developed by Mary? Display the institute names from the studies table without the duplicates How many different courses are mentioned in the studies table? Display the names of the programmers whose names contain 2 occurrences of the letter ‘A’ 224 . COBOL or Pascal Display the details of those who will be completing 2 years of services this year? Calculate the amount to be recovered for those packages whose development cost has not yet been recovered? List the packages. in descending order. Display the names and ages of all the programmers Display the names of those who have done the DAP course What is the highest number of copies sold by a package Display the names and date of birth of all programmers born in January Display the lowest course fee How many programmers have done the PGDCA course How much revenue has been earned through sale of packages developed in C Display the software’s developed by Ramesh How many programmers studied at Sabhari? Display the details of the packages whose sales crossed 2000 mark. Who are the programmers who celebrate their birthday’s during the current month? How many female programmers are there? What are the languages known by the male programmers What is the average salary How many people draw 2000 to 4000? Display the details of those who don’t know Clipper. What is the price of the costliest software developed in BASIC How many packages were developed in DBASE? How many programmers studied at Pragathi? How many programmers paid 5000 to 10000 for their course? What is the average course fee? Display the details of programmers knowing C How many programmers know either COBOL or PASCAL? How many programmers don’t know PASCAL and C? How old is the oldest male programmer? What is the average age of female programmers? Calculate the experience in years for each programmer and display along with the names.

costliest package and cheapest packages developed by him / her. dcost and difference between scost and dcost in descending order of difference Display the names of the packages whose names contain more than 1 word Display the name. lowest and average salaries for those earning more than 2000 225 . average cost per course Display each Institute name with number of students Display the names of male and female programmers Display the programmer’s name and their packages Display the number of packages in each language except C and C++ Display the number of packages in each language for which development cost is less than 1000 Display the average difference between SCOST and DCOST for each language Display the total SCOST. DCOST and amount to be recovered for each programmer for those whose dcost has not yet been recovered Display the highest. dob. average selling cost and average price per copy Display each programmer’s name. scost.sex.Siva Kumar HVK Display the names of the programmers whose names contains 5 characters How many female programmers knowing COBOL have more than 2 yrs experience What is the length of the shortest name in the programmer table What is the average development cost of a package developed in COBOL Display the name. Display each institute name with number of courses . doj of those month of birth and month of joining are same QUERY – II Display the cost of the package developed by each programmer Display the sales values of the packages developed by the each programmer Display the number of packages sold by each programmer Display the sales cost of the packages developed by each programmer Display each language name with average development cost. dob(dd/mm/yy format) . DOJ(dd/mm/yy format) for all the programmers What is the amount paid in salaries of the male programmers who don’t know COBOL Display the title .

How many packages developed by female programmers earning more than the highest paid male programmer How many packages were developed by the most experienced programmer from BDPS 226 .000 How many packages were developed by the person who developed the cheapest package . ORACLE OR DBASE Which programmer has developed highest no of packages Who are the male programmers earning below the average salary of female programmers Display the details of those who are drawing salary Display the details of the software developed by the male programmers earning more than 3000 Display the details of the software developed in C by female programmers of Pragathi How many months it will take for each programmer to recover their cost of study Display the details of the software developed in the language which is not the programmers first proficiency Display the details of the software developed in the language which is neither the first nor second proficiency of the programmer Who are the programmers who joined in the same day Display the programmers who are drawing same salary Which is the costliest package developed by a person with under 3 years experience What is the average salary for those whose software sales value is more than 50.Siva Kumar HVK QUERY – III Who is the most experienced programmer knowing pascal? Which course has been done by the most of the students? Which course has the lowest selling cost? Display the courses whose fees are within 1000/. Where did he / she study.( + or .C++.does not know C.) of the average fee Who developed the package that has sold the least number of copies Which language was used to develop most number of packages Display the names of the packages which have been sold less than the average number of copies Who is the youngest male programmer born in 1965 In which year most number of programmers born Which female programmer earning more than 3000/.

IV Write a query to display the last name. or why not? Write a query to display the last names of the employees who earn less than the average salary in their departments. Sort the results on salary from highest to lowest. and department name for all employees Create a unique listing of all jobs that are in department 80.Siva Kumar HVK QUERY . and department name for all employees who work in Toronto. and salary of any employee whose department number and salary both match the department number and salary of any employee who earns a commission. location ID. job. department name. department number. department number. hire date. Can this be done by using the NOT IN operator? How. and salary for all employees who have the same salary and commission as Kochhar. a. Create a query to display the last name. Find all employees who are not supervisors. department number. department name. Note: Do not display Kochhar in the result set. Create a query to display the employees who earn a salary that is higher than the salary of all of the sales managers (JOB_ID = 'SA_MAN'). Display the employee last name and department name for all employees who have an a (lowercase) in their last names Write a query to display the last name. First do this using the NOT EXISTS operator b. Write a query to display the last names of the employees who have one or more coworkers in their departments with later hire dates but higher salaries. Write a query to display the employee last name. Include the location of the department in the output. Write a query to display the department names of those departments whose total salary cost is above one eighth (1/8) of the total salary cost of the whole company Write a query to display the last name. and city of all employees who earn a commission. 227 . Display the last name. and salary of any employee whose salary and commission match the salary and commission of any employee located in location ID 1700.

department numbers. Give each column an appropriate label.Siva Kumar HVK display all employees including King. and grade for all employees. Write a query to display the following for those employees whose manager ID is less than 120: • Manager ID • Job ID and total salary for every job ID for employees who report to the same manager • Total salary of those managers • Total salary of those managers. job. Order the results by the employee number. and all the employees who work in the same department as a given employee. Create a query that displays employee last names. Create a query that displays the name. irrespective of the job IDs 228 . salary. Create a query to display the name and hire date of any employee hired after employee Davies. department name. who has no manager. Show the structure of the JOB_GRADES table.

manager FROM employee. position. join Difference.e. which capabilities of a SELECT statement are performed? 1. Question: 2 You need to produce a report for mailing labels for all customers. DEPARTMENT d WHERE e. cust_address FROM customers. 2.e. 4. 2. 3. name. projection. 5. 4. cust_name. manager FROM employee. projection. join Difference. SELECT id. cust_phone FROM customers. phone FROM customers. Question: 3 Evaluate this SQL statement: SELECT e. position. address FROM customers. 4.Siva Kumar HVK OCA SAMPLE QUESTIONS Question: 1 Which SELECT statement should you use if you want to display unique combinations of the POSITION and MANAGER values from the EMPLOYEE table? 1. join Selection.DEPARTMENT_ID. The mailing label must have only the customer name and address. SELECT cust_id. DISTINCT manager FROM employee. join Intersection. SELECT name. 3. The CUSTOMERS table has these columns: CUST_ID CUST_NAME CUST_ADDRESS CUST_PHONE NUMBER(4) NOT NULL VARCHAR2(100) VARCHAR2(150) VARCHAR2(20) Which SELECT statement accomplishes this task? 1.DEPARTMENT_ID = d. SELECT cust_name.. manager DISTINCT FROM employee. 2. projection. 5. SELECT* FROM customers.EMPLOYEE_ID. d. Selection. 3.DEPARTMENT_ID. cust_address. FROM EMP e. In the statement.LAST_NAME. projection. SELECT SELECT SELECT SELECT DISTINCT position. intersection. position. address.DEPARTMENT_NAME. product 229 .

4. city FROM manufacturer AND manufacturer_id = 'NF10032' ORDER BY city. The The The The The The sort is in ascending by order by default. ORDER BY clause is executed on the client side. manufacturer m WHERE p. Updating 2.city FROM product p. Inserting 5.manufacturer_id = 'NF10032'. m. m. Deleting 4. Viewing 3. 2. manufacturer_id FROM product WHERE manufacturer_id = 'NF10032'. SELECT id_number. You use this statement to retrieve data from a data table for __________.manufacturer_id AND m. Question: 5 From SQL*Plus. and join when executed? 1. 1. 3.manufacturer_id = m. 6. 230 . manufacturer_id FROM product ORDER BY manufacturer_id. a selection. ORDER BY clause comes last in the SELECT statement.Siva Kumar HVK Question: 4 Which two statements are true regarding the ORDER BY clause? 1. 5. 4. ORDER BY clause is executed first in the query execution. Truncating Question: 6 Which SQL SELECT statement performs a projection. sort is in descending order by default. 3. you issue this SELECT statement: SELECT * From orders. 2.manufacturer_id.id_number. SELECT id_number. ORDER BY clause must precede the WHERE clause. SELECT p. SELECT manufacturer_id. id_number.

Siva Kumar HVK Question: 7 The CUSTOMERS table has these columns: CUSTOMER_ID NUMBER(4) NOT NULL CUSTOMER_NAME VARCHAR2(100) NOT NULL STREET_ADDRESS VARCHAR2(150) CITY_ADDRESS VARCHAR2(50) STATE_ADDRESS VARCHAR2(50) PROVINCE_ADDRESS VARCHAR2(50) COUNTRY_ADDRESS VARCHAR2(50) POSTAL_CODE VARCHAR2(12) CUSTOMER_PHONE VARCHAR2(20) Which statement finds the rows in the CUSTOMERS table that do not have a postal code? 1. customer_name FROM customers WHERE postal_code = '________'. 4. The two statements produce identical results. SELECT customer_id. salary. 3. hire_date FROM EMPLOYEES ORDER BY salary DESC. 5. SELECT customer_id. customer_name FROM customers WHERE postal_code IS NULL. SELECT customer_id. SELECT last_name. customer_name FROM customers WHERE postal_code CONTAINS NULL. customer_name FROM customers WHERE postal code IS NVL. Question: 8 Evaluate these two SQL statements: SELECT last_name. 231 . hire_date FROM EMPLOYEES ORDER BY 2 DESC. salary . 2. SELECT customer_id. What is true about them? 1. customer_name FROM customers WHERE postal_code = NULL. SELECT customer_id.

employee_id "Emp_id". 4. The DESCRIBE DEPT statement displays the structure of the DEPT table. m. m. The two statements can be made to produce identical results by adding a column alias for the salary column in the second SQL statement. e. 3. 2. 4.emp_name "Manager" 232 . The second statement returns a syntax error. Question: 9 Evaluate the set of SQL statements: CREATE TABLE dept (deptno NUMBER(2). ROLLBACK. The ROLLBACK statement frees the storage space occupies by the DEPT table.salary. EMPLOYEES (EMPLOYEE_ID is the primary key.employee_id "Mgr_id". DESCRIBE DEPT What is true about the set? 1. e.emp_name "Employee". Question: 10 Examine the data of the EMPLOYEES table.Siva Kumar HVK 2.. The DESCRIBE DEPT statement displays the structure of the DEPT table only if the COMMIT statement introduced before the ROLLBACK statement. MGR_ID is the ID of managers and refers to the EMPLOYEE_ID) EMPLOYEE_ID EMP_NAME 101 Smith 102 Martin 103 Chris 104 John 105 Diana 106 Bryan 108 Jennifer 110 Bob 120 Ravi DEPT_ID 20 10 20 30 30 40 30 40 20 MGR_ID 120 105 120 108 108 110 110 110 JOB_ID SA_REP CLERK IT_ADMIN HR_CLERK HR_MGR AD_ASST HR_DIR EX_DIR SA_DIR SALARY 4000 2500 4200 2500 5000 3000 6500 8000 6500 Evaluate this SQL statement: SELECT e. dname VARCNAR2(14). There is no need to specify DESC because the results are sorted in descending order by default. The DESCRIBE DEPT statement returns an error ORA-04043: object DEPT does not exist. 3. loc VARCNAR2(13)).

salary > 4000.------------.-------------110 Bob 8000 Bob 120 Ravi 6500 110 Ravi 108 Jennifer 6500 110 Jennifer 103 Chris 4200 120 Chris 105 Diana 5000 108 Diana Manager 2.--------.---------. EMP_id EMPLOYEE SALARY Mgr_id ------.employee_id AND e. EMP_id EMPLOYEE SALARY Mgr_id ------.-------------110 Bob 8000 110 Bob 120 Ravi 6500 120 Ravi 108 Jennifer 6500 108 Jennifer 103 Chris 4200 103 Chris 105 Diana 5000 105 Dina 5.------------. What is its output? 1.mgr_id = m.------------.---------.-------------110 Bob 800 120 Ravi 6500 110 Bob 108 Jennifer 6500 110 Bob 103 Chris 4200 120 Ravi 105 Diana 5000 108 Jennifer D EMP_id EMPLOYEE SALARY Mgr_id ------.--------.--------.-------------120 Ravi 6500 110 Bob 108 Jennifer 6500 110 Bob 103 Chris 4200 120 Ravi 105 Diana 500 108 Jennifer Manager 3. employees m WHERE e.------------.---------.---------. EMP_id EMPLOYEE SALARY Mgr_id ------.Siva Kumar HVK FROM employees e. Manager Manager 233 .--------. The SQL statement produces an error.

Enables you to specify alternated out for NULL column values. Nullifies the value of the column out put. 4. This feature cannot be implemented through /SQL*Plus. Replacement variables 3. Which of the following statement correctly describes how to specify a column alias? 1. Assists in the distribution of output across multiple columns. Instead-of variables 5. Question: 14 You want to use SQL*Plus to connect to the oracle database. The NVL function accomplishes which of the following tasks? 1. 2. 3. Place the alias after each column separated by a space to describe the column. Place the alias after each column separated by a comma to describe the column. 2. Enables you to specify alternate output for non-NULL column values. 234 . Substitution variables 2. 2. Which of the following choices does not indicate a component you must specify when logging into the oracle? 1.Siva Kumar HVK Question: 11 Which /SQL*Plus feature can be used to replace values in the WHERE clause? 1. database name. Prompt variables 4. Question: 13 You want to use a function in you column clause of a SQL statement. The The The The SQL*Plus Keyword. Question: 12 You are formulating queries in a SQL*Plus. 3. Place the alias at the end of the statement to describe the table. Place the alias at the beginning of the statement to describe the table. 3. 4. username password. 4.

SELECT employee_id||' . 235 . SELECT employee_id||' . 1996. You need to create a report to display all former employees that were hired on or after January 1. hire_date||' / '||depart_date "Term of Employment" FROM employee_history WHERE hire_date > '31-DEC-95' AND depart_date <> NULL. hire_date||' / '||depart_date 'Term of Employment' FROM employee_history WHERE hire_date > '31-DEC-95' AND depart_date > NULL. The data should display in this format: Former Employee Term of Employment ---------------------------. hire_date||' / '||depart_date "Term of Employment" FROM employee_history WHERE hire_date > '31-DEC-95' AND depart_date IS NOT NULL.'||last_name "Former Employee". 2.'||last_name "AS Former Employee". hire_date||' / '||depart_date AS Term of Employment FROM employee_history WHERE hire_date > '31-DEC-95'. SELECT employee_id||' .SMITH 10-MAY-92 / 01-JUN-01 Which SELECT statement could you use? 1. hire_date||' / '||depart_date "AS Term of Employment" FROM employee_history WHERE hire_date > '31-DEC-95'. SELECT employee_id||' .Siva Kumar HVK Question: 15 The EMPLOYEE_HISTORY table contains these columns: EMPLOYEE_ID NUMBER LAST_NAME VARCHAR2(25) FIRST_NAME VARCHAR2(25) DEPARTMENT_ID NUMBER POSITION VARCHAR2(30) SALARY NUMBER(6. 3.2) HIRE_DATE DATE DEPART_DATE DATE The EMPLOYEE_HISTORY table contains only former employees.---------------------------------14837 .'||last_name "Former Employee". 4. SELECT employee_id||' . 5.'||last_name 'Former Employee'.'||last_name AS Former Employee.

employee_id AND e.salary. SELECT e.emp_name "Manager" FROM employees e. e. SELECT employee_id "Emp_id". employee_id "Mgr_id".mgr_id = m.emp_name "Employee". MGR_ID is the ID of managers and refers to the EMPLOYEE_ID) EMPLOYEE_ID 101 102 103 104 105 106 108 110 120 EMP_NAME Smith Martin Chris John Diana Bryan Jennifer Bob Ravi DEPT_ID 20 10 20 30 30 40 30 40 20 MGR_ID 120 105 120 108 108 110 110 110 JOB_ID SA_REP CLERK IT_ADMIN HR_CLERK HR_MGR AD_ASST HR_DIR EX_DIR SA_DIR SALARY 4000 2500 4200 2500 5000 3000 6500 8000 6500 Which statement lists the ID. m.emp_name "Manager" FROM employees e. m. 2. m. name. and salary of the employee.salary > 4000. and the ID and name of the employee's manager. SELECT e.'||Ename||'.emp_name "Employee". 236 . employees m WHERE e.employee_id "Mgr_id". e. for all the employees who have a manager and earn more than 4000? 1.employee_id "Mgr_id". EMPLOYEES (EMPLOYEE_ID is the primary key. e.'||Job "Employee Information" FROM employee. emp_name "Manager" FROM employees WHERE salary > 4000.Siva Kumar HVK Question: 16 The EMPloyee table contains these columns: Empno Number(4) Ename Varchar2(10) job Varchar2(10) sal Varchar2(10) You need to display the employees information by using this query. m.mgr_id = m. A) 1 B) 2 C) 3 D) 0 E) 4 Question: 17 Examine the data of the EMPLOYEES table. 3. e. employees m WHERE e.employee_id "Emp_id". salary.salary.employee_id "Emp_id".salary > 4000.mgr_id AND e. How many columns are presented after executing this query: SELECT Empno||'. emp_name "Employee".

o. m.order_amount. You want to rank the top three sales representatives who have sold the maximum number of products.product_name FROM customer c. m. Use the table aliases instead of the table names in the WHERE clause.salary > 4000. o.emp_name "Employee". m.order_id. 237 . e.Siva Kumar HVK 4. SELECT e. SELECT last_name FROM EMP WHERE last name LIKE ‘*A%’ Question: 19 In which scenario would TOP N analysis be the best solution? 1. Question: 18 You need to display the last names of those employees who have the letter “A” as the second character in their names. 3. You want to identify the person who makes the highest salary for all employees.employee_id "Emp_id".emp_name "Manager" FROM employees e.salary. SELECT e.order_date. You want to identify the most senior employee in the company. 4. 5.customer_id. 2.employee_id AND e. p.product_id = p. e.mgr_id "Mgr_id".salary.employee_id "Emp_id". Use the table name in the ORDER BY clause. e. SELECT last_name FROM EMP WHERE last name =’*A%’ 3. This statement fails when executed. 4. 3.mgr_id = m. product p WHERE customer. Question: 20 Evaluate this SQL statement: SELECT c. SELECT last_name FROM EMP WHERE last_name LIKE ‘_A%’.emp_name "manager" FROM employees e. Which SQL statement displays the required results? 1. employees m WHERE e..emp_name "Employee".product_id ORDER BY o. 2.mgr_id "Mgr_id". Include the ORDER_AMOUNT column in the SELECT list.customer_id AND o. e. You want to find the manager supervising the largest number of employees.customer_id = curr_order.salary > 4000. employees m WHERE e.employee_id AND e. SELECT last_name FROM EMP WHERE last name =’_A%’. m. curr_order o. 2. Remove the table aliases from the WHERE clause.employee_id = m. 5. Remove the table alias from the ORDER BY clause and use only the column name. 4. Which change will correct the problem? 1.

Question: 22 For which task would you use the WHERE clause in a SELECT statement? 1. Price is less then $500 or greater than $900 You want to sort the results by their data of purchase. semester_end. 4. SELECT student_id.900) AND purchase_date < ’21-JAN-2001’ ORDER BY purchase date ASC. to display only unique PRODUCT_ID values 4. Which statement accomplishes this? 1. Purchased before January 21. gpa 238 . SELECT book_title FROM books WHERE price IN (500. 2. 2001 2. starting with the most recently bought book. to designate the ORDER table location 2. Which statement should you use? 1. to compare PRODUCT_ID values to 7382 3. SELECT book_title FROM books WHERE price between 500 and 900 AND purchase_date < ’21-JAN-2001’ ORDER BY purchase_date. SELECT book_title FROM books WHERE price < 500 or > 900 AND purchase_date < ’21-JAN-2001’ ORDER BY purchase date DESC. 3. to restrict the rows returned by a GROUP BY clause Question: 23 The STUDENT_GRADES table has these columns: STUDENT_ID NUMBER(12) SEMESTER_END DATE GPA NUMBER(4.Siva Kumar HVK Question: 21 You want to display the titles of books that meet these criteria: 1.3) The registrar has requested a report listing the students' grade point averages (GPA). starting from the earliest date. SELECT book_title FROM books WHERE (price < 500 OR price > 900) AND purchase_date < ’21-JAN-2001’ ORDER BY purchase date DESC. sorted from highest grade point average to lowest within each semester.

semester_end ASC. SELECT student_id. gpa FROM student_grades ORDER BY gpa DESC. 3. gpa FROM student_grades ORDER BY semester_end ASC. SELECT student_id. 4. semester_end DESC.00 and 2000. the order total. gpa DESC.2) The ORDERS table tracks the Order nnmher. SELECT customer_id. SELECT customer_id. 2. and the customer to whom the Order belongs.. 4. order_total FROM orders RANGE ON order_total (100 AND 2000) INCLUSIVE. order_id. gpa ASC. SELECT student_id. SELECT customer_id. order_total FROM orders WHERE order_total BETWEEN 100 and 2000. SELECT student_id. semester_end. Question: 24 The ORDERS table has these columns: ORDER_ID NUMBER(4) NOT NULL CUSTOMER_ID NUMBER(12) NOT NULL ORDER_TOTAL NUMBER(10. semester_end. SELECT customer_id. Question: 25 Examine the structure of the PRODUCT table. order_total FROM orders WHERE order_total >= 100 and <= 2000. SELECT customer_id. semester_end. order_id. Which two statements retrieve orders with an inclusive total that ranges between 100. 2. order_total FROM orders HAVING order_total BETWEEN 100 and 2000.00 dollars? 1. order_id. order_id. order_id. PRODUCT Table PRODUCT _ID NUMBER Primary Key PRODUCT_NAME VARCHAR2(25) 239 . semester_end. 5. 3. 5.Siva Kumar HVK FROM student_grades ORDER BY semester_end DESC. gpa DESC. gpa FROM student_grades ORDER BY semester_end. order_total FROM orders WHERE order_total >= 100 and order_total <= 2000. gpa FROM student_grades ORDER BY gpa DESC.

Mary Elizabeth HST_RELIG 240 . SELECT product_id FROM product WHERE qty_per_unit >= 500 SORT BY supplier_id. SELECT product_id FROM product WHERE qty_per_unit >= 500 ORDER BY supplier_id. SELECT product_id FROM product WHERE qty_per_unit >= 500 ORDER BY supplier_id. Karen HST_REVOL Hopewell.------------------Jones. 4. ID LAST_NAME FIRST_NAME SUBJECT_ID 88 Tsu Ming HST_AMER 70 Smith Ellen HST_INDIA 56 Jones Karen HST_REVOL 58 Hann Jeff HST_CURR 63 Hopewell Mary Elizabetn HST_RELIG Which query should you use to return the following values from the TEACHER table? Name Subject ------------------------------------. then by product number from lowest to highest. You want the product numbers displayed alphabetically by supplier. product_id. 3.2) COST NUMBER (5. product_id DESC. SELECT product_id FROM product WHERE qty_per_unit > 500 SORT BY supplier_id. Question: 26 Examine the data in TEACHER table. 2.Siva Kumar HVK SUPPLIER_ID CATERORY_ID QTY_PER_UNIT NUMBER references SUPPLIER(SUPPLIER_ID) NUMBER NUMBER LIST_RRICE NUMBER (5.2) You want to display all product identification numbers of products for which there are 500 or more available for immediate sale. product_id. Which statement should you use to achieve the required results? 1. product_id.

subject_id "Subject" FROM teacher WHERE subject_id LIKE '%HST\_R%' ESC '\ '. '||first_name "Name". SELECT last_name||'. 3. '||first_name "Name". SELECT last_name||'. subject_id "Subject" FROM teacher WHERE subject_id LIKE 'HST\_%' ESCAPE '\'. 2.Siva Kumar HVK 1. 3. 241 . marks. ROWNUM "Rank" FROM students WHERE ROWNUM <= 10 AND finish_date BETWEEN '01-JAN-99' AND '31-DEC-99' AND course_id = 'INT_SQL' ORDER BY marks DESC. subject_id "Subject" FROM teacher WHERE subject_id = 'HST\_R%'. 600) AND bonus BETWEEN 250 AND 500). SELECT last_name||'. 500. SELECT student_ id. 4. Which SQL statement accomplishes this task? 1. 2. '||first_name "Name". 4. '||first_name "Name". Question: 27 You query the database with this SQL statement: SELECT bonus FROM salary WHERE bonus BETWEEN 1 AND 250 OR (bonus IN(190. SELECT last_name||'. Which value could the statement return? 1. 100 260 400 600 Question: 28 Examine the structure of the STUDENTS table: STUDENT_ID NUMBER Primary Key STUDENT_NAME VARCHAR2(30) COURSE_ID VARCHAR2(10) NOT NULL MARKS NUMBER START_DATE DATE FINISH_DATE DATE You need to create a report of the 10 students who achieved the highest ranking in the course INT SQL and who completed the course in the year 1999. subject_id "Subject" FROM teacher WHERE subject_id LIKE 'HST_%'.

product_id. ROWNUM "Rank” FROM (SELECT student_id. marks. SELECT student_id. SELECT order_id. SELECT student_id. LINE_ITEM_ID NUMBER(9). ROWID "Rank" FROM students WHERE ROWID <= 10 AND finish_date BETWEEN '01-JAN-99' AND '31-DEC-99' AND course_id = 'INT_SQL' ORDER BY marks.Siva Kumar HVK 2. quantity DESC. ORDER_ID). and quantity of each item where the quantity ranges from 10 through 100. Constraint primary key (LINE_ITEM_ID. quantity FROM line_item WHERE quantity BETWEEN 9 AND 101 AND order_id BETWEEN 1500 AND 1575 ORDER BY order_id DESC. The order numbers must be in the range of 1500 through 1575. marks FROM students WHERE ROWNUM <= 10 AND finish_date BETWEEN '01-JAN-99' AND '31-DEC-99' AND course_id = 'INT_SQL' ORDER BY marks DESC). 4. line_item_id. 3. ORDER_ID NUMBER(9) NOT NULL. ROWNUM "Rank" FROM (SELECT student_id. marks FROM students ORDER BY marks DESC) WHERE ROWNUM <= 10 AND finish_date BETWEEN '01-JAN-99' AND '31-DEC-99' AND course_id = 'INT_SQL'. marks. PRODUCT_ID NUMBER(9) NOT_NULL. Constraint foreign key PRODUCT_ID REFERENCES PRODUCT(PRODUCT_ID)). 242 . Which statement should you use to display the desired result? 1. QUANTITY NUMBER(9). line item number. The results must be sorted by order number from lowest to highest and then further sorted by quantity from highest to lowest. product identification number. marks. SELECT student_id. Question: 29 Examine the structure of the LINE_ITEM table. You must display the order number. Constraint foreign key ORDER_ID REFERENCES CURR_ORDER(ORDER_ID).

cost) * . SELECT cost.(cost * . 3. Question: 30 The ITEM table contains these columns: ITEM_ID NUMBER(9) COST NUMBER(7.cost) .((retail . retail.2) RETAIL NUMBER(7. retail .25 "Profit" FROM item WHERE item_id = 783920. SELECT order_id. SELECT order_id. quantity. product_id. quantity FROM line_item WHERE (quantity > 9 OR quantity < 101) AND order_id BETWEEN 1500 AND 1575 ORDER BY order_id. and then deduct an administrative fee of 25 percent of this derived value. and the profit for item number 783920. quantity DESC.retail . line_item_id. quantity FROM line_item WHERE quantity BETWEEN 10 AND 100 AND order_id BETWEEN 1500 AND 1575 ORDER BY order_id. To calculate the profit. line_item_id.25) "Profit" FROM item WHERE item_id = 783920.retail .cost) * . Which SELECT statement produces the desired results? 1. SELECT order_id. line_item_id.25) "Profit" FROM item WHERE item_id = 783920.Siva Kumar HVK 2.cost . 243 . quantity. product_id. retail.cost . the retail price. product_id. 2.cost * . retail. SELECT cost. 3. SELECT cost. (retail .retail .2) You need to create a report that displays the cost. (retail . SELECT cost. 4. (retail .25 "Profit" FROM item WHERE item_id = 783920. quantity FROM line_item WHERE (quantity > 10 AND quantity < 100) AND order_id BETWEEN 1500 AND 1575 ORDER BY order_id ASC. 4.cost) . subtract the cost of the item from its retail price. retail.

The SQL statement displays the desired results. (retail * 1. SELECT item_id. Question: 32 The EMP table contains these columns: LAST NAME VARCHAR2(25) SALARY NUMBER(6.2) DEPARTMENT_ID NUMBER(6) You need to display the employees who have not been assigned to any department.(cost * .10 "Calculated Profit" FROM item. What will be the result? 1.Siva Kumar HVK Question: 31 The ITEM table contains these columns: ITEM_ID NUMBER(9) COST NUMBER(7. 4. What is true about this SQL statement? 1. 2.10) AS Calculated Profit FROM item.10) . One of the statements will NOT execute.00 . 3.cost * . The operator in the WHERE clause should be changed to display the desired results. The column in the WHERE clause should be changed to display the desired results. 2. 4.00 . 2. 3.(cost * 1. retail * 1. 244 . You write the SELECT statement: SELECT LAST_NAME. SALARY. Statement 1 will display the 'Calculated Profit' column heading. Statement 1 will return a higher value than statement 2.2) The RETAIL and COST columns contain values greater than zero.25) + 5. The WHERE clause should be changed to use an outer join to display the desired results.25 + 5. DEPARTMENT_ID FROM EMP WHERE DEPARTMENT_ID = NULL. SELECT item_id.cost * 1.10 . Evaluate these two SQL statements: 1.2) RETAIL NUMBER(7. Statement 1 and statement 2 will return the same value.

The column you are sorting on contains NULL records. Which statement about this SELECT statement is true? 1. Evaluate this statement: SELECT account_id. 2. NVL(previous_balance.2) CREDIT_LIMIT NUMBER(7) You need to display the account number.2) NEW_PURCHASES NUMBER(7. 3. 3. A HAVING clause can be used to restrict both rows and groups.009)) . The statement calculates the finance charge incorrectly. 5. At the beginning of the list. 4. 6.2) PAYMENTS NUMBER(7. A WHERE clause CANNOT be used in a query of the query uses a HAVING clause. Question: 35 The ACCOUNT table contains these columns: ACCOUNT_ID NUMBER(12) PREVIOUS_BALANCE NUMBER(7. new purchases value. 2. 245 . 0) * . A WHERE clause can be used to restrict rows only. 2. At the same location they are listed in the unordered table. 0) + (NVL(previous_balance. The statement calculates the current balance incorrectly. finance charge. The statement returns only accounts that have NO previous balance. Adding the previous balance value. In the middle of the list. and current balance for accounts 1500 through 2000 with a current balance greater than the account's credit limit. and finance charge value. and then subtracting the payments value yields the current balance value. A WHERE clause can be used to restrict both rows and groups.009) NVL(payments.9 percent (. A HAVING clause can be used to restrict groups only. 4. where will the NULL record appears? 1. 3. A HAVING clause CANNOT be used in subqueries.Siva Kumar HVK Question: 33 Which two statements are true about WHERE and HAVING clauses? 1. Question: 34 You are sorting data in a table in you SELECT statement in descending order.009) of the previous balance.009 finance_charge.payments > credit_limit AND account_id BETWEEN 1500 AND 2000. NVL(new_purchases. 0) current balance FROM account WHERE (new_purchases + (previous_balance * 1. 0) * 1. The finance charge is . At the end of the list.

MAX(salary) FROM employees GROUP BY dept_id. 2. previous balance. 3.2) Which statement ensures that a value is displayed in the calculated columns for all employees? 1. SELECT dept_id. 4. 12*salary*commison_pct FROM emp. SELECT last_name. and payments values. 12*salary* (commission_pct. SELECT last_name. job_cat. SELECT last_name. MAX(salary) FROM employees WHERE salary > MAX(salary).0)) FROM emp. Question: 37 Management has asked you to calculate the value 12*salary* comossion_pct for all the employees in the EMP table. SELECT last_name. MAX(salary) FROM employees GROUP BY dept_id. MAX(salary) FROM employees GROUP BY dept_id. job_cat. 2. 4. 5.0)) FROM emp. The EMP table contains these columns: LAST NAME VARCNAR2(35) NOT NULL SALARY NUMBER(9. SELECT dept_id. job_cat. MAX(salary) FROM employees. 246 . SELECT dept_id.2) NOT NULL COMMISION_PCT NUMBER(4. 12*salary*(decode(commission_pct.0) FROM emp.2) Which statement shows the maximum salary paid in each job category of each department? 1. Question: 36 Examine the description of the EMPLOYEES table: EMP_ID NUMBER(4) NOT NULL LAST_NAME VARCHAR2(30) NOT NULL FIRST_NAME VARCHAR2(30) DEPT_ID NUMBER(2) JOB_CAT VARCHARD2(30) SALARY NUMBER(8. job_cat. job_cat. 3. job_cat. 12*salary*(nvl(commission_pct. The statement returns only accounts that have new purchases.Siva Kumar HVK 4. SELECT dept_id. salary. SELECT dept_id. job_cat.

EMPLOYEES. SELECT last_name. 2001". AVG(start_date) 3. a zero must be displayed against the calculated column. 4. 'FMDY. TO_CHAR(SYSDATE. TO_CHAR(SYSDATE.0) FROM (salary * 12) * NVL2(commission_pct. SELECT SELECT SELECT SELECT SELECT TO_DATE(SYSDATE. Question: 41 Evaluate the SQL statement: 247 . Which SELECT statement should you use? 1. YYYY') FROM dual. 5. AVG(start_date. SELECT last_name. end_date) 5. 0) FROM (salary * 12) * NVL(commission_pct. 'YYY') FROM dual. EMPLOYEES. Which SQL statement displays the desired results? 1. YYYY') FROM dual. 3. For records that have a NULL commission_pct. COUNT(start_date) 4. TO_CHAR(SYSDATE. DD Month.Siva Kumar HVK Question: 38 Examine the description of the STUDENTS table: STD_ID NUMBER(4) COURSE_ID VARCHARD2(10) START_DATE DATE END_DATE DATE. SUM(start_date) 2. 0) FROM Question: 40 You would like to display the system date in the format "Monday. 2. YYYY') FROM dual. 3. 2. DY Month. (salary * 12) * commission_pct FROM EMPLOYEES.2) You want to display the name and annual salary multiplied by the commission_pct for all employees. DDD Month. 01 June. 'FMDD. 'FMDY.2) COMMISSION_PCT NUMBER(5. 4. DDD Month. 'FMDay. (salary * 12) * IFNULL(commission_pct. Which two aggregate functions are valid on the START_DATE column? 1. DD Month. EMPLOYEES. 'FMDAY. MIN(start_date) 6. MAXIMUM(start_date) Question: 39 The EMPLOYEE tables has these columns: LAST_NAME VARCNAR2(35) SALARY NUMBER(8. SELECT last_name. SELECT last_name. YYYY') TO_DATE(SYSDATE.

000.999. 2. SELECT TO_CHAR (2000.10).Siva Kumar HVK SELECT ROUND(TRUNC(MOD(1600. ‘$9. SELECT TO_CHAR (2000. 1 3.NN ’) FROM dual. SELECT TO_CHAR (2000. SELECT TO_CHAR (2000.00’) FROM dual. 6. 4.2) FROM dual. The statement returns an error at the SELECT clause. ‘$0. SELECT TO_CHAR (2000.###. Examine this SELECT statement based on the MARKS table: SELECT subj1+subj2 total_marks. ‘$N.000. 0 2. 4.00’) FROM dual. An error statement Question: 42 Examine the description of the MARKS table: STD_ID NUMBER(4) STUDENT_NAME VARCHAR2(30) SUBJ1 NUMBER(3) SUBJ2 NUMBER(3) SUBJ1 and SUBJ2 indicate the marks obtained by a student in two subjects. 2. 3. What will be displayed? 1. The statement returns an error at the WHERE clause. 5. The statement executes successfully and returns the student ID and sum of all marks for each student who obtained more than the average mark in each subject.999.-1). 3. ‘$9. What is the result of the SELECT statement? 1.000. ‘$#. std_id FROM marks WHERE subj1 > AVG(subj1) AND subj2 > AVG(subj2) ORDER BY total marks. SELECT TO_CHAR (2000.##’) FROM dual.00 4.00”? 1. ‘$2.NNN. 248 . 0.00’) FROM dual.99’) FROM dual. The statement returns an error at the ORDER BY clause. Question: 43 Which three SELECT statements displays 2000 in the format “$2.

MAX(salary) FROM employees WHERE MIN(salary) < 5000 AND MAX(salary) > 15000. SELECT dept_id. SELECT dept_id. MAX(salary) FROM employees HAVING MIN(salary) < 5000 AND MAX(salary) > 15000. MIN(salary(. 249 . minimum salary. and maximum salary paid in that department. MIN(salary). MAX(salary) FROM employees GROUP BY dept_id HAVING MIN(salary) < 5000 AND MAX(salary) > 15000. SELECT dept_id. 2.2) Which statement shows the department ID. SELECT dept_id. MIN(salary). MAX(salary) FROM employees WHERE MIN(salary) < 5000 AND MAX(salary) > 15000 GROUP BY dept_id. SELECT dept_id. 4. DEPT_ID NUMBER(2) JOB_CAT VARCHAR2(30) SALARY NUMBER(8. 5. only of the minimum salary is less then 5000 and the maximum salary is more than 15000? 1. MIN(salary).Siva Kumar HVK Question: 44 Examine the description of the EMPLOYEES table: EMP_ID NUMBER(4) NOT NULL LAST_NAME VARCHAR2(30) NOT NULL FIRST_NAME VARCHAR2(30). MIN(salary). 3. salary HAVING MIN(salary) < 5000 AND MAX(salary) > 15000. MAX(salary) FROM employees GROUP BY dept_id.

You can pass column names. NVL compares two expressions and returns null if they are equal. You can use aggregate functions in any clause of a SELECT statement.Siva Kumar HVK Question: 45 Which two are true about aggregate functions? 1. expression. 6. only by grouping the whole table as one single group. 6. or the first expression of they are not equal. 3. NVL2 returns the first non-null expression in the expression list. TRIM trims the heading of trailing characters (or both) from a character string. 2. constants. 250 . You can use aggregate functions on a table. 4. 2. 5. expressions. 7. 4. or functions as parameters to an aggregate function. TRUNCATE rounds the column. DECODE translates an expression after comparing it to each search value. or value to n decimal places. You can use aggregate functions only in the column list of the SELECT clause and in the WHERE clause of a SELECT statement. NULLIF compares two expressions and returns null if they are equal. Question: 46 Which four statements correctly describe functions that are available in SQL? 1. 5. 3. INSTR returns the numeric position of a named character. You cannot group the rows of a table by more than one column while using aggregate functions. or the first expression if they are not equal. You can mix single row columns with aggregate functions in the column list of a SELECT statement by grouping on the single row columns.

admission a2 WHERE a.Siva Kumar HVK Question: 47 Examine the structures of the PATIENT. References PHYSICIAN_ID column of the PHYSICIA table ADMIT_DATE DATE DISCHG_DATE DATE ROOM_ID NUMBER Foreign key to ROOM_ID of the ROOM table Which SQL statement will produce a list of all patients who have more than one physician? 1.patient_id FROM admission a. 3.patient_id IN (SELECT patient_id FROM admission GROUP BY patient_id HAVING COUNT(*) > 1). SELECT patient_id FROM admission WHERE COUNT(physician_id) > 1.physician_id. SELECT p. 251 . 4. SELECT DISTINCT a. PHYSICIAN.patient_id = a2.patient_id FROM patient p WHERE p. 2. and ADMISSION tables. SELECT patient_id FROM patient FULL OUTER JOIN physician. Primary Key. References PATIENT_ID column of the PATIENT table PHYSICIAN_ID NUMBER NOT NULL. PATIENT Table PATIENT_ID NUMBER Primary Key LAST_NAME VARCHAR2 (30) FIRST_NAME VARCHAR2 (25) DOB DATE INS_CODE NUMBER PHYSICIAN Table PHYSICIAN _ID LAST_NAME FIRST_NAME LICENSE_NO HIRE_DTAE NUMBER Primary Key VARCHAR2 (30) NOT NULL VARCHAR2 (25) NOT NULL NUMBER (7) NOT NULL DATE ADMISSION Table PATIENT_ID NUMBER NOT NULL.patient_id AND a.physician_id <> a2. Primary Key.

Immediately after the SELECT clause 2. After the WHERE clause Question: 50 Which two are character manipulation functions? 1. HAVING 3. REPLACE 3. WHERE 2. After the ORDER BY clause 5. TRIM 2.Siva Kumar HVK Question: 48 Which clause should you use to exclude group results? 1. Before the WHERE clause 3. MOD 6. TRUNC 4. TO_DATE 5. Before the FROM clause 4. where is the GROUP BY clause placed in the SELECT statement? 1. GROUP BY 5. RESTRICT 4. ORDER BY Question: 49 In a SELECT statement that includes a WHERE clause. CASE 252 .

Sign up to vote on this title
UsefulNot useful