112
By: Gajendra Reddy. A Oracle: SQL Quick Reference

Oracle Quick Reference

Embed Size (px)

Citation preview

Page 1: Oracle Quick Reference

By:

Gajendra Reddy. A

Oracle: SQL Quick Reference

Page 2: Oracle Quick Reference

SQL Quick Reference 2

CONTENTS________________________________________________________

1. DATABASE CONCEPTS 5 What Is Data Base Data Base Management System Benefits of DBMS Relational Data Base Management System Dr.E.F.Codd Rules for RDBMS DBMSVs RDBMS Normalization

First Normal Form Second Normal Form Third Normal Form

Introduction to SQL

2. TABLES USED IN THIS BOOK 10

3. COMPONENTS OF SQL 11 Data definition language. Data Manipulation language. Data Query language. Data Control language. Transaction Control language.

4. SET OPERATIONS 17 Union all Union Intersect Minus The IN Function The EXISTS Function

5. SQL OPERATORS 19 Mathematical Logical Range

By A.G.Reddy

Page 3: Oracle Quick Reference

SQL Quick Reference 3

6. FUNCTIONS 21 Number functions Character function Date functions Conversion Functions Other Functions

7. PSEUDO COLUMNS 26 Level Row number Rowid User UID Sysdate Dual Table

8. AGGREGATE FUNCTIONS 27 Max Min Sum Avg Count

9. ANALYTICAL FUNCTIONS 29

10. GROUP BY, HAVING AND ORDER BY CLAUSES 31

11. INTEGRETY CONSTRAINTS 32 Primary Key Unique Key Foreign Key Not Null Check Default Enabling & Disabling Constraint Defining constraints via the alter table command Dropping constraints via the alter table command

By A.G.Reddy

Page 4: Oracle Quick Reference

SQL Quick Reference 4 12. PERFORMANCE TUNING 38

Views Indexes Sequences

13. MATERIALIZED VIEWS 44

14. JOINS 48 Cartesian product Self join Inner Join / Equi Join / Natural Join Cross Join Outer Join

Left Outer Join Right Outer Join Full Outer Join

15. SUB QUERIES 54

16 CASE EXPRESSIONS 56 Simple Case Statement Searched Case Statement NULL IF Function COALESCE Function

17. MISCELLANIOUS TOPICS 57 INSERT all statement Merge statement Creating a table from a table Inserting data into a table from another table The Cast Function

18. ORACLE 8i, 9i AND 10g FEATURES 60

19. IMPORTANT SQL QUERIES 62

20. FREQUENTLY ASKED QUESTIONS 68

21. USER DICTIONARY TABLES 70

1. DATABASE CONCEPTS

By A.G.Reddy

Page 5: Oracle Quick Reference

SQL Quick Reference 5

Data Base Management System:A database management system (DBMS), sometimes just called a database manager, is a

program that lets one or more computer users create and access data in a database. The DBMS manages user requests (and requests from other programs) so that users and other programs are free from having to understand where the data is physically located on storage media and, in a multi-user system, who else may also be accessing the data. In handling user requests, the DBMS ensures the integrity of the data (that is, making sure it continues to be accessible and is consistently organized as intended) and security (making sure only those with access privileges can access the data). The most typical DBMS is a relational database management system (RDBMS). A standard user and program interface is the Structured Query Language (SQL). A newer kind of DBMS is the object-oriented database management system (ODBMS).

Benefits of DBMS: Data is integrated Data duplication is reduced Data is program independent Data is easy to understand

Relational Data Base Management System:Relational database management system. A database management system with the ability

to access data organized in tabular files that can be related.

ACID Model:The ACID model is one of the oldest and most important concepts of database theory. It

sets forward four goals that every database management system must strive to achieve: atomicity, consistency, isolation and durability. No database that fails to meet any of these four goals can be considered reliable.

Let’s take a moment to examine each one of these characteristics in detail:

Atomicity states that database modifications must follow an “all or nothing” rule. Each transaction is said to be “atomic.” If one part of the transaction fails, the entire transaction fails. It is critical that the database management system maintain the atomic nature of transactions in spite of any DBMS, operating system or hardware failure.

Consistency states that only valid data will be written to the database. If, for some reason, a transaction is executed that violates the database’s consistency rules, the entire transaction will be rolled back and the database will be restored to a state consistent with those rules. On the other hand, if a transaction successfully executes, it will take the database from one state that is consistent with the rules to another state that is also consistent with the rules.

By A.G.Reddy

Page 6: Oracle Quick Reference

SQL Quick Reference 6 Isolation requires that multiple transactions occurring at the same time not impact each other’s execution. For example, if Joe issues a transaction against a database at the same time that Mary issues a different transaction; both transactions should operate on the database in an isolated manner. The database should either perform Joe’s entire transaction before executing Mary’s or vice-versa. This prevents Joe’s transaction from reading intermediate data produced as a side effect of part of Mary’s transaction that will not eventually be committed to the database. Note that the isolation property does not ensure which transaction will execute first, merely that they will not interfere with each other.

Durability ensures that any transaction committed to the database will not be lost. Durability is ensured through the use of database backups and transaction logs that facilitate the restoration of committed transactions in spite of any subsequent software or hardware failures.

Take a few minutes to review these characteristics and commit them to memory. If you spend any significant portion of your career working with databases, you’ll see them again and again. They provide the basic building blocks of any database transaction model.

The ACID properties of a DBMS allow safe sharing of data. Without these ACID properties, everyday occurrences such using computer systems to buy products would be difficult and the potential for inaccuracy would be huge. Imagine more than one person trying to buy the same size and color of a sweater at the same time -- a regular occurrence. The ACID properties make it possible for the merchant to keep these sweater purchasing transactions from overlapping each other -- saving the merchant from erroneous inventory and account balances.

Dr.E.F.Codd Rules for RDBMS:Let’s have a look at the 12 rules of Dr. Codd for RDBMS 

Rule 1: the Information Rule  All data should be presented to the user in table form. 

 Rule 2: Guaranteed Access Rule

All data should be accessible without ambiguity. This can be accomplished through a combination of the table name, primary key, and column name.  

Rule 3: Systematic Treatment of Null Values A field should be allowed to remain empty. This involves the support of a null value,

which is distinct from an empty string or a number with a value of zero. Of course, this can’t apply to primary keys. In addition, most database implementations support the concept of a nun- null field constraint that prevents null values in a specific table column.

 Rule 4: Dynamic On-Line Catalog Based on the Relational Model  A relational database must provide access to its structure through the same tools that are used to access the data. This is usually accomplished by storing the structure definition within special system tables. 

Rule 5: Comprehensive Data Sub-language Rule 

By A.G.Reddy

Page 7: Oracle Quick Reference

SQL Quick Reference 7 The database must support at least one clearly defined language that includes

functionality for data definition, data manipulation, data integrity, and database transaction control. All commercial relational databases use forms of the standard SQL (Structured Query Language) as their supported comprehensive language. 

 Rule 6: View Updating Rule 

Data can be presented to the user in different logical combinations, called views. Each view should support the same full range of data manipulation that direct-access to a table has available. In practice, providing update and delete access to logical views is difficult and is not fully supported by any current database.

  Rule 7: High-level Insert, Update, and Delete  

Data can be retrieved from a relational database in sets constructed of data from multiple rows and/or multiple tables. This rule states that insert, update, and delete operations should be supported for any retrievable set rather than just for a single row in a single table. 

 Rule 8: Physical Data Independence  

The user is isolated from the physical method of storing and retrieving information from the database. Changes can be made to the underlying architecture (hardware, disk storage methods) without affecting how the user accesses it. 

 Rule 9: Logical Data Independence  

How a user views data should not change when the logical structure (tables structure) of the database changes. This rule is particularly difficult to satisfy. Most databases rely on strong ties between the user view of the data and the actual structure of the underlying tables.  

Rule 10: Integrity Independence  The database language (like SQL) should support constraints on user input that maintain

database integrity. This rule is not fully implemented by most major vendors. At a minimum, all databases do preserve two constraints through SQL. No component of a primary key can have a null value. (see rule 3) If a foreign key is defined in one table, any value in it must exist as a primary key in another table.

  Rule 11: Distribution Independence  

A user should be totally unaware of whether or not the database is distributed (whether parts of the database exist in multiple locations). A variety of reasons make this rule difficult to implement; I will spend time addressing these reasons when we discuss distributed databases.

  Rule 12: Non-subversion Rule  

There should be no way to modify the database structure other than through the multiple row database language (like SQL). Most databases today support administrative tools that allow some direct manipulation of the data-structure

DBMS Vs RDBMS: By A.G.Reddy

Page 8: Oracle Quick Reference

SQL Quick Reference 8 It would be inappropriate to differentiate between DBMS & RDBMS. As RDBMS is

nothing different but a part of DBMS.

DBMS (Database Management System):- is the way you organize your data. Or how you store/process that.

RDBMS (Relational Database Management System):- is a classification under DBMS where you organize data in relational way.

NORMALIZATION:What is Normalization?

Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.

The Normal FormsThe database community has developed a series of guidelines for ensuring that databases

are normalized. These are referred to as normal forms and are numbered from one (the lowest form of normalization, referred to as first normal form or 1NF) through five (fifth normal form or 5NF). In practical applications, you'll often see 1NF, 2NF, and 3NF along with the occasional 4NF. Fifth normal form is very rarely seen and won't be discussed in this article.

Before we begin our discussion of the normal forms, it's important to point out that they are guidelines and guidelines only. Occasionally, it becomes necessary to stray from them to meet practical business requirements. However, when variations take place, it's extremely

Important to evaluate any possible ramifications they could have on your system and account for possible inconsistencies. That said, let's explore the normal forms.

First Normal Form (1NF):First normal form (1NF) sets the very basic rules for an organized database: Eliminate duplicative columns from the same table. Create separate tables for each group of related data and identify each row with a unique

column or set of columns (the primary key). Second Normal Form (2NF):

Second normal form (2NF) further addresses the concept of removing duplicative data: Meet all the requirements of the first normal form. Remove subsets of data that apply to multiple rows of a table and place them in separate

tables. Create relationships between these new tables and their predecessors through the use of

foreign keys.

Third Normal Form (3NF):

By A.G.Reddy

Page 9: Oracle Quick Reference

SQL Quick Reference 9 Third normal form (3NF) goes one large step further: Meet all the requirements of the second normal form. Remove columns that are not dependent upon the primary key.

Fourth Normal Form (4NF):Finally, fourth normal form (4NF) has one additional requirement: Meet all the requirements of the third normal form. A relation is in 4NF if it has no multi-valued dependencies.

Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database.

Introduction to SQL: SQL (usually pronounced as sequel) stands for structured query language. SQL is an ANSI (American National Standards Institute) standard computer language for

accessing and manipulating database systems. SQL statements are used to retrieve and update data in a database.

SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc.

Unfortunately, there are many different versions of the SQL language, but to be in compliance with the ANSI standard, they must support the same major keywords in a similar manner (such as SELECT, UPDATE, DELETE, INSERT, WHERE, and others).

Interactive Vs Embedded SQL: Interactive SQL is used to operate directly on database to produce output for

human consumption, in this you can enter a command now, and it is executed now, you can see the output immediately

Embedded SQL commands put inside of programs written in other language.

Operations we can do with SQL: Creation of Objects Insertion of data into tables Updating of existing data Deletion of data Retrieval of the data

DATABASE OBJECTS

Tables Stored Procedures

User Defined Functions

Triggers User Defined Data Types

Default And Check

Constraints

ViewsIndexes Columns Foreign Keys Primary Keys Variables

2. TABLES USED IN THIS BOOK By A.G.Reddy

Page 10: Oracle Quick Reference

SQL Quick Reference 10

SQL> select * from EMP;

EMPNO ENAME JOB SAL MGR COMM HIREDATE DEPTNO-----------------------------------------------------------------------------------------------------------------------------------------------7369 SMITH CLERK 900 7902 17-DEC-80 207499 LLEN SALESMAN 1600 7698 300 20-FEB-81 307521 WARD SALESMAN 1250 7698 500 22-FEB-81 307566 JONES MANAGER 2975 7839 02-APR-81 207654 MARTIN SALESMAN 1250 7698 1400 28-SEP-81 307698 BLAKE MANAGER 2850 7839 01-MAY-81 307782 CLERK MANAGER 2450 7839 09-JUN-81 107788 SCOTT ANALYST 4000 7566 19-APR-87 207839 KING PRESIDENT 5000 17-NOV-81 107844 TURNER SALESMAN 1500 7698 0 08-SEP-81 30 7876 DAMS CLERK 1100 7788 23-MAY-87 207900 JAMES CLERK 950 7698 03-DEC-81 307902 FORD ANALYST 4000 7566 03-DEC-81 207934 MILLER CLERK 1300 7782 23-JAN-82 10

SQL> select * from dept;

DEPTNO DNAME LOC---------- -------------------- ----------------------------------------- 10 ACCOUNTING NEW YORK 20 RESERCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON

3. COMPONENTS OF SQL By A.G.Reddy

Page 11: Oracle Quick Reference

SQL Quick Reference 11

DATA DEFINITION LANGUAGE:Set of SQL commands used to create, modify and delete database structure is called data definition language.

Create:This command is used to create a table. The syntaxes of this command are:

Creating a new table. CREATE TABLE emp (empno number,

ename varchar2 (15), job varchar2 (15), Sal number (5), mgr varchar2 (15), comm. Number, hiredate date, deptno number)

Creating a table from a table. CREATE TABLE myemp(name varchar2(10),sal number) AS SELECT

(ename,sal) FROM emp;

Alter:Table structure can be changed by using alter command. With this command Field type or property can be changed or a new field can be added. This sql alter table command is used like create table command. 

Please note that while changing the structure we must honor the existing constraints of the table. For example if you decide to change a field to UNIQUE so it will not accept any duplicate records then if some records with duplicate value are already there then system will not allow this and we will get error message. Same way we have to take care of other constraints.

Adding new columns: ALTER TABLE emp ADD (city varchar2(15));

Dropping a column from a table: ALTER TABLE emp DROP COLUMN city;

Modifying existing columns: ALTER TABLE emp MODIFY (city varchar2(30));

By A.G.Reddy

CreateAlterDropTruncate

DDL Commands

Page 12: Oracle Quick Reference

SQL Quick Reference 12

Renaming a column. ALTER TABLE emp RENAME COLUMN ename TO empname;

Adding constraints. ALTER TABLE emp ADD CONSTRAINT pk_ename PRIMARY KEY(ename);

Dropping constraints. ALTER TABLE emp DROP CONSTRAINT pk_empno ;

Restrictions on the ALTER TABLE: The following tasks can not be performed when using the ALTER TABLE command

Change the name of the table. Decrease the size of the column if table data exists.

Renaming tables: RENAME emp TO myemp:

Drop:The drop table command is used to delete a table and all rows in the table.

To delete an entire table including all of its rows, issue the drop table command followed by the table name. Drop table is different from deleting all of the records in the table. Deleting all of the records in the table leaves the table including column and constraint information. Dropping the table removes the table definition as well as all of its rows.

DROP TABLE emp;

Truncate:Removes all rows from a table without logging the individual row deletes.

TRUNCATE TABLE emp:

DATA MANIPULATION LANGUAGE:The Data Manipulation Language (DML) is used to insert, delete and modify database information. These commands will be used by all database users during the routine operation of the database.

Insert:This statement is used to insert a row of data in a table. All string values are enclosed using single quote. The syntax of this command is. By A.G.Reddy

InsertUpdateDelete

DML Commands

Page 13: Oracle Quick Reference

SQL Quick Reference 13

INSERT INTO emp (empno,ename,deptno) VALUES (1234,gajendra,30); INSERT INTO emp VALUES (1234,ravi,analyst,ramu,3000,10,’12-jan-83’,30); INSERT INTO emp VALUES

(&empno,’&ename’,’&job’,’&mgr’,&sal,&comm.,’&hiredate’,&deptno);

Update:This command is used to make changes to records in tables.

Updating all rows. UPDATE emp SET ename=’gajendra’, sal=5000;

Updating records conditionally. UPDATE emp SET ename=’gajendra’, sal=5000 WHERE deptno=10;

Delete:The delete command deletes rows from the table that satisfies the condition provided by its where clause.

Removal of all rows. DELETE FROM emp;

Removal of specific rows. DELETE FROM emp WHERE deptno=10;

Removal of specific rows based on the data held by the other table. DELETE FROM emp WHERE EXISTS(SELECT dname FROM dept WHERE

deptno=50)

Truncate:Truncate command deletes all records from table there is no rollback it always commits without giving the commit. 

TRUNCATE TABLE emp;

Truncate Vs Delete:

S.NO DELETE TRUNCATE

By A.G.Reddy

Page 14: Oracle Quick Reference

SQL Quick Reference 14

1 DELETE is a DML command TRUNCATE is a DDL command

2 Can be rolled back Cannot be rolled back

3 We can use WHERE clause We can't use WHERE clause

DATA QUERY LANGUAGE:Used to retrieve data from tables.

Select: To view all rows and all columns.

SELECT * FROM emp;

To view selected columns and all rows. SELECT ename, deptno, sal FROM emp WHERE deptno=10;

To view selected rows and all columns. SELECT * FROM emp WHERE sal>3000;

To view selected columns and selected rows. SELECT ename, empno FROM emp WHERE comm. Is null;

Eliminating duplicate rows. SELECT DISTINCT deptno FROM emp;

DATA CONTROL LANGUAGE: Data Control Language (DCL) is a set of SQL commands, used to control access to data in a database.

The following things can be GRANTED TO or REVOKED FROM a user or role: ALTER SELECT

By A.G.Reddy

Select DQL Commands

GrantRevoke DCL Commands

Page 15: Oracle Quick Reference

SQL Quick Reference 15 INSERT UPDATE DELETE

Grant and revoke:Oracle provides extensive security features in order to safeguard information stored in its

tables from unauthorized viewing and damage. Depending on user’s status and responsibility, appropriate right on oracle’s resources can be assigned to the user by the DBA. The rights that allow the use of some or all of oracle’s resources on the server are called Privileges.

Objects that are created by a user are owned and controlled by that user. If a user wishes to access any of the objects belonging to another user, the owner of the object will have to give permissions for such access. This is called granting of privileges.

Granting Privileges Using the GRANT Statement:WITH GRANT OPTION allows the grantee to in turn grant object privileges to other users.

To give all data manipulation permissions on a table: GRANT ALL ON emp TO gajendra;

To give permission to view and modify records in the table: GRANT SELECT,UPDATE ON emp TO gajendra;

To give grant with grant option: GRANT ALL ON emp TO gajendra WITH GRANT OPTION;

Revoking privileges given: To revoke all privileges:

REVOKE ALL ON emp FROM gajendra;

To revoke specific privileges: REVOKE DELETE ON emp FROM gajendra;

TRANSACTION CONTROL LANGUAGE:Transaction Control Language (TCL) is a set of SQL commands, used to control transactional processing in a database.

Commit:COMMIT commits the current transaction. All changes made by the transaction become visible to others and are guaranteed to be durable if a crash occurs.

By A.G.Reddy

CommitRollbackSave Point

TCL Commands

Page 16: Oracle Quick Reference

SQL Quick Reference 16 COMMIT;

Rollback:ROLLBACK rolls back the current transaction and causes all the updates made by the transaction to be discarded.

ROLLBACK; ROLLBACK TO s1;

Save point:SAVEPOINT establishes a new savepoint within the current transaction. A savepoint is a special mark inside a transaction that allows all commands that are executed after it was established to be rolled back, restoring the transaction state to what it was at the time of the save point.

SAVEPOINT s1; SAVEPOINT s2; ROLLBACK TO SAVEPOINT s1; ROLLBACK TO SAVEPOINT s2;

4. SET OPERATIONS

There are situations when we need to combine the results from two or more SELECT statements. SQL enables us to handle these requirements by using set operations. The result of

By A.G.Reddy

Page 17: Oracle Quick Reference

SQL Quick Reference 17 each SELECT statement can be treated as a set, and SQL set operations can be applied on those sets to arrive at a final result. Oracle SQL supports the following four set operations:

Set Operators:

SQL statements containing these set operators are referred to as compound queries, and each SELECT statement in a compound query is referred to as a component query. Two SELECTs can be combined into a compound query by a set operation only if they satisfy the following two conditions:

The result sets of both the queries must have the same number of columns. The datatype of each column in the second result set must match the datatype of its

corresponding column in the first result set.

These conditions are also referred to as union compatibility conditions. The term union compatibility is used even though these conditions apply to other set operations as well. Set operations are often called vertical joins, because the result combines data from two or more SELECTS based on columns instead of rows. The generic syntax of a query involving a set operation is:

The keywords UNION, UNION ALL, MINUS, and INTERSECT are set operators. We can have more than two component queries in a composite query; we will always use one less set operator than the number of component queries.

The following sections discuss syntax, examples, rules, and restrictions for the four set operations.

Union All:The UNION ALL operator merges the result sets of two component queries. This operation

returns rows retrieved by either of the component queries. The following example illustrates the UNION ALL operation

Select * from emp where deptno=10 union all select * from emp where deptno=20;

Union The UNION operator returns all distinct rows retrieved by two component queries. The

UNION operation eliminates duplicates while merging rows retrieved by either of the component queries. The following example illustrates the UNION operation By A.G.Reddy

Union All

Union

Minus

Intersect

Union All

Union

Minus

Intersect

Page 18: Oracle Quick Reference

SQL Quick Reference 18

Select * from emp where deptno=10 union select * from emp where deptno=20;

Intersect:INTERSECT returns only the rows retrieved by both component queries. Compare this with

UNION, which returns the rows retrieved by any of the component queries. If UNION acts like 'OR', INTERSECT acts like 'AND'.

SELECT ename FROM emp WHERE sal>1000 INTERSECT SELECT ename FROM emp WHERE deptno=20;

Minus:MINUS returns all rows from the first SELECT that are not also returned by the second

SELECT.

SELECT ename FROM emp WHERE sal>1000 MINUS SELECT ename FROM emp WHERE deptno=20;

The IN Function:The IN function helps reduce the need to use multiple OR conditions.

SELECT * FROM emp WHERE deptno IN(20,10,40,50);

The EXISTS Function:Many times you're required to write query to determine if a record exists. Typically you use

this to determine whether to insert or update a record. Using the EXISTS keyword is a great way to accomplish this.

The EXISTS function takes one parameter which is a SQL statement. If any records exist that match the criteria it returns true, otherwise it returns false. This gives you a clean, efficient way to write a stored procedure that does either an insert or update.

The other benefit of EXISTS is that once it finds a single record that matches it stops processing. This doesn't have a huge impact if you're checking on a primary key. It does have a big impact if you're checking for existence based on another field.

DELETE FROM emp WHERE EXISTS(SELECT dname FROM dept WHERE deptno=50)

5. SQL OPERATORS

Operators are used in expressions or conditional statements. They show equality, inequality, or a combination of both. Mathematical operators are found in every computer language and

By A.G.Reddy

Page 19: Oracle Quick Reference

SQL Quick Reference 19 may be familiar to you. SQL operators follow the same rules you may have learned in a math class or know from previous programming experience.

Operators come in three flavors, mathematical, logical, or range operations. Mathematical operators add, subtract, multiply, divide, and compare equality of numbers and strings. There are two logical operators, AND / OR. Range operators include the infamous < and > symbols used to compare equality. Take note of the following tables for future reference.

Operators come in three flavors

SQL Arithmetic Operators:Operator Example Result Definition

+ 7 + 7 = 14 Addition- 7 - 7 = 0 Subtraction* 7 * 7 = 49 Multiplication/ 7 / 7 = 1 Division

% 7 % 7 = 0 Modulus

Modulus may be the only unfamiliar term on the chart. This term describes the result when one number is divided by another number resulting in a remainder. For example 4 % 3 would result with a value of 1 since 1 is left over after 4 is divided by 3.

SQL Range Operators:Operator Example Defined Result

< 7 < 4 7 less than 4? False> 7 > 4 Greater than 4? True

<= 7 <= 11 Is 7 less than or equal to 11? True>= 7 >= 11 Are 7 greater than or equal to 11? False

SQL Equality Operators:Operator Example Defined Result

= 5 = 5 Are 5 equal to 5? True

<> 7 <> 2 Are 7 not equal to 2? True

By A.G.Reddy

MathematicalLogicalRange

MathematicalLogicalRange

Page 20: Oracle Quick Reference

SQL Quick Reference 20

SQL Logical Operators:

Operator Defined Example

AND Associates two values using AND if (($x AND $y) == 5)...

OR Associates two values using OR if (($x OR $y) == 5)...

6. FUNCTIONS

SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. Do not confuse SQL functions with user-defined functions written in PL/SQL.

By A.G.Reddy

Page 21: Oracle Quick Reference

SQL Quick Reference 21 If you call a SQL function with an argument of a datatype other than the datatype expected

by the SQL function, then Oracle attempts to convert the argument to the expected datatype before performing the SQL function. If you call a SQL function with a null argument, then the SQL function automatically returns null. The only SQL functions that do not necessarily follow this behavior are CONCAT, NVL, and REPLACE

Numeric Functions: Numeric functions accept numeric input and return numeric values. Most numeric

functions that return NUMBER values that are accurate to 38 decimal digits. The transcendental functions COS, COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, and TANH are accurate to 36 decimal digits. The transcendental functions ACOS, ASIN, ATAN, and ATAN2 are accurate to 30 decimal digits. The numeric functions are:

S.No Function Name

Description Example

1 ABS(n) ABS returns the absolute value of n. ABS(-9)=9

2 CEIL(n) CEIL returns smallest integer greater than or equal to n.

CEIL(9.5)=10

3 FLOOR(n) FLOOR returns largest integer equal to or less than n.

FLOOR(10.5)=10

4 MOD(m,n) MOD returns the remainder of m divided by n. Returns m if n is 0.

MOD(7,5)=2

5 POWER(m,n)POWER returns m raised to the nth power.

The base m and the exponent n can be any numbers, but if m is negative, then n must be an integer

POWER(3,3)=27

6ROUND(m,n)

ROUND returns n rounded to integer places to the right of the decimal point. If you omit integer, then n is rounded to 0 places. The argument integer can be negative to round off digits left of the decimal point.

ROUND(10.586,2)=10.59ROUND(10.586,-2) =200

7 TRUNC(m,n)

The TRUNC (number) function returns n truncated to m decimal places. If m is omitted, then n is truncated to 0 places. m can be negative to truncate (make zero) m digits left of the decimal point.

TRUNC(10.586,2)=10.58TRUNC(10.586,-2)=100

8 SGN(n)SIGN returns the sign of n. This function

takes as an argument any numeric datatype or any nonnumeric datatype that can be implicitly converted to NUMBER, and returns NUMBER.

SGN(3)=1SGN(-3)=-1SGN(0)=0

By A.G.Reddy

Page 22: Oracle Quick Reference

SQL Quick Reference 22 9 SQRT(n) SQRT returns the square root of n. SQRT(n)

10 SIN(n) SIN returns the sine of n (an angle expressed in radians).

SIN(30*3.142/180)=

11 COS(n) COS returns the cosine of n (an angle expressed in radians).

COS(30*3.142/180)=

12 TAN(n) TAN returns the tangent of n (an angle expressed in radians).

TAN(30*3.142/180)=

Character Functions:A character function is a function that takes one or more character values as parameters and

returns either a character value or a number value. The Oracle Server and PL/SQL provide a number of different character datatypes, including CHAR, VARCHAR, and VARCHAR2, LONG, RAW, and LONG RAW.

S.No Function Name Description

1 ASCIIReturns the ASCII code of a character.

2 CHR Returns the character associated with the specified collating code.

3 INITCAP Sets the first letter of each word to uppercase. All other letters are set to lowercase.

4 INSTR Returns the location in a string of the specified substring.

5LENGTH Returns the length of a string.

6LOWER Converts all letters to lowercase.

7

LPAD Pads a string on the left with the specified characters.

8 RPAD Pads a string on the right with the specified characters.

9 LTRIM Trims the left side of a string of all specified characters.

10 RTRIM Trims the right side of a string of all specified characters.

11 SOUNDEX Returns the "soundex" of a string.

12 SUBSTR Returns the specified portion of a string.

13 UPPER Converts all letters in the string to uppercase.

14 TRANSLATE Translates single characters in a string to different characters.

By A.G.Reddy

Page 23: Oracle Quick Reference

SQL Quick Reference 23 15 REPLACE Replaces a character sequence in a string with a different set of

characters.16 TRIM TRIM enables you to trim leading or trailing characters (or

both) from a character string.17 CONCAT Concatenates two strings into one.

Date Functions:Datetime functions operate on values of the DATE datatype. All datetime functions return

a datetime or interval value of DATE datatype, except the MONTHS_BETWEEN function, which returns a number. The datetime functions are:

S.No Function Name Description

1ADD_MONTHS

Adds the specified number of months to a date.

2LAST_DAY

Returns the last day in the month of the specified date.

3MONTHS_ BETWEEN

Calculates the number of months between two dates.

4NEW_TIME

Returns the date/time value, with the time shifted as requested by the specified time zones.

5 NEXT_DAYReturns the date of the first weekday specified that is later than the date.

6ROUND

Returns the date rounded by the specified format unit.

7 SYSDATE Returns the current date and time in the Oracle Server.

8 TRUNC Truncates the specified date of its time portion according to the format unit provided.

Conversion Function:Conversion functions convert a value from one datatype to another. Generally, the form of

the function names follows the convention datatype TO datatype. The first datatype is the input datatype. The second datatype is the output datatype. The SQL conversion functions are:

By A.G.Reddy

Page 24: Oracle Quick Reference

SQL Quick Reference 24

S.No Function Name Description

1

TO_CHAR (datetime)

TO_CHAR (datetime) converts a datetime or interval value of DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, or TIMESTAMP WITH LOCAL TIME ZONE datatype to a value of VARCHAR2 datatype in the format specified by the date format fmt. If you omit fmt, then date is converted to a VARCHAR2 value as follows:

2 TO_CHAR(number)

TO_CHAR (number) converts n to a value of VARCHAR2 datatype, using the optional number format fmt. The value n can be of type NUMBER, BINARY_FLOAT, or BINARY_DOUBLE. If you omit fmt, then n is converted to a VARCHAR2 value exactly long enough to hold its significant digits.

3TO_CHAR (character)

TO_CHAR (character) converts NCHAR, NVARCHAR2, CLOB, or NCLOB data to the database character set.

4 TO_DATE

TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to a value of DATE datatype. The fmt is a datetime model format specifying the format of char. If you omit fmt, then char must be in the default date format. If fmt is J, for Julian, then char must be an integer.

5TO_NUMBER

TO_NUMBER converts expr to a value of NUMBER datatype. The expr can be a BINARY_FLOAT or BINARY_DOUBLE value or a value of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype containing a number in the format specified by the optional format model fmt.

6CAST

CAST converts one built-in datatype or collection-typed value into another built-in datatype or collection-typed value.

7ASCIISTR

ASCIISTR takes as its argument a string in any character set and returns an ASCII version of the string. Non-ASCII characters are converted to the form \xxxx, where xxxx represents a UTF-16 code unit.

8TO_TIMESTAMP

ASCIISTR takes as its argument a string in any character set and returns an ASCII version of the string. Non-ASCII characters are converted to the form \xxxx, where xxxx represents a UTF-16 code unit.

Other Function:

By A.G.Reddy

Page 25: Oracle Quick Reference

SQL Quick Reference 25

S.No Function Name Description

1DECODE

DECODE compares expr to each search value one by one. If expr is equal to a search, then Oracle returns the corresponding result. If no match is found, then Oracle returns default. If default is omitted, then Oracle returns null.

2GREATEST

GREATEST returns the greatest of the list of exprs

3LEAST

LEAST returns the least of the list of exprs.

4

NVL

NVL lets you replace a null (blank) with a string in the results of a query. If expr1 is null, then NVL returns expr2. If expr1 is not null, then NVL returns expr1.

5COALESCE

COALESCE returns the first non-null expr in the expression list. At least one expr must not be the literal NULL. If all occurrences of expr evaluate to null, then the function returns null.

6 NULLIFNULLIF compares expr1 and expr2. If they are equal, then the function returns null. If they are not equal, then the function returns expr1. You cannot specify the literal NULL for expr1.

7 NVL2

NVL2 lets you determine the value returned by a query based on whether a specified expression is null or not null. If expr1 is not null, then NVL2 returns expr2. If expr1 is null, then NVL2 returns expr3.

7. PSEUDO COLUMNS By A.G.Reddy

Page 26: Oracle Quick Reference

SQL Quick Reference 26

A pseudo column is an item of data which does not belong in any particular table but which can be treated as if it did. Any SELECT list of columns can include these pseudo columns.

LEVEL:It returns a level of a row in a tree-structured query. It returns level 1 for a root node, 2

for children etc. it can be used in select statement where connect by is used.

SELECT LEVEL, ename FROM manager CONNECT BY ename=mname START WITH ename=’vijay’;

ROWID:It gives location in the database where row is physically stored. SELECT ROWID, name FROM emp;

ROWNUM:It gives a sequence in which rows are retrieved from the database. SELECT ROWNUM, name FROM emp;

SYSDATE:It gives current date and time of the system. SELECT SYSDATE FROM DUAL; SELECT SYSDATE, name FROM emp;

UID: It gives a number that identifies auser since oracle is used in a multi-user environment. UID is the way identifying a user.

Select YID from dual;

USER: It is used for retrieving the user name. SELECT USER FROM dual;

The DUAL table:ORACLE provides a "dummy" table called DUAL containing one column and one row.

It is useful for selecting miscellaneous information from ORACLE.

Some uses for DUAL: Display today's date

SELECT SYSDATE FROM dual; Display the value of 356 divided by 17, to three decimal places

SELECT ROUND (356 / 17, 3) FROM dual; Display the current user name

SELECT USER FROM dual;

8. AGGREGATE FUNCTIONS

By A.G.Reddy

Page 27: Oracle Quick Reference

SQL Quick Reference 27

Aggregate functions perform a calculation on a set of values and return a single value. With the exception of COUNT, aggregate functions ignore null values. Aggregate functions are often used with the GROUP BY clause of the SELECT statement.

All aggregate functions are deterministic; they return the same value any time they are called with a given set of input values.

Aggregate functions are allowed as expressions only in: The select list of a SELECT statement (either a subquery or an outer query). A COMPUTE or COMPUTE BY clause. A HAVING clause.

Aggregate Functions

Max:Returns the maximum value in the expression.

SELECT MAX ( sal ) FROM emp; SELECT MAX ( DISTINCT sal ) FROM emp; SELECT MAX( ALL sal ) FROM emp;

Min:Returns the minimum value in the expression.

SELECT MIN ( sal ) FROM emp; SELECT MIN ( DISTINCT sal ) FROM emp; SELECT MIN( ALL sal ) FROM emp;

Sum:Returns the sum of all the values, or only the DISTINCT values, in the expression. SUM can be used with numeric columns only. Null values are ignored.

SELECT SUM ( sal ) FROM emp; SELECT SUM ( DISTINCT sal ) FROM emp; SELECT SUM ( ALL sal ) FROM emp;

Avg:Returns the average of the values in a group. Null values are ignored. By A.G.Reddy

MaxMinSumAvgCount

MaxMinSumAvgCount

Page 28: Oracle Quick Reference

SQL Quick Reference 28 SELECT AVG ( sal ) FROM emp; SELECT AVG ( DISTINCT sal ) FROM emp; SELECT AVG ( ALL sal ) FROM emp;

Count:Returns the number of items in a group.

SELECT COUNT ( sal ) FROM emp; SELECT COUNT ( DISTINCT deptno ) FROM emp; SELECT COUNT ( ALL sal ) FROM emp; SELECT COUNT ( * ) FROM emp;

9. ANALYTICAL FUNCTIONS

By A.G.Reddy

Page 29: Oracle Quick Reference

SQL Quick Reference 29 Analytic functions compute an aggregate value based on a group of rows. They differ

from aggregate functions in that they return multiple rows for each group. The group of rows is called a window and is defined by the analytic_clause. For each row, a sliding window of rows is defined. The window determines the range of rows used to perform the calculations for the current row. Window sizes can be based on either a physical number of rows or a logical interval such as time.

Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. All joins and all WHERE, GROUP BY, and HAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER BY clause.

Analytic functions are commonly used to compute cumulative, moving, centered, and reporting aggregates.

RANK:RANK calculates the rank of a value in a group of values. The return type is NUMBER.

Rows with equal values for the ranking criteria receive the same rank. Oracle Database then adds the number of tied rows to the tied rank to calculate the next rank. Therefore, the ranks may not be consecutive numbers. This function is useful for top-N and bottom_N reporting.

As an aggregate function, RANK calculates the rank of a hypothetical row identified by the arguments of the function with respect to a given sort specification. The arguments of the function must all evaluate to constant expressions within each aggregate group, because they identify a single row within each group. The constant argument expressions and the expressions in the ORDER BY clause of the aggregate match by position. Therefore, the number of arguments must be the same and their types must be compatible.

As an analytic function, RANK computes the rank of each row returned from a query with respect to the other rows returned by the query, based on the values of the value_exprs in the order_by_clause.

Select rank () over (order by salary desc) rk, salary from employees;

DENSE_RANK:DENSE_RANK computes the rank of a row in an ordered group of rows and returns the

rank as a NUMBER. The ranks are consecutive integers beginning with 1. The largest rank value is the number of unique values returned by the query. Rank values are not skipped in the event of ties. Rows with equal values for the ranking criteria receive the same rank. This function is useful for top-N and bottom-N reporting.

This function accepts as arguments any numeric datatype and returns NUMBER.

As an aggregate function, DENSE_RANK calculates the dense rank of a hypothetical row identified by the arguments of the function with respect to a given sort specification.

By A.G.Reddy

Page 30: Oracle Quick Reference

SQL Quick Reference 30 The arguments of the function must all evaluate to constant expressions within each aggregate group, because they identify a single row within each group. The constant argument expressions and the expressions in the order_by_clause of the aggregate match by position. Therefore, the number of arguments must be the same and types must be compatible.

As an analytic function, DENSE_RANK computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_exprs in the order_by_clause.

select dense_rank() over(order by salary desc) rk,salary from employees;

ROW_NUMBER:ROW_NUMBER is an analytic function. It assigns a unique number to each row to

which it is applied (either each row in the partition or each row returned by the query), in the ordered sequence of rows specified in the order_by_clause, beginning with 1.

By nesting a subquery using ROW_NUMBER inside a query that retrieves the ROW_NUMBER values for a specified range, you can find a precise subset of rows from the results of the inner query. This use of the function lets you implement top-N, bottom-N, and inner-N reporting. For consistent results, the query must ensure a deterministic sort order.

Select row_number() over(order by salary desc) ro,salary from employees;

SUM:SUM returns the sum of values of expr. You can use it as an aggregate or analytic

function.This function takes as an argument any numeric datatype or any nonnumeric datatype that can be implicitly converted to a numeric datatype. The function returns the same datatype as the numeric datatype of the argument.

OTHER ANALYTICAL FUNCTION:AVG CORR COVAR_POP COVAR_SAMP COUNT CUME_DISTFIRST FIRST_VALUE LAG LASTLAST_VALUE LEADMAX MIN NTILE PERCENT_RANKPERCENTILE_CONT PERCENTILE_DISC RATIO_TO_REPORT REGR_ (Linear Regression) STDDEV STDDEV_POP STDDEV_SAMP SUM VAR_POP VAR_SAMP VARIANCE

By A.G.Reddy

Page 31: Oracle Quick Reference

SQL Quick Reference 31

10. GROUP BY, HAVING & ORDER BY CLAUSES

GROUP BY Clause:The GROUP BY clause can be used in a SELECT statement to collect data across multiple

records and group the results by one or more columns.

GROUP BY... was added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called, and without the GROUP BY function it was impossible to find the sum for each individual group of column values.

SELECT MAX ( sal ), deptno FROM emp GROUP BY deptno;

HAVING Clause:The HAVING clause is used in combination with the GROUP BY clause. It can be used in a

SELECT statement to filter the records that a GROUP BY returns.

SELECT MAX ( sal ), deptno FROM emp GROUP BY deptno HAVING deptno=10;

ORDER BY Clause:

The ORDER BY clause allows you to sort the records in your result set. The ORDER BY clause can only be used in SELECT statements.

The ORDER BY clause sorts the result set based on the columns specified. If the ASC or DESC value is omitted, the system assumed ascending order.

ASC indicates ascending order. (Default)DESC indicates descending order.

SELECT MAX ( sal ) a, deptno FROM emp GROUP BY deptno ORDER BY a; SELECT MAX ( sal ) a, deptno FROM emp GROUP BY deptno ORDER BY a ASC; SELECT MAX ( sal ) a, deptno FROM emp GROUP BY deptno ORDER BY a DESC;

By A.G.Reddy

Page 32: Oracle Quick Reference

SQL Quick Reference 32

11. INTEGRITY CONSTRAINTS

A constraint is a property assigned to a column or the set of columns in a table that prevents certain types of inconsistent data values from being placed in the column(s). Constraints are used to enforce the data integrity. This ensures the accuracy and reliability of the data in the database. The following categories of the data integrity exist

Entity Integrity Domain Integrity Referential integrity User-Defined Integrity

Entity Integrity ensures that there are no duplicate rows in a table.

Domain Integrity enforces valid entries for a given column by restricting the type, the format, or the range of possible values.

Referential integrity ensures that rows cannot be deleted, which are used by other records (for example, corresponding data values between tables will be vital).

User-Defined Integrity enforces some specific business rules that do not fall into entity, domain, or referential integrity categories.

Each of these categories of the data integrity can be enforced by the appropriate constraints. Microsoft SQL Server supports the following constraints

Integrity constraints

You can create constraints when the table is created, as part of the table definition by using the CREATE TABLE statement.

By A.G.Reddy

Primary KeyUnique KeyForeign KeyNot NullCheckDefault

Primary KeyUnique KeyForeign KeyNot NullCheckDefault

Page 33: Oracle Quick Reference

SQL Quick Reference 33 Column level constraint:If data constraints are defined as an attribute of a column definition when creating or altering a table structure they are column level constraints.

Table level constraint:If data constraints are defined after defining all table column attributes when creating or altering a table structure they are table level constraints.

PRIMARY KEY:A PRIMARY KEY constraint is a unique identifier for a row within a database table.

Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. The primary key constraints are used to enforce entity integrity.

Features of primary key:2. Primary key is a column or set of columns that uniquely identifies a row. Its main

purpose is the record uniqueness.3. Primary key will not allow duplicate values.4. Primary key will not allow null values.5. Primary key is not compulsory but it is recommended.6. Primary key can not be LONG or LONG RAW data type.7. Only one Primary key is allowed per table.8. Unique index is created automatically if there is a primary key.9. One table can combine up to 16 columns in a composite primary key.

Primary key defined at column level: CREATE TABLE emp (empno number, ename varchar2(15),job

varchar2(15), mgr varchar2(15), sal number, comm Number, hiredate date, deptno number PRIMARY KEY);

Primary key defined at table level: CREATE TABLE emp (empno number, ename varchar2(15),job

varchar2(15), mgr varchar2(15), sal number, comm Number, hiredate date, deptno number, PRIMARY KEY (deptno));

Composite primary key: CREATE TABLE emp (empno number, ename varchar2(15),job

varchar2(15), mgr varchar2(15), sal number, comm Number, hiredate date, deptno number, PRIMARY KEY (deptno,ename));

FOREIGN KEY: By A.G.Reddy

Page 34: Oracle Quick Reference

SQL Quick Reference 34 A FOREIGN KEY constraint prevents any actions that would destroy link between tables

with the corresponding data values. A foreign key in one table points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity.

Features of foreign key:1. Foreign key is a column(s) that references a column(s) of a table and it can be the same

table also.2. Parent that is being referenced has to be unique or primary key.3. Foreign key constraint can be specified on child but not on parent.4. Parent record can be deleting provided no child record exists.5. Master table can not be updated if child record exists.

Foreign key defined at column level: CREATE TABLE dept (deptno number FOREIGN KEY REFERENCES

emp (deptno), dname varchar2(15),loc varchar2(15));

Foreign key defined at table level: CREATE TABLE dept (deptno number, dname varchar2(15),loc

varchar2(15), FOREIGN KEY(deptno) REFERENCES emp (deptno) );

Foreign key constraint defined with ON DELETE CASCADE:A foreign key with a cascade delete means that if a record in the parent table is deleted,

then the corresponding records in the child table with automatically be deleted. This is called a cascade delete.

CREATE TABLE dept (deptno number, dname varchar2(15),loc varchar2(15), FOREIGN KEY(deptno) REFERENCES emp (deptno) ON DELETE CASCADE);

Foreign key constraint defined with ON DELETE SET NULL:A foreign key with an ON DELETE SET NULL means that if a record in the parent table

is deleted, then the corresponding records in the child table will have the foreign key fields set to null. The records in the child table will not be deleted.

CREATE TABLE dept (deptno number, dname varchar2(15),loc varchar2(15), FOREIGN KEY(deptno) REFERENCES emp (deptno) ON DELETE SET NULL);

UNIQUE KEY:

By A.G.Reddy

Page 35: Oracle Quick Reference

SQL Quick Reference 35 A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no

duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints.

Features of unique key:1. Unique key will not allow duplicate values.2. Unique index is created automatically.3. A table can have more than one unique key which is not possible in primary key.4. Unique can combine up to 16 columns in a composite unique key.5. Unique key can not be LONG or LONGRAW data type.

Unique key defined at column level: CREATE TABLE emp (empno number UNIQUE, ename

varchar2(15),job varchar2(15), mgr varchar2(15), sal number, comm Number, hiredate date, deptno number );

Unique key defined at table level: CREATE TABLE emp (empno number, ename varchar2(15),job

varchar2(15), mgr varchar2(15), sal number, comm Number, hiredate date, deptno number, UNIQUE (empno) );

CHECK:A CHECK constraint is used to limit the values that can be placed in a column. The

check constraints are used to enforce domain integrity.

Check defined at column level: CREATE TABLE emp (empno number CHECK (empno>10), ename

varchar2(15),job varchar2(15), mgr varchar2(15), sal number, comm Number, hiredate date, deptno number );

Check defined at table level: CREATE TABLE emp (empno number, ename varchar2(15),job

varchar2(15), mgr varchar2(15), sal number, comm Number, hiredate date, deptno number, CHECK (empno>10) );

NOT NULL:A NOT NULL constraint enforces that the column will not accept null values. The not null

constraints are used to enforce domain integrity, as the check constraints. CREATE TABLE emp (empno number, ename varchar2(15),job

varchar2(15), mgr varchar2(15), sal number, comm Number, hiredate date, deptno number NOT NULL);

DEFAULT:

By A.G.Reddy

Page 36: Oracle Quick Reference

SQL Quick Reference 36 Default constraint will insert the value defined as default, implicitly. When you define a

default value, you don’t have to explicitly insert values. You can ignore them when you’re inserting.

Features of default:1. The data type of the default value should match the data type of the column.2. Character and date values will be specified in single quotes.3. If a column level constraint is defined on the column with a default value, the default

value clause must precede constraint definition.

CREATE TABLE emp (empno number, ename varchar2(15),job varchar2(15), mgr varchar2(15), sal number DEFAULT 1000, comm Number, hiredate date, deptno number);

Assigning user defined names to constraints:When constraints are defined, oracle assigns a unique name to each constraint. On other

hand users can define their own names to constraints as follows:

CREATE TABLE dept (deptno number CONSTRAINT fk_deptno FOREIGN KEY REFERENCES emp (deptno), dname varchar2(15),loc varchar2(15));

CREATE TABLE dept (deptno number, dname varchar2(15),loc varchar2(15), CONSTRAINT fk_deptno FOREIGN KEY(deptno) REFERENCES emp (deptno) );

Enabling & Disabling Constraint:If the constraints are present then for each DML operation constraints are checked by

executing certain code internally. It may slow down DML operation marginally. For massive DML operations such as transferring data from one table to another because of presence of constraint, the speed will be considerably slower. To improve the speed in such cases the following methods are adopted:

1. Disable constraint.2. Perform the DML operation.3. Enable constraint.

Enabling and disabling Oracle constraints can also be done with the ENABLE and DISABLE keywords of the CONSTRAINT clause.

If you define a constraint but do not explicitly enable or disable it, ORACLE enables it by default.

Any SQL INSERT, UPDATE or DELETE command applied to a table with constraints enabled has the possibility of failing.

By A.G.Reddy

Page 37: Oracle Quick Reference

SQL Quick Reference 37

ALTER TABLE emp DISABLE CONSTRAINT pk_empno; ALTER TABLE emp ENABLE CONSTRAINT pk_empno;

While enabling the constraint if the existing data is violating the constraint, then constraints are not enabled, an error message is displayed. In such cases do as follow:

ALTER TABLE emp ENABLE CONSTRAINT pk_empno EXCEPTION INTO excp_table;

Defining constraints via the alter table command:Oracle will not allow constraints defined using the ALTER TABLE, to be applied to the

table if the data previously placed in the table violates such constraints.

ALTER TABLE emp ADD PRIMARY KEY (deptno); ALTER TABLE emp ADD CONSTRAINT pk_deptno PRIMARY KEY (deptno);

Dropping constraints via the alter table command:Dropping UNIQUE and PRIMARY KEY constraints also drop all associated indexes.

ALTER TABLE emp DROP PRIMARY KEY; ALTER TABLE emp DROP CONSTRAINT F_empKey;

12. PERFORMANCE TUNING

INDEXES:

By A.G.Reddy

Page 38: Oracle Quick Reference

SQL Quick Reference 38 An index is a performance-tuning method of allowing faster retrieval of records. An

index creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes.Indexes are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes; they are just used to speed up queries. 

Note: Updating a table containing indexes takes more time than updating a table without, this is because the indexes also need an update. So, it is a good idea to create indexes only on columns that are often used for a search.

Indexing involves forming a two dimensional matrix completely independent of the table on which the index being created. This two dimensional matrix will have a column, which will hold sorted data, extracted from the table column(s) on which the index is created.

Another column called the address field identifies the location of the record in the oracle database.

Few things about Indexes:1. Indexes are optional structures associated with tables and clusters.2. You can create indexes on one or more columns of a table to speed SQL statement

execution on that table3. Oracle index provides fast access path to table data.4. Indexes are the primary means of reducing disk I/O when properly used.5. You can create many indexes for a table as long as the combination of columns differs for

each index.6. You can create more than one index using the same columns if you specify distinctly

different combinations of the columns.

What to Index: Columns used frequently in Where clauses Columns used in joins, usually primary and foreign keys Columns used in Group by clauses Columns used in Order by clauses Columns used in aggregate functions

What Not to Index: Tables with a small number of rows Tables with heavy transaction-based I/O Columns not used in Where clause Columns with greater than 5 percent selectivity Wide columns (greater than 25 bytes in width)

Index-organized Table applications: Online transaction processing (OLTP). Internet (for example, search engines and portals). E-commerce (for example, electronic stores and catalogs).

By A.G.Reddy

Page 39: Oracle Quick Reference

SQL Quick Reference 39 Data warehousing. Time-series applications.

Types of Indexes:

TYPES

OF

INDEXES

S.No Index Name

1. Duplicate / Unique Index 2. Simple Index3. Composite Index4. Reverse Key Index5. Bitmap Index6. Function Based Index

Duplicate / Unique Index:Oracle allows the creation of two types of indexes:

Indexes that allow duplicate values for the indexed column i.e. duplicate index. Indexes that deny duplicate values for the indexed column i.e. unique index.

Creation of an index:An index can be created on one or more columns. Based on the number of columns included in the index, an index can be:

Simple Index Composite Index

Simple index:An index created on a single column is called a simple index.

Create index i_ename on emp (ename);

Composite index: An index created on more than one column is called a composite index.

Create index i_ename on emp (ename,deptno);

Unique index:A unique index can be created on one or more columns

Create unique index i_empno on emp (empno);

Reverse key index:A reverse key index works by reversing the order of the bytes in the key value; of course, the

rowid value is not altered, just the key value. The only way to create a reverse-key index is to

use the CREATE INDEX command. An index that is not reverse-key cannot be altered or rebuilt into a reverse-key index; however, a reverse-key index can be rebuilt as a normal index.

By A.G.Reddy

Page 40: Oracle Quick Reference

SQL Quick Reference 40 Reverse key indexing avoids performance degradation in indexes where modifications to

the index are concentrated on a small set of blocks. By reversing the keys of the index, the insertion becomes distributed all over the index.

Create index i_empno ON emp (ename) REVERSE;

A reverse key index can be rebuilt into normal index by using the key words REBUILD NO REVERSE.

ALTER INDEX i_empno REBUILD NOREVERSE;

Bitmap index:Oracle bitmap indexes are very different from standard b-tree indexes. In bitmap

structures, a two-dimensional array is created with one column for every row in the table being indexed. Each column represents a distinct value within the bitmapped index. This two-dimensional array represents each value within the index multiplied by the number of rows in the table. At row retrieval time, Oracle decompresses the bitmap into the RAM data buffers so it can be rapidly scanned for matching values. These matching values are delivered to Oracle in the form of a Row-ID list, and these Row-ID values may directly access the required information.

The real benefit of bitmapped indexing occurs when one table includes multiple bitmapped indexes. Each individual column may have low cardinality. The creation of multiple bitmapped indexes provides a very powerful method for rapidly answering difficult SQL queries.

CREATE BITMAP INDEX i_deptno On emp(deptno);

Bitmap index provides the following benefits: Reduced response time for large classes of ad hoc queries. A substantial reduction of space usage compared to other indexing techniques.

Function based indexes:Traditionally, performing a function on an indexed column in the where clause of a query

guaranteed an index would not be used. Oracle 8i introduced Function Based Indexes to counter this problem. Rather than indexing a column, you index the function on that column, storing the product of the function, not the original column data. When a query is passed to the server that could benefit from that index, the query is rewritten to allow the index to be used. The following code samples give an example of the use of Function Based Indexes:

CREATE INDEX i_upname ON emp( UPPER (ename));

Dropping indexes: DROP index i_upname;

By A.G.Reddy

Page 41: Oracle Quick Reference

SQL Quick Reference 41

VIEWS:A view is simply the representation of a SQL statement that is stored in memory so that it

can easily be re-used. Oracle views are used to simplify a complex query by hiding the entire internal table joins operations. A view is a logical entity. It is a SQL statement stored in the database in the system table space. Data for a view is built in a table created by the database engine in the TEMP table space

Reasons why views are created are: Views are used to simplify a complex query. When data security is required. When data redundancy is to be kept to minimum while maintaining data security.

TYPES OF VIEWS:

S.NO NAME OF THE VIEW

DESCRIPTION

1 READ ONLY VIEW a view is used to only to look at the table data then it is called readonlyview.

2 UPDATABLE VIEWif a view is used to look at the table data as well as INSERT, UPDATE and DELETE table data is called updatable views.

3 INLINE VIEWThe inline view is a construct in Oracle SQL where you can place a query in the SQL FROM, clause, just as if the query was a table name.

4 FORCE VIEW Force ... Forces The Creation Of A View Even When The View Will Be Invalid. No Force Is The Default

When an updatable view name is given in an INSERT, UPDATE and DELETE statements, the modifications to data in the view will be immediately passed to the underlying table.

For a view to be updatable, it should meet the following criteria: Views defined from a single table. If the user wants to INSERT records with the help of a view, then the primary key

column(s) and all not null column(s) must be included in the view.

The updatable view definition must not include: Aggregate functions Distinct, group by and having clauses. Sub-queries.

By A.G.Reddy

Page 42: Oracle Quick Reference

SQL Quick Reference 42 Union, intersect and minus clauses.

Creating a view:The ORDER BY clause can not be used while creating a view.

CREATE VIEW v_emp AS SELECT * FROM emp; CREATE VIEW v_emp AS SELECT ename,deptno from emp;

Selecting data set from a view: SELECT * FROM v_emp; SELECT ename, deptno FROM v_emp;

Inline View:The inline view is a construct in Oracle SQL where you can place a query in the SQL

FROM, clause, just as if the query was a table name. A common use for in-line views in Oracle SQL is to simplify complex queries by removing join operations and condensing several separate queries into a single query.

SELECT ename,deptno FROM(SELECT * FROM emp);

Force View:A view can be created even if the defining query of the view cannot be executed, as long

as the CREATE VIEW command has no syntax errors. We call such a view a view with errors. For example, if a view refers to a non-existent table or an invalid column of an existing table, or if the owner of the view does not have the required privileges, then the view can still be created and entered into the data dictionary.

CREATE FORCE VIEW v_emp AS SELECT * FROM emp;

Destroying a view: DROP VIEW v_emp;

SEQUENCES:

In Oracle, you can create an auto number field by using sequences. A sequence is an object in Oracle that is used to generate a number sequence. This can be useful when you need to create a unique number to act as a primary key.

PRACTICE:SQL> CREATE SEQUENCE ABC_SEQ INCREMENT BY 5 START WITH 0 MAXVALUE 1000 MINVALUE 0 NOCACHE NOCYCLE;

Sequence created.

SQL> SELECT ABC_SEQ.NEXTVAL FROM DUAL;

NEXTVAL

By A.G.Reddy

Page 43: Oracle Quick Reference

SQL Quick Reference 43 ---------- 0

SQL> SELECT ABC_SEQ.CURRVAL FROM DUAL;

CURRVAL ---------- 0

SQL> CREATE TABLE ABC (NO NUMBER);

Table created.

SQL> INSERT INTO ABC VALUES (ABC_SEQ.NEXTVAL);

1 row created.

SQL> INSERT INTO ABC VALUES (ABC_SEQ.NEXTVAL);

1 row created.

SQL> INSERT INTO ABC VALUES (ABC_SEQ.NEXTVAL);

1 row created.

SQL> INSERT INTO ABC VALUES (ABC_SEQ.NEXTVAL);

1 row created.SQL> SELECT * FROM ABC;

13. MATERIALIZED VIEWS

What is a Materialized View?In a database management system following the relational model, a view is a virtual table

representing the result of a database query. Whenever an ordinary view's table is queried or updated, the DBMS converts these into queries or updates against the underlying base tables. A By A.G.Reddy

Page 44: Oracle Quick Reference

SQL Quick Reference 44 materialized view takes a different approach in which the query result is cached as a concrete table that may be updated from the original base tables from time to time. This enables much more efficient access, at the cost of some data being potentially out-of-date. It is most useful in data warehousing scenarios, where frequent queries of the actual base tables are extremely expensive.

In addition, because the view is manifested as a real table, anything that can be done to a real table can be done to it, most importantly building indexes on any column, enabling drastic speedups in query time. In a normal view, it's typically only possible to exploit indexes on columns that come directly from (or have a mapping to) indexed columns in the base tables; often this functionality is not offered at all.

Materialized views were implemented first by the Oracle database.

A materialized view is a replica of a target master from a single point in time. The master can be either a master table at a master site or a master materialized view at a materialized view site. Whereas in MultiMate replication tables are continuously updated by other master sites, materialized views are updated from one or more masters through individual batch updates, known as a refreshes, from a single master site or master materialized view site, as illustrated in the below Figure. The arrows in Figure represent database links.

Materialized View Connected to a Single Master Site:

When a materialized view is fast refreshed, Oracle must examine all of the changes to the master table or master materialized view since the last refresh to see if any apply to the materialized view. Therefore, if any changes where made to the master since the last refresh, then a materialized view refresh takes some time to apply the changes to the materialized view.

If, however, no changes at all were made to the master since the last refresh of a materialized view, then the materialized view refresh should be very quick.

Types of materialized views:There are three types of materialized views:

1. Read only materialized view By A.G.Reddy

Page 45: Oracle Quick Reference

SQL Quick Reference 45 2. Updateable materialized view 3. Writeable materialized view

1). Read only materialized views:You can make a materialized view read-only during creation by omitting the FOR

UPDATE clause or disabling the equivalent option in the Replication Management tool. Read-only materialized views use many of the same mechanisms as updatable materialized views, except that they do not need to belong to a materialized view group.

In addition, using read-only materialized views eliminates the possibility of a materialized view introducing data conflicts at the master site or master materialized view site, although this convenience means that updates cannot be made at the remote materialized view site. The following is an example of a read-only materialized view:

CREATE MATERIALIZED VIEW hr.employees ASSELECT * FROM [email protected];

Advantages:

There is no possibility for conflicts as they cannot be updated. Complex materialized views are supported

2). Updateable materialized views:You can make a materialized view updatable during creation by including the FOR

UPDATE clause or enabling the equivalent option in the Replication Management tool. For changes made to an updatable materialized view to be pushed back to the master during refresh, the updatable materialized view must belong to a materialized view group.

Updatable materialized views enable you to decrease the load on master sites because users can make changes to the data at the materialized view site. The following is an example of an updatable materialized view:

CREATE MATERIALIZED VIEW hr.departments FOR UPDATE AS SELECT * FROM [email protected];

Advantages:

Can be updated even when disconnected from the master site or master materialized view site.

Requires fewer resources than multi master replication.

Are refreshed on demand. Hence the load on the network might be reduced compared to using multi master replication because multi master replication synchronizes changes at regular intervals.

Updateable materialized views require the advanced replication option to be installed.

Writeable materialized views:

By A.G.Reddy

Page 46: Oracle Quick Reference

SQL Quick Reference 46 A writeable materialized view is one that is created using the FOR UPDATE clause but is

not part of a materialized view group. Users can perform DML operations on a writeable materialized view, but if you refresh the materialized view, then these changes are not pushed back to the master and the changes are lost in the materialized view itself. Writeable materialized views are typically allowed wherever fast-refreshable read-only materialized views are allowed.

Most of the documentation about materialized views only refers to read-only and updatable materialized views because writeable materialized views are rarely used.

They are created with the for update clause during creation without then adding the materialized view to a materialized view group. In such a case, the materialized view is updatable, but the changes are lost when the materialized view refreshes.

Writeable materialized views require the advanced replication option to be installed.

Why Use Materialized Views?You can use materialized views to achieve one or more of the following goals:

Ease Network Loads Create a Mass Deployment Environment Enable Data Sub setting Enable Disconnected Computing

Ease Network LoadsIf one of your goals is to reduce network loads, then you can use materialized views to

distribute your corporate database to regional sites. Instead of the entire company accessing a single database server, user load is distributed across multiple database servers. Through the use of multitier materialized views, you can create materialized views based on other materialized views, which enables you to distribute user load to an even greater extent because clients can access materialized view sites instead of master sites. To decrease the amount of data that is replicated, a materialized view can be a subset of a master table or master materialized view.

While multimaster replication also distributes a corporate database among multiple sites, the networking requirements for multimaster replication are greater than those for replicating with materialized views because of the transaction by transaction nature of multimaster replication. Further, the ability of multimaster replication to provide real-time or near real-time replication may result in greater network traffic, and might require a dedicated network link.

Materialized views are updated through an efficient batch process from a single master site or master materialized view site. They have lower network requirements and dependencies than multimaster replication because of the point in time nature of materialized view replication. Whereas multimaster replication requires constant communication over the network, materialized view replication requires only periodic refreshes.

By A.G.Reddy

Page 47: Oracle Quick Reference

SQL Quick Reference 47 In addition to not requiring a dedicated network connection, replicating data with

materialized views increases data availability by providing local access to the target data. These benefits, combined with mass deployment and data subsetting (both of which also reduce network loads), greatly enhance the performance and reliability of your replicated database.

Create a Mass Deployment EnvironmentDeployment templates allow you to precreate a materialized view environment locally.

You can then use deployment templates to quickly and easily deploy materialized view environments to support sales force automation and other mass deployment environments. Parameters allow you to create custom data sets for individual users without changing the deployment template. This technology enables you to roll out a database infrastructure to hundreds or thousands of users.

Enable Data SubsettingMaterialized views allow you to replicate data based on column- and row-level

subsetting, while multimaster replication requires replication of the entire table. Data subsetting enables you to replicate information that pertains only to a particular site. For example, if you have a regional sales office, then you might replicate only the data that is needed in that region, thereby cutting down on unnecessary network traffic.

Enable Disconnected ComputingMaterialized views do not require a dedicated network connection. Though you have the

option of automating the refresh process by scheduling a job, you can manually refresh your materialized view on-demand, which is an ideal solution for sales applications running on a laptop. For example, a developer can integrate the replication management API for refresh on-demand into the sales application. When the salesperson has completed the day's orders, the salesperson simply dials up the network and uses the integrated mechanism to refresh the database, thus transferring the orders to the main office.

14. JOINS

Few Points about Joins: A join is a query that combines rows from two or more tables, views, or materialized

views.

By A.G.Reddy

Page 48: Oracle Quick Reference

SQL Quick Reference 48 A join is performed whenever two or more tables is listed in the FROM clause of an SQL

statement.

The select list of the query can select any columns from any of these tables. If any two of these tables have a column name in common, then you must qualify all references to these columns throughout the query with table names to avoid ambiguity.

Most join queries contain WHERE clause conditions that compare two columns, each from a different table. Such a condition is called a join condition. To execute a join, Oracle Database combines pairs of rows, each containing one row from each table, for which the join condition evaluates to TRUE. The columns in the join conditions need not also appear in the select list.

To execute a join of three or more tables, Oracle first joins two of the tables based on the join conditions comparing their columns and then joins the result to another table based on join conditions containing columns of the joined tables and the new table. Oracle continues this process until all tables are joined into the result. The optimizer determines the order in which Oracle joins tables based on the join conditions, indexes on the tables, and, any available statistics for the tables.

In addition to join conditions, the WHERE clause of a join query can also contain other conditions that refer to columns of only one table. These conditions can further restrict the rows returned by the join query.

Cartesian product:If two tables in a join query have no join condition, then Oracle Database returns their

Cartesian product. Oracle combines each row of one table with each row of the other. A Cartesian product always generates many rows and is rarely useful. For example, the Cartesian product of two tables, each with 100 rows, has 10,000 rows. Always include a join condition unless you specifically need a Cartesian product. If a query joins three or more tables and you do not specify a join condition for a specific pair, then the optimizer may choose a join order that avoids producing an intermediate Cartesian product.

Self join:A self join is a join of a table to itself. This table appears twice in the FROM clause and is

followed by table aliases that qualify column names in the join condition. To perform a self join, Oracle Database combines and returns rows of the table that satisfy the join condition.

SELECT a.ename, b.mgr FROM emp a, emp b WHERE a.deptno=b.deptno;

TYPES OF JOINS:S.No Join Method Sub Type

1. Inner/natural/Equi Joins -----

Left Outer join

By A.G.Reddy

Page 49: Oracle Quick Reference

SQL Quick Reference 49

2.Outer Join Right Outer Join

Full Outer Join

3. Cross Join -----

Inner Join / Equi Join / Natural Join: An inner join (sometimes called a simple join) is a join of two or more tables that returns

only those rows that satisfy the join condition. An inner join is called Equi Join when the where statement compares two columns with

the equivalence (‘=’) operator. These joins returns all rows from both tables where there is a match. Most common joins used in SQL.

SELECT * FROM emp a, dept b WHERE a.deptno=b.deptno; (Theta Style) SELECT * FROM emp a INNER JOIN dept b ON a.deptno=b.deptno; (ANSI Style)

Cross Join: Returns what known as Cartesian product. Combines every row from the left table to the every row in the right table. Same as forgetting to add a WHERE clause when joining two tables. There is no use with the Cross Join.

Outer Join: Returns all rows from the left/right/both table(s) regardless of weather the other table

have values in common. Enters null where data is missing.

Left Outer Join;This returns all the rows from the table on the left side of the join, along with the values

from the right-hand side, or nulls if a matching row doesn't exist.

To write a query that performs an outer join of tables A and B and returns all rows from A (a left outer join), use the LEFT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+) to all columns of B in the join condition in the WHERE clause. For all rows in A that have no matching rows in B, Oracle Database returns null for any select list expressions containing columns of B.

SELECT a.ename, b.mgr FROM emp a, emp b WHERE a.deptno=b.deptno(+); (Theta Style)

SELECT a.ename, b.mgr FROM emp a LEFT OUTR JOIN emp b ON (a.deptno=b.deptno); (ANSI Style)

Right Outer Join:

By A.G.Reddy

Page 50: Oracle Quick Reference

SQL Quick Reference 50 This returns all the rows from the table on the right side of the join, along with the values

from the left-hand side, or nulls if a matching row doesn't exist.

To write a query that performs an outer join of tables A and B and returns all rows from B (a right outer join), use the RIGHT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+) to all columns of A in the join condition in the WHERE clause. For all rows in B that have no matching rows in A, Oracle returns null for any select list expressions containing columns of A.

SELECT a.ename, b.mgr FROM emp a, emp b WHERE a.deptno(+)=b.deptno;(Theta Style)

SELECT a.ename, b.mgr FROM emp a RIGHT OUTR JOIN emp b ON (a.deptno=b.deptno); (ANSI Style)

Full Outer Join:This returns all rows from both tables, filling in any blanks with nulls. There is no

equivalent for this in Oracle8i.

To write a query that performs an outer join and returns all rows from A and B, extended with nulls if they do not satisfy the join condition (a full outer join), use the FULL [OUTER] JOIN syntax in the FROM clause.

SELECT e.ename, d.dname FROM emp e FULL OUTER JOIN dept d ON (e.deptno=d.deptno);

JOIN METHODS IN ORACLE:When a select statement gets data from multiple tables, the table are said to be joined.

Different join methods are possible in Oracle. Such a join method determines the mechanism how such row sources are joined.

To join each pair of row sources, Oracle must perform one of these operations: 1. nested loops 2. sort-merge 3. cluster 4. hash join (not available with rule-based optimization)

Nested loops:To perform a nested loops join, Oracle follows these steps:

A. The optimizer chooses one of the tables as the outer table, or the driving table. The other table is called the inner table.

B. For each row in the outer table, Oracle finds all rows in the inner table that satisfy the join condition.

C. Oracle combines the data in each pair of rows that satisfy the join condition and returns the resulting rows.

By A.G.Reddy

Page 51: Oracle Quick Reference

SQL Quick Reference 51

Figure shows the execution plan for this statement using a nested loops join: SELECT * FROM emp, dept WHERE emp.deptno = dept.deptno;

To execute this statement, Oracle performs these steps: 1. Step 2 accesses the outer table (EMP) with a full table scan. 2. For each row returned by Step 2, Step 4 uses the EMP.DEPTNO value to perform a

unique scan on the PK_DEPT index. 3. Step 3 uses the rowid from Step 4 to locate the matching row in the inner table (DEPT). 4. Oracle combines each row returned by Step 2 with the matching row returned by Step 4

and returns the result.

Sort Merge join:Oracle can only perform a sort-merge join for an equijoin. To perform a sort-merge join, Oracle follows these steps:

1. Oracle sorts each row source to be joined if they have not been sorted already by a previous operation. The rows are sorted on the values of the columns used in the join condition.

2. Oracle merges the two sources so that each pair of rows, one from each source, that contain matching values for the columns used in the join condition are combined and returned as the resulting row source.

Figure shows the execution plan for this statement using a sort-merge join: SELECT * FROM emp, dept WHERE emp.deptno = dept.deptno;

By A.G.Reddy

Page 52: Oracle Quick Reference

SQL Quick Reference 52

To execute this statement, Oracle performs these steps: Steps 3 and 5 perform full table scans of the EMP and DEPT tables. Steps 2 and 4 sort each row source separately. Step 1 merges the sources from Steps 2 and 4 together, combining each row from

Step 2 with each matching row from Step 4, and returns the resulting row source.

Cluster Join: Oracle can perform a cluster join only for an equijoin that equates the cluster key columns of

two tables in the same cluster. In a cluster, rows from both tables with the same cluster key values are stored in the same blocks, so Oracle only accesses those blocks.

Figure shows the execution plan for this statement in which the EMP and DEPT tables are stored together in the same cluster:

SELECT * FROM emp, dept WHERE emp.deptno = dept.deptno;

By A.G.Reddy

Page 53: Oracle Quick Reference

SQL Quick Reference 53 To execute this statement, Oracle performs these steps:

Step 2 accesses the outer table (DEPT) with a full table scan. For each row returned by Step 2, Step 3 uses the DEPT.DEPTNO value to find the

matching rows in the inner table (EMP) with a cluster scan.

A cluster join is nothing more than a nested loop joins involving two tables that are stored together in a cluster. Since each row from the DEPT table is stored in the same data blocks as the matching rows in the EMP table, Oracle can access matching rows most efficiently.

Hash joins:Oracle can only perform a hash join for an equijoin. Hash join is not available with rule-

based optimization. You must enable hash join optimization, using the initialization parameter HASH_JOIN_ENABLED (which can be set with the ALTER SESSION command) or the USE_HASH hint.

To perform a hash join, Oracle follows these steps:

1. Oracle performs a full table scan on each of the tables and splits each into as many partitions as possible based on the available memory.

2. Oracle builds a hash table from one of the partitions (if possible, Oracle will select a partition that fits into available memory). Oracle then uses the corresponding partition in the other table to probe the hash table. All partition pairs that do not fit into memory are placed onto disk.

3. For each pair of partitions (one from each table), Oracle uses the smaller one to build a hash table and the larger one to probe the hash table.

Figure shows the execution plan for this statement using a hash join: SELECT * FROM emp, dept WHERE emp.deptno = dept.deptno;

To execute this statement, Oracle performs these steps: Steps 2 and 3 perform full table scans of the EMP and DEPT tables. Step 1 builds a hash table out of the rows coming from Step 2 and probes it

with each row coming from Step 3. The initialization parameter HASH_AREA_SIZE controls the amount of memory used

for hash join operations and the initialization parameter HASH_MULTIBLOCK_IO_COUNT controls the number of blocks a hash join operation should read and write concurrently.

By A.G.Reddy

Page 54: Oracle Quick Reference

SQL Quick Reference 54

15. SUB QUERIES

Subqueries are extremely useful, particularly for web-based database applications where you need to take two queries and manually put them together to reach a desired result -- subqueries allow SQL to do all of the heavy lifting! Subqueries can also be used in many cases to replace a self-join (or vice-versa). A SQL join is usually quicker but, as we've discussed many times before, there is usually more than one way to perform any given SQL task.

A subquery is inner query that will be used by outer query. A subquery could return scalar value or a series of value. Based on query dependency, a subquery could be self-contained or correlated one. A self-contained subquery is a subquery independent from outer query, and correlated subquery is a subquery that is referencing to a row in outer query.

  Self-contained subquery is easier to debug than correlated subquery. And it is executed

only once whereas correlated subquery is executed once for each row of outer query.

A query in a query(Sub Query)?The subquery is fairly straightforward part of the SQL specification. In a nutshell, a

subquery is a SQL SELECT statement that is placed in the predicate of any other SQL statement we've explored -- SELECT, INSERT, UPDATE, or DELETE.

A subquery can be used in a number of scenarios: SELECT/UPDATE/DELETE.... WHERE (SELECT ...) which can be used to filter data

before an action is applied to the results of that filter; INSERT INTO.... SELECT.... which can be used to copy tables or portions of tables into

a new table for further manipulation; Another subquery which can then be nested again up to the limits of your database

platform -- or your sanity and understanding.

Sample of self-contained subquery that returns scalar value is shown below:

SELECT customerid FROM dbo.orders WHERE employeeid = (SELECT employeeid FROM dbo.employees WHERE lastname = ‘Chang’);

  This query returns customers list whose employee is Chang.(Assume one chang). SELECT ename,empno FROM emp WHERE sal=(SELECT max(sal) FROM emp);

Sample of self-contained subquery that returns series of value is shown below: SELECT customerid FROM dbo.orders WHERE employeeid in (1,2,3,4,5);

This query return customer lists that were served by employee with employeeid = 1,2,3,4 and 5.Self-contained subquery doesn’t have join to outer query, while correlated subquery has join to outer query.

SELECT * FROM emp WHERE deptno IN (10,20); SELECT ename FROM emp WHERE deptno IN (10,20,30);

By A.G.Reddy

Page 55: Oracle Quick Reference

SQL Quick Reference 55 correlated subquery:

A correlated subquery is a SELECT statement nested inside another T-SQL statement, which contains a reference to one or more columns in the outer query. Therefore, the correlated subquery can be said to be dependent on the outer query. This is the main difference between a correlated subquery and just a plain subquery. A plain subquery is not dependent on the outer query, can be run independently of the outer query, and will return a result set. A correlated subquery, since it is dependent on the outer query will return a syntax errors if it is run by itself.

A correlated subquery will be executed many times while processing the  SQL statement that contains the correlated subquery. The correlated subquery will be run once for each candidate row selected by the outer query. The outer query columns, referenced in the correlated subquery, are replaced with values from the candidate row prior to each execution. Depending on the results of the execution of the correlated subquery, it will determine if the row of the outer query is returned in the final result set.

Here the sample of correlated subquery: SELECt s.shipperid, (select count(*) FROM dbo.orders as o WHERE o.shipperid =

s.shipperid) as numberOfOrders FROM dbo.shippers as s;

SELECT DEPTNO, ENAME, SAL FROM EMP A WHERE 3 = (SELECT COUNT(B.SAL) FROM EMP B WHERE A.SAL < B.SAL) ORDER BY SAL DESC;

  Other forms of correlated subquery could be like this one: SELECT orderid, orderdate, employeeid FROM dbo.orders as o1 WHERE orderdate =

(SELECT max (orderdate) FROM dbo.orders as o2 WHERE o2.employeeid = o1.employeeid);

 This query answers request information about last order made by participating

employees. Another operators that handle correlated subquery is EXISTS (NOT EXISTS) and IN (NOT IN).

Difference Between Simple and Correlated Subquery: Simple sub query is one in which inner query is evaluated only once and from that result

outer query is evaluated. Correlated Subquery is one in which Inner query is evaluated for multiple times for

getting one row of that outer query.

By A.G.Reddy

Page 56: Oracle Quick Reference

SQL Quick Reference 56

16. CASE EXPRESSIONS

The SQL CASE...WHEN statement is very similar to a switch or case statement in other computer languages. The key that makes it especially useful is that you can use CASE...WHEN within a SELECT statement. Technically, CASE evaluates a list of conditions and returns one of multiple possible result expressions—so it's easy to see how someone new to the language might try to use a series of IF...THEN statements instead of looking for something a little more powerful

Evaluates a list of conditions and returns one of multiple possible result expressions. CASE has two formats:

1. Simple Case Statement:The simple CASE function compares an expression to a set of simple expressions to

determine the result. SELECT ename, CASE deptno WHEN 10 THEN ‘Ten’ WHEN 20 THEN

‘Twenty’ ELSE ‘Thirty’ END AS dept FROM emp;

2. Searched Case Statement:The searched CASE function evaluates a set of Boolean expressions to determine the

result. SELECT ename, CASE WHEN sal>2000 THEN ‘Grade A’ WHEN sal<2000

THEN ‘Grade B’ END AS grade FROM emp;

NULLIF Function:Returns null value if the two specified expressions are equal.

SELECT NULLIF(comm,300) FROM emp;

COALESCE Function:In Oracle/PLSQL, the coalesce function returns the first non-null expression in the list. If

all expressions evaluate to null, then the coalesce function will return null.

COALESCE (arg1, arg2...) is a pretty useful function in SQL. Suppose we have a table A having 3 columns FullName, CompleteName and DisplayName. Any of these columns can contain null values. Now we want to select the DisplayName from this table, but if it is null, then return FullName, if that is also null then return CompleteName. We can easily perform the same in one select statement as:

SELECT COALESCE(DisplayName, FullName, CompleteName) From A

SELECT COALESCE( comm, sal, deptno) FROM emp;

By A.G.Reddy

Page 57: Oracle Quick Reference

SQL Quick Reference 57

17. MISCELLANIOUS TOPICS

INSERT ALL statement:Insert All statement is used to insert values into multiple tables at a time. Without the WHEN clause INSERT ALL performs all inserts unconditionally.

INSERT ALLINTO ap_cust VALUES (customer_id, program_id, delivered_date)INTO ap_orders VALUES (order_date, program_id)SELECT program_id, delivered_date, customer_id, order_dateFROM airplanes;

MERGE Statement:A common need arises when you have to perform a combination of insert and update

operation on a single table with respect to another table. Oracle provides a 'Merge' statement for this purpose. It’s a DML operation.

The following example best describes the concept. We have two tables emp and bonuses. We want to perform a merge operation on bonuses and emp table. We want that if we match emp and bonuses table, then if a record matches in both then the record in bonuses table gets updated and if there is no match then the record from emp table gets inserted into bonus table.

Example1:SQL> SELECT * FROM bonuses;EMPLOYEE_ID BONUS----------- --------------------------- 1 100 2 100 3 100

SQL> SELECT * FROM emp;

EMPID NAME---------- --------------------- 1 Fahd 2 DAN 3 TOM 4 TOW

By A.G.Reddy

Page 58: Oracle Quick Reference

SQL Quick Reference 58

SQL> MERGE INTO BONUSES B USING (SELECT EMPID FROM EMP) E ON (B.EMPLOYEE_ID=E.EMPID) WHEN MATCHED THEN UPDATE SET B.BONUS=B.BONUS+100 WHEN NOT MATCHED THEN INSERT (B.EMPLOYEE_ID, B.BONUS) VALUES (E.EMPID, 200);

Example 2:SQL> SELECT * FROM T1;

SNO SEX ---------- ----- 1 M 2 F 4 8 M

SQL> SELECT * FROM T2;

SNO SEX ---------- ----- 1 F 3 F 4 M 6 H

SQL>MERGE INTO T1 A1. USING (SELECT SNO, SEX FROM T2) B2. ON (A.SNO=B.SNO)3. WHEN MATCHED THEN4. UPDATE SET A.SEX=B.SEX5. WHEN NOT MATCHED THEN

INSERT VALUES (B.SNO, B.SEX);

SQL> select * from t1;

SNO S---------- - 1 F 2 F 4 M 8 M 6 H 3 F

By A.G.Reddy

Page 59: Oracle Quick Reference

SQL Quick Reference 59

Creating a table from a table:In oracle it is possible to create a copy of a table with all the content in it as shown below.

CREATE TABLE abc (name,dept) AS SELECT ename,deptno FROM emp;

Inserting data into a table from another table: INSERT INTO abc SELECT ename,deptno FROM emp;

The Cast Function:In Oracle/PLSQL, the cast function converts one datatype to another.The syntax for the

cast function is: CAST ( { EXPR | ( SUB QUERY ) | MULTISET ( SUB QUERY ) } AS type name )

The following casts are allowed:

TO FROM

char, varchar2

number datetime / interval

raw rowid, urowid

nchar, nvarchar2

char, varchar2 X X X X X

number X X

datetime / interval X X

raw X X

rowid, urowid X X

nchar, nvarchar2 X X X X X

Applies To: Oracle 9i, Oracle 10g, Oracle 11g

For example: Select cast (‘22-Aug-2003' AS varchar2 (30) ) from dual;

This would convert the date (i.e.: 22-Aug-2003) into a varchar2(30) value.

By A.G.Reddy

Page 60: Oracle Quick Reference

SQL Quick Reference 60

18. ORACLE 9i, 8i AND10g FEATURES

In 9i merge, insert all, case is introduced. In 9i new data type called timestamp In 9i you can monitor index using alter index <index name> monitoring usage or u can

check User objects table from system user. In 9i new performance monitoring tools called STATPACK. In 9i you can dynamically change init ora parameter using alter system <parameter>

scope=/path/ of your spfile/pfile. In 9i new concept for undo transaction called UNDO tablespace In 9i by default TEMP tablespace is considering while creating new oracle users In 9i new partition called LIST In 9i tablespace next extent can be managed automatically In oracle 8i default tablespace is dictionary managed while in 9i it is locally managed. In Oracle 9i can support 512 PetaByte of data. In Oracle can support 10,000 concurrent users. In oracle 9i provides auto undo segment management. You have automatic undo management. you have automatic segment space management You got these locally managed tablespaces which is better than the dictionary managed

tabespaces as u can avoid fragmentation with locally managed tablespaces. You have a new dbms_metadata package to extract object definitions from database. multi table insert is possible with 9i Importantly you have this spfile in 9i. Also you have dynamic memory management facility with 9i. You have tuning advisories with 9i. You have multi block size parameter with 9i and many more features like these...

1. You can change SGA whenever you want! 2. Multiple DB blocks size support. 3. Log miner enhancement. DDL statement supported. 4. Automated management of rollback segments. 5. OMF. Remove datafile automatically when you drop tablespace. 6. Locally managed datafile default 7. Enhancement of standby DB. Automatically transfer the online redo log files. 8. You can see execution plan any time. 9. ANSI type sql support. 10. Flash back query support. (ex: You can query data before 5 minutes whether you delete and commit.) 11. Enhancement of OPS => RAC (Real Application Cluster): Cache Fusion full support 12. DML enhancement. One SQL statement support inserts and update.

By A.G.Reddy

Page 61: Oracle Quick Reference

SQL Quick Reference 61 What are the main advantages of upgrading from Oracle 7 to Oracle 8i/9i?

There are many advantages. Some of them are:

1) adding objects to the database2) adding new data type such as BLOB/CLOB3) new administrative options like moving tables between tablespaces4) many NEW dbms packages5) writing JAVA code inside Oracle6) passing parameters to sp with the NOCOPY Option7) smart sql loader options8) can work with array types9) the new log miner

Oracle 10g New Features flashback available at the row, transaction, table or database level; recovery area on disk that is maintained automatically by the database and contains

only those blocks changed since the last backup - thereby enabling faster recovery from media failure;

data guard (standby database) has been enhanced to enable compression and encryption of log traffic from the master database to the standby system;

tables can now be re-defined without invalidating stored procedures; Support for rolling upgrades of the hardware, operating system and the database to

reduce planned down time. DBMS_ERRLOG package is used to create the error log output table and link it to the

table being updated Oracle Database 10G now allows you to flush the database buffer cache with the alter

system command using the flush buffer_cache parameter 1) rule based optimizer no longer supported,

2) support for regular expression in sql,3) the model clause in queries to support multidimensional arrays,4) better support for web services (you can now easily use external web services in pl/sql code),5) improved pl/sql engine, resulting in smaller and faster code.

19. IMPORTANT SQL QUERIES By A.G.Reddy

Page 62: Oracle Quick Reference

SQL Quick Reference 62

1. The following query retrieves 2nd highest paid employees FROM each Department: SELECT deptno, empno, sal FROM emp e WHERE 2 > ( SELECT COUNT(e1.sal)

FROM emp e1 WHERE e.deptno = e1.deptno AND e.sal < e1.sal) ORDER BY 1, 3 DESC;

2. Query that will display the total no. of employees, and of that total the number who were hired in 1980, 1981, 1982, and 1983. Give appropriate column headings.

Total 1980 1981 1982 1983-------- ------------ ------------ --------- ------- 14 1 10 2 1

SELECT COUNT (*), COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'),'1980', empno)) "1980",COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1981', empno)) "1981",COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1982', empno)) "1982",COUNT (DECODE (TO_CHAR (hiredate, 'YYYY'), '1983', empno)) "1983"FROM emp;

3. Query for listing Deptno, ename, sal, SUM (sal in that dept): SELECT a.deptno, ename, sal, (SELECT SUM(sal) FROM emp b WHERE a.deptno = b.deptno)

FROM emp a ORDER BY a.deptno;

4. Create a matrix query to display the job, the salary for that job based on department number, and the total salary for that job for all departments, giving each column an appropriate heading.

SELECT job "Job", SUM (DECODE (deptno, 10, sal)) "Dept 10", SUM (DECODE (deptno, 20, sal)) "Dept 20", SUM (DECODE (deptno, 30, sal)) "Dept 30", SUM (sal) "Total" FROM emp GROUP BY job;

5. 4th Top Salary of all the employees: SELECT DEPTNO, ENAME, SAL FROM EMP A WHERE 3 = (SELECT COUNT (B.SAL)

FROM EMP B WHERE A.SAL < B.SAL) ORDER BY SAL DESC;

6. Retrieving the 5th row FROM a table: SELECT DEPTNO, ENAME, SAL FROM EMP WHERE ROWID =

(SELECT ROWID FROM EMP WHERE ROWNUM <= 5 MINUS SELECT ROWID FROM EMP WHERE ROWNUM < 5)

8. Eliminate duplicates rows in a table: DELETE FROM table_name A WHERE ROWID > (SELECT min (ROWID) FROM

table_name B WHERE A.col = B.col);

By A.G.Reddy

Page 63: Oracle Quick Reference

SQL Quick Reference 63 9. Displaying EVERY 4th row in a table: (If a table has 14 rows, 4,8,12 rows will be selected)

SELECT * FROM emp WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4) FROM emp);

10. Top N rows FROM a table : (Displays top 9 salaried people) SELECT ename, deptno, sal FROM (SELECT * FROM emp ORDER BY sal DESC)

WHERE ROWNUM < 10;

11. How does one count/sum RANGES of data values in a column? A value x will be between values y and z if GREATEST(x, y) = LEAST(x, z).

SELECT f2, COUNT(DECODE(greatest(f1,59), least(f1,100), 1, 0)) "Range 60-100", COUNT(DECODE(greatest(f1,30), least(f1, 59), 1, 0)) "Range 30-59", COUNT(DECODE(greatest(f1,29), least(f1, 0), 1, 0)) "Range 00-29" FROM my_table GROUP BY f2;

12. For equal size ranges it might be easier to calculate it with DECODE (TRUNC (value/range), 0, rate_0, 1, rate_1, ...).

SELECT ename "Name", sal "Salary", DECODE( TRUNC(sal/1000, 0), 0, 0.0, 1, 0.1, 2, 0.2, 3, 0.3) "Tax rate"

FROM emp;

13. How does one count different data values in a column? SELECT dno, SUM (DECODE (sex,'M', 1, 0)) MALE,

SUM (DECODE (sex,'F', 1, 0)) FEMALE, COUNT (DECODE (sex,'M', 1,'F', 1)) TOTAL

FROM t1 GROUP BY dno;

14. Query to get the product of all the values of a column: SELECT EXP(SUM(LN(col1))) FROM srinu;

15. Query to display only the duplicate records in a table: SELECT num FROM satyam GROUP BY num HAVING COUNT(*) > 1;

16. Query for getting the following output as many number of rows in the table:

**********

SELECT RPAD(DECODE(temp,temp,'*'),ROWNUM,'*') FROM srinu1;

By A.G.Reddy

Page 64: Oracle Quick Reference

SQL Quick Reference 64 19. SELECT Query for counting No of words:SELECT ename,NVL(LENGTH(REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ',' @'),' ',''))+1,1) word_lengthFROM emp;

Explanation:TRANSLATE (UPPER (RTRIM (ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ',' @') -- This will translate all the characters FROM A-Z including a single quote to a space. It will also translate a space to a @.

REPLACE (TRANSLATE (UPPER (RTRIM (ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ',' @'),' ','') -- This will replace every space with nothing in the above result.

LENGTH(REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ',' @'),' ',''))+1 -- This will give u the count of @ characters in the above result.

21. Query for removing all non-numeric: SELECT TRANSLATE(LOWER(ssn),'abcdefghijklmnopqrstuvwxyz- ','') FROM DUAL;

22. Query for translating a column values to INITCAP: SELECT TRANSLATE (INITCAP (temp),

SUBSTR (temp, INSTR (temp,'''') +1, 1), LOWER (SUBSTR (temp, INSTR (temp,'''') +1)))FROM srinu1;

26. Query for deleting alternate odd rows FROM a table : DELETE FROM srinu WHERE (ROWID,1) IN (SELECT ROWID, MOD(ROWNUM,2)

FROM srinu);

28. Alternate Query for DECODE function: SELECT case

WHEN sex = 'm' THEN 'male'WHEN sex = 'f' THEN 'female'ELSE 'unknown'END

FROM mytable;

29. Create table adding Constraint to a date field to SYSDATE or 3 months later: CREATE TABLE srinu(dt1 date DEFAULT SYSDATE, dt2 date,

CONSTRAINT check_dt2 CHECK ((dt2 >= dt1) AND (dt2 <= ADD_MONTHS (SYSDATE, 3)));

31. Query to get the last Sunday of any month: SELECT NEXT_DAY (LAST_DAY (TO_DATE ('26-10-2001','DD-MM-YYYY')) - 7,'sunday')

FROM DUAL;

By A.G.Reddy

Page 65: Oracle Quick Reference

SQL Quick Reference 65 33. Query to SELECT last N rows FROM a table:

SELECT empno FROM emp WHERE ROWID in(SELECT ROWID FROM empMINUSSELECT ROWID FROM emp WHERE ROWNUM <= (SELECT COUNT (*)-5 FROM emp));

35. Query to get the DB Name: SELECT name FROM v$database;

36. Getting the current default schema: SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

37. Query to get all the column names of a particular table: SELECT column_name FROM all_tab_columns WHERE TABLE_NAME = 'ORDERS';

38. How do I spool only the query result to a file in SQLPLUS:

Place the following lines of code in a file and execute the file in SQLPLUS:

set heading offset feedback offset colsep ' 'set termout offset verify offspool c:\srini.txtSELECT empno,ename FROM emp; /* Write your Query here */spool off

39. Query for getting the current SessionID: SELECT SYS_CONTEXT ('USERENV','SESSIONID') Session_ID FROM DUAL;

40. Query to display rows FROM m to n:To display rows 5 to 7:

SELECT DEPTNO, ENAME, SAL FROM EMP WHERE ROWID IN(SELECT ROWID FROM EMP WHERE ROWNUM <= 7

MINUSSELECT ROWID FROM EMP WHERE ROWNUM < 5);

OR

SELECT ename FROM emp GROUP BY ROWNUM, ename HAVING ROWNUM > 5 and ROWNUM < =7

41. Query to count no. Of columns in a table: SELECT COUNT(column_name) FROM user_tab_columns WHERE table_name =

'MYTABLE';

By A.G.Reddy

Page 66: Oracle Quick Reference

SQL Quick Reference 66 42. Differences between SQL and MS-Access:

Difference 1:Oracle: select name from table1 where name like 'k%';Access: select name from table1 where name like 'k*';

Difference 2:Access: SELECT TOP 2 name FROM Table1;Oracle: will not work there is no such TOP key word.

43. Columns of a table select column_name from user_tab_columns where TABLE_NAME = 'EMP' select column_name from all_tab_columns where TABLE_NAME = 'EMP' select column_name from dba_tab_columns where TABLE_NAME = 'EMP' select column_name from cols where TABLE_NAME = 'EMP'

44. Change SettingsOpen file oracle_home\plus32\glogin.sql andadd this set linesize 100set pagewidth 20and save the fileand exit from sql and reload then it will set it.

45. Table comparisonThe table in both the schemas should have exactly the same structure. The data init could be same or different a-b and b-a

select * from a.a minus select * from b.a and select * from b.a minus select * from a.a

46. Switching Columns Update tblname Set column1 = column2, Column2 = column1;

47. Replace and RoundI have the number e.g. 63,9823874012983 and I want to round it to 63,98 and at the same time

change the , to a . select round(replace('63,9823874012983',',','.'),2) from dual;

48. First date of the yearselect trunc(sysdate, 'y') from dual;

01-jan-2002

last year this month through a select statementselect add_months(sysdate, -12) from dual;05-APR-01

By A.G.Reddy

Page 67: Oracle Quick Reference

SQL Quick Reference 67 49. Current Week

select next_day(sysdate-7,'SUNDAY'), next_day(sysdate,'SATURDAY') from dual;

50. need to extract only the arithmetic operators (+, *, and +) so that I can use them in a query. How can I do this?

select replace(translate('1+2*30+40','01234',' '), ' ') from dual;

51. What is the difference between an "empty" value and a "null" value? An empty string is treated as a null value in Oracle.

52. Query to select only odd rows. SELECT * FROM emp WHERE (ROWID,1) IN (SELECT ROWID,MOD(ROWNUM,2)

FROM emp);

52. Query to select only even rows. SELECT * FROM emp WHERE (ROWID,0) IN (SELECT ROWID,MOD(ROWNUM,2)

FROM emp);

53. Query to select employee who have highest salary. SELECT ename FROM (SELECT * FROM emp ORDER BY sal DESC) WHERE

ROWNUM<2;

54. Query to find no of columns in a table. SELECT COUNT(column_name) user_tab_columns WHERE table_name=’emp’;

By A.G.Reddy

Page 68: Oracle Quick Reference

SQL Quick Reference 68

20. FREQUENTLY ASKED QUESTIONS

1. Difference between Char, Varchar and varchar22. What is view and its types3. Difference between sub query and correlated subquery4. Difference between Truncate , delete and drop5. Difference between Substr and Instr6. Difference between Translate and Replace7. Difference between Round and Trunc8. Difference between Ceil and Floor9. What is In line view10. what is Force View11. Explain Check Constraint12. Query to find nth max salary13. Query to find max salary of each Department14. Query to delete Duplicate rows15. When we delete a Table , view will work or not16. What are the Pseudo columns17. Query to retrieve Nth Row in a Table18. Query to ret rive first n rows19. Query to ret rive last n rows20. Query to retrieve records fro nth row to mth row21. Query to retrieve alternate rows22. Query to retrieve odd rows, even rows, last row, first row23. Query to find number of words in a string24. Query to select records according to the month25. Difference between DDL and DML 26. What is COMMIT , ROLLBACK and SAVE POINT 27. Query to select Employees who have joined in the last 5 years28. Query to select only duplicate rows29. What is Join, types of joins30. Query to select employee and their managers names31. What is set Operators32. Difference between WHERE,GROUP BY and HAVING33. Difference between Primary, Unique and Not null, Foreign key constrains34. Difference between Decode and Case35. What is INDEX36. What is SEQUENCE37. NULLIF Function.38. COALESCE Function.39. Use of Bitmap Index.40. Advantages and Disadvantages of Indexes.41. What is joining, types of joins.42. Join Methods.43. Can we update a complex view?

By A.G.Reddy

Page 69: Oracle Quick Reference

SQL Quick Reference 69

44. What is the difference between nvl and nvl2?45. What is schema?

A schema is a collection of logical structures of data, or schema objects. A schema is owned by a database user and has the same name as that user. Each user owns a single schema. Schema objects can be created and manipulated with SQL.

46. What is pragma?Pragmas are specially formatted comments. Pragmas can be used anywhere within your

source files

By A.G.Reddy

Page 70: Oracle Quick Reference

SQL Quick Reference 70

21. USER DICTIONARY TABLES

S.No Table Name Description of the table

1 USER_ALL_TABLESDescription of all object and relational tables owned by the user's

2 USER_ARGUMENTS Arguments in object accessible to the user3 USER_ASSOCIATIONS All assocations defined by the user

4 USER_AUDIT_OBJECTAudit trail records for statements concerning objects, specifically: table, cluster, view, index, sequence etc

5 USER_AUDIT_POLICIESAll fine grained auditing policies for objects in user schema

6 USER_AUDIT_POLICY_COLUMNSUsers fine grained auditing policy columns in the database

7 USER_AUDIT_SESSIONAll audit trail records concerning CONNECT and DISCONNECT

8 USER_AUDIT_STATEMENTAudit trail records concerninggrant, revoke, audit, noaudit and alter system

9 USER_AUDIT_TRAIL Audit trail entries relevant to the user10 USER_AWS Analytic Workspaces owned by the user

11 USER_AW_PSPagespaces in Analytic Workspaces owned by the user

12 USER_BASE_TABLE_MVIEWSAll materialized views with log(s) owned by the user in the database

13 USER_CATALOGTables, Views, Synonyms and Sequences owned by the user

14 USER_CHANGE_NOTIFICATION_REGSchange notification registrations for current user

15 USER_CLUSTERS Descriptions of user's own clusters16 USER_CLUSTER_HASH_EXPRESSIONS Hash functions for the user's hash clusters17 USER_CLU_COLUMNS Mapping of table columns to cluster columns

18 USER_COLL_TYPESDescription of the user's own named collection types

19 USER_COL_COMMENTSComments on columns of user's tables and views

20 USER_COL_PRIVSGrants on columns for which the user is the owner, grantor or grantee

21 USER_COL_PRIVS_MADEAll grants on columns of objects owned by the user

22 USER_COL_PRIVS_RECDGrants on columns for which the user is the grantee

23 USER_CONSTRAINTS Constraint definitions on user's own tables

24 USER_CONS_COLUMNSInformation about accessible columns in constraint definitions

25 USER_CONS_OBJ_COLUMNSList of types an object column or attribute is constrained to in the tables owned by the user

26 USER_DATAPUMP_JOBS Datapump jobs for current user

By A.G.Reddy

Page 71: Oracle Quick Reference

SQL Quick Reference 71 27 USER_DB_LINKS Database links owned by the user28 USER_DEPENDENCIES Dependencies to and from a users objects

29 USER_DIMENSIONSDescription of the dimension objects accessible to the DBA

30 USER_DIM_ATTRIBUTESRepresentation of the relationship between a dimension level anda functionally dependent column

31 USER_DIM_CHILD_OFRepresentaion of a 1:n hierarchical relationship between a pair of levels in a dimension

32 USER_DIM_HIERARCHIES Representation of a dimension hierarchy

33 USER_DIM_JOIN_KEYRepresentation of a join between two dimension tables.

34 USER_DIM_LEVELSDescription of dimension levels visible to DBA

35 USER_DIM_LEVEL_KEYRepresentations of columns of a dimension level

36 USER_ENCRYPTED_COLUMNSEncryption information on columns of tables owned by the user

37 USER_EPG_DAD_AUTHORIZATION DADs authorized to use the user's privileges

38 USER_ERRORSCurrent errors on stored objects owned by the user

39 USER_EVALUATION_CONTEXTS rule evaluation contexts owned by user40 USER_EVALUATION_CONTEXT_TABLES tables in user rule evaluation contexts41 USER_EVALUATION_CONTEXT_VARS variables in user rule evaluation contexts

42 USER_EXTENTSExtents comprising segments owned by the user

43 USER_EXTERNAL_LOCATIONSDescription of the user's external tables locations

44 USER_EXTERNAL_TABLES Description of the user's own external tables45 USER_FILE_GROUPS Details about file groups

46 USER_FILE_GROUP_EXPORT_INFODetails about export information of file group versions

47 USER_FILE_GROUP_FILES Details about file group files

48 USER_FILE_GROUP_TABLESDetails about the tables in the file group repository

49 USER_FILE_GROUP_TABLESPACESDetails about the transportable tablespaces in the file group repository

50 USER_FILE_GROUP_VERSIONS Details about file group versions

51 USER_FREE_SPACEFree extents in tablespaces accessible to the user

52 USER_HISTOGRAMS Synonym for USER_TAB_HISTOGRAMS53 USER_INDEXES Description of the user's own indexes54 USER_INDEXTYPES All user indextypes55 USER_INDEXTYPE_ARRAYTYPES All array types specified by the indextype56 USER_INDEXTYPE_COMMENTS Comments for user-defined indextypes57 USER_INDEXTYPE_OPERATORS All user indextype operators

58 USER_IND_COLUMNSCOLUMNs comprising user's INDEXes and INDEXes on user's TABLES

59 USER_IND_EXPRESSIONS Functional index expressions in user's indexes

By A.G.Reddy

Page 72: Oracle Quick Reference

SQL Quick Reference 72 and indexes on user's tables

60 USER_IND_STATISTICS Optimizer statistics for user's own indexes

61 USER_INTERNAL_TRIGGERSDescription of the internal triggers on the user's own tables

62 USER_JOBS All jobs owned by this user

63 USER_JOIN_IND_COLUMNSJoin Index columns comprising the join conditions

64 USER_LIBRARIES Description of the user's own libraries

65 USER_LOBSDescription of the user's own LOBs contained in the user's own tables

66 USER_LOG_GROUPS Log group definitions on user's own tables

67 USER_LOG_GROUP_COLUMNSInformation about columns in log group definitions

68 USER_METHOD_PARAMSDescription of method parameters of the user's own types

69 USER_METHOD_RESULTSDescription of method results of the user's own types

70 USER_MVIEWS All materialized views in the database

71 USER_MVIEW_AGGREGATESDescription of the materialized view aggregates created by the user

72 USER_MVIEW_ANALYSISDescription of the materialized views created by the user

73 USER_MVIEW_COMMENTSComments on materialized views owned by the user

74 USER_MVIEW_DETAIL_RELATIONSDescription of the materialized view detail tables of the materialized views created by the user

75 USER_MVIEW_JOINSDescription of a join between two columns in the WHERE clause of a materialized view created by the

76 USER_MVIEW_KEYSDescription of the columns that appear in the GROUP BY list of a materialized viewcreated by the u

77 USER_MVIEW_LOGS All materialized view logs owned by the user

78 USER_MVIEW_REFRESH_TIMESMaterialized views and their last refresh times for each master table that the user can look at

79 USER_NESTED_TABLESDescription of nested tables contained in the user's own tables

80 USER_NESTED_TABLE_COLS Columns of nested tables81 USER_OBJECTS Objects owned by the user82 USER_OBJECT_SIZE Sizes, in bytes, of various pl/sql objects83 USER_OBJECT_TABLES Description of the user's own object tables

84 USER_OBJ_AUDIT_OPTSAuditing options for user's own tables and views with atleast one option set

85 USER_OBJ_COLATTRSDescription of object columns and attributes contained in tables owned by the user

86 USER_OPANCILLARY All ancillary opertors defined by user

87 USER_OPARGUMENTSAll operator arguments of operators defined by user

88 USER_OPBINDINGS All binding functions or methods on operators

By A.G.Reddy

Page 73: Oracle Quick Reference

SQL Quick Reference 73 defined by the user

89 USER_OPERATORS All user operators90 USER_OPERATOR_COMMENTS Comments for user-defined operators91 USER_OUTLINES Stored outlines owned by the user92 USER_OUTLINE_HINTS Hints stored in outlines owned by the user93 USER_PARTIAL_DROP_TABS User tables with unused columns94 USER_PASSWORD_LIMITS Display password limits of the user

95 USER_PENDING_CONV_TABLESAll user's tables which are not upgraded to the latest type version

96 USER_PLSQL_OBJECT_SETTINGSCompiler settings of stored objects owned by the user

97 USER_POLICIESAll row level security policies for synonyms, tables, or views owned by the user

98 USER_POLICY_CONTEXTSAll policy driving context defined for synonyms, tables, or views in current schema

99 USER_POLICY_GROUPSAll policy groups defined for any synonym, table, or view

100 USER_PROCEDURES Description of the users own procedures

101 USER_PROXIESDescription of connections the user is allowed to proxy

102 USER_PUBLISHED_COLUMNSSource columns available for Change Data Capture

103 USER_QUEUES All queues owned by the user104 USER_QUEUE_SUBSCRIBERS queue subscribers under a user'schema105 USER_QUEUE_TABLES All queue tables created by the user106 USER_RECYCLEBIN User view of his recyclebin107 USER_REFRESH All the refresh groups

108 USER_REFRESH_CHILDRENAll the objects in refresh groups, where the user owns the refresh group

109 USER_REFSDescription of the user's own REF columns contained in the user's own tables

110 USER_REGISTERED_MVIEWSRemote materialized views of local tables currently using logs owned by the user

111 USER_REGISTERED_SNAPSHOTSRemote snapshots of local tables currently using logs owned by the user

112 USER_REPAUDIT_ATTRIBUTEInformation about attributes automatically maintained for replication

113 USER_REPAUDIT_COLUMNInformation about columns in all shadow tables for user's replicated tables

114 USER_REPCATLOGInformation about the current user's asynchronous administration requests

115 USER_REPCOLUMNReplicated columns for the current user's table in ascending order

116 USER_REPCOLUMN_GROUP All column groups of user's replicated tables

117 USER_REPDDLArguments that do not fit in a single repcat log record

118 USER_REPFLAVORSFlavors current user created for replicated object groups

119 USER_REPFLAVOR_COLUMNSReplicated columns from current user's tables in flavors

By A.G.Reddy

Page 74: Oracle Quick Reference

SQL Quick Reference 74 120 USER_REPFLAVOR_OBJECTS Replicated user objects in flavors

121 USER_REPGENERATEDObjects generated for the current user to support replication

122 USER_REPGENOBJECTSObjects generated for the current user to support replication

123 USER_REPGROUP Replication information about the current user

124 USER_REPGROUPED_COLUMNColumns in the all column groups of user's replicated tables

125 USER_REPGROUP_PRIVILEGESInformation about users who are registered for object group privileges

126 USER_REPKEY_COLUMNSPrimary columns for a table using column-level replication

127 USER_REPOBJECTReplication information about the current user's objects

128 USER_REPPARAMETER_COLUMNAll columns used for resolving conflicts in user's replicated tables

129 USER_REPPRIORITYValues and their corresponding priorities in user's priority groups

130 USER_REPPRIORITY_GROUP Information about user's priority groups

131 USER_REPPROPPropagation information about the current user's objects

132 USER_REPRESOLUTIONDescription of all conflict resolutions for user's replicated tables

133 USER_REPRESOLUTION_METHODAll conflict resolution methods accessible to the user

134 USER_REPRESOLUTION_STATISTICSStatistics for conflict resolutions for user's replicated tables

135 USER_REPRESOL_STATS_CONTROLInformation about statistics collection for conflict resolutions for user's replicated tables

136 USER_REPSCHEMAN-way replication information about the current user

137 USER_REPSITESN-way replication information about the current user

138 USER_RESOURCE_LIMITS Display resource limit of the user

139 USER_RESUMABLEResumable session information for current user

140 USER_REWRITE_EQUIVALENCESDescription of all rewrite equivalence owned by the user

141 USER_ROLE_PRIVS Roles granted to current user

142 USER_RSRC_CONSUMER_GROUP_PRIVSSwitch privileges for consumer groups for the user

143 USER_RSRC_MANAGER_SYSTEM_PRIVSsystem privileges for the resource manager for the user

144 USER_RULES Rules owned by the user

145 USER_RULESETSRulesets owned by the user: maintained for backward compatibility

146 USER_RULE_SETS Rule sets owned by the user147 USER_RULE_SET_RULES Rules in user rule sets

148 USER_SCHEDULER_CHAINSAll scheduler chains owned by the current user

By A.G.Reddy

Page 75: Oracle Quick Reference

SQL Quick Reference 75

149 USER_SCHEDULER_CHAIN_RULESAll rules from scheduler chains owned by the current user

150 USER_SCHEDULER_CHAIN_STEPSAll steps of scheduler chains owned by the current user

151 USER_SCHEDULER_JOBS All scheduler jobs in the database

152 USER_SCHEDULER_JOB_ARGSAll arguments with set values of all scheduler jobs in the database

153 USER_SCHEDULER_JOB_LOG Logged information for all scheduler jobs154 USER_SCHEDULER_JOB_RUN_DETAILS The details of a job run155 USER_SCHEDULER_PROGRAMS Scheduler programs owned by the current user

156 USER_SCHEDULER_PROGRAM_ARGSAll arguments of all scheduler programs in the database

157 USER_SCHEDULER_RUNNING_CHAINSAll steps of chains being run by jobs owned by the current user

158 USER_SCHEDULER_SCHEDULES Schedules belonging to the current user159 USER_SECONDARY_OBJECTS All secondary objects for domain indexes

160 USER_SEC_RELEVANT_COLSSecurity Relevant columns of VPD policies for tables or views owned by the user

161 USER_SEGMENTS Storage allocated for all database segments162 USER_SEQUENCES Description of the user's own SEQUENCEs163 USER_SNAPSHOTS Snapshots the user can look at164 USER_SNAPSHOT_LOGS All snapshot logs owned by the user

165 USER_SNAPSHOT_REFRESH_TIMESSynonym for USER_MVIEW_REFRESH_TIMES

166 USER_SOURCE Source of stored objects accessible to the user

167 USER_SOURCE_TABLESSource tables available for Change Data Capture

168 USER_SQLJ_TYPES Description of the user's own types

169 USER_SQLJ_TYPE_ATTRSDescription of attributes of the user's own types

170 USER_SQLJ_TYPE_METHODSDescription of methods of the user's own types

171 USER_SQLSET_DEFINITIONS Synonym for USER_SQLSET

172 USER_STORED_SETTINGSParameter settings for objects owned by the user

173 USER_SUBSCRIBED_COLUMNS Change Data Capture subscribed columns174 USER_SUBSCRIBED_TABLES Change Data Capture subscribed tables175 USER_SUBSCRIPTIONS Change Data Capture subscriptions

176 USER_SUMMARIESDescription of the summaries created by the user

177 USER_SYNONYMS The user's private synonyms178 USER_SYS_PRIVS System privileges granted to current user179 USER_TABLES Description of the user's own relational tables180 USER_TABLESPACES Description of accessible tablespaces181 USER_TAB_COLS Columns of user's tables, views and clusters182 USER_TAB_COLUMNS Columns of user's tables, views and clusters183 USER_TAB_COL_STATISTICS Columns of user's tables, views and clusters

184 USER_TAB_COMMENTSComments on the tables and views owned by the user

185 USER_TAB_HISTOGRAMS Histograms on columns of user's tables By A.G.Reddy

Page 76: Oracle Quick Reference

SQL Quick Reference 76 186 USER_TAB_MODIFICATIONS Information regarding modifications to tables

187 USER_TAB_PRIVSGrants on objects for which the user is the owner, grantor or grantee

188 USER_TAB_PRIVS_MADE All grants on objects owned by the user

189 USER_TAB_PRIVS_RECDGrants on objects for which the user is the grantee

190 USER_TAB_STATISTICS Optimizer statistics of the user's own tables191 USER_TAB_STATS_HISTORY History of table statistics modifications192 USER_TRIGGERS Triggers owned by the user193 USER_TRIGGER_COLS Column usage in user's triggers194 USER_TS_QUOTAS Tablespace quotas for the user195 USER_TUNE_MVIEW tune_mview catalog view owned by the user196 USER_TYPES Description of the user's own types

197 USER_TYPE_ATTRSDescription of attributes of the user's own types

198 USER_TYPE_METHODSDescription of methods of the user's own types

199 USER_TYPE_VERSIONS Description of each version of the user's types200 USER_UNUSED_COL_TABS User tables with unused columns201 USER_UPDATABLE_COLUMNS Description of updatable columns202 USER_USERS Information about the current user

203 USER_USTATSAll statistics on tables or indexes owned by the user

204 USER_VARRAYSDescription of varrays contained in the user's own tables

205 USER_VIEWS Description of the user's own views

206 USER_WARNING_SETTINGSWarning Parameter settings for objects owned by the user

207 USER_XML_INDEXESDescription of the user's own XMLType indexes

208 USER_XML_SCHEMASDescription of XML Schemas registered by the user

209 USER_XML_TABLESDescription of the user's own XMLType tables

210 USER_XML_TAB_COLSDescription of the user's own XMLType tables

211 USER_XML_VIEWSDescription of the user's own XMLType views

212 USER_XML_VIEW_COLSDescription of the user's own XMLType views

.

By A.G.Reddy