Oracle

:
SQL Quick Reference
By: Gajendra Reddy. A

SQL Quick Reference

2

CONTENTS _______________________________________________________ _
1.

DATABASE CONCEPTS • 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 TABLES USED IN THIS BOOK COMPONENTS OF SQL • Data definition language. • Data Manipulation language. • Data Query language. • Data Control language. • Transaction Control language. SET OPERATIONS • Union all • Union • Intersect • Minus • The IN Function • The EXISTS Function 5. SQL OPERATORS • Mathematical • Logical • Range

5

2. 3.

10 11

4.

17

19

By A.G.Reddy

SQL Quick Reference

3

• • • • • • • • • • • •

6. FUNCTIONS Number functions Character function Date functions Conversion Functions Other Functions 7. PSEUDO COLUMNS Level Row number Rowid User UID Sysdate Dual Table 8. AGGREGATE FUNCTIONS • Max • Min • Sum • Avg • Count 9. ANALYTICAL FUNCTIONS 10. GROUP BY, HAVING AND ORDER BY CLAUSES 11. INTEGRETY CONSTRAINTS • 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

21

26

27

29 31 32

By A.G.Reddy

SQL Quick Reference

4

12. PERFORMANCE TUNING • Views • Indexes • Sequences 13. MATERIALIZED VIEWS 14. JOINS • 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 16 CASE EXPRESSIONS • Simple Case Statement • Searched Case Statement • NULL IF Function • COALESCE Function 17. MISCELLANIOUS TOPICS • 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 19. IMPORTANT SQL QUERIES 20. FREQUENTLY ASKED QUESTIONS

38

44 48

54 56

57

60 62 68
By A.G.Reddy

SQL Quick Reference

5

21. USER DICTIONARY TABLES

70

1. DATABASE CONCEPTS
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
By A.G.Reddy

SQL Quick Reference

6

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.

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 nunnull field constraint that prevents null values in a specific table column. Rule 4: Dynamic On-Line Catalog Based on the Relational Model
By A.G.Reddy

SQL Quick Reference

7

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 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

By A.G.Reddy

SQL Quick Reference

8

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:
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 Forms The 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:
By A.G.Reddy

SQL Quick Reference

9

• 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): 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
By A.G.Reddy

SQL Quick Reference

10

DATABASE OBJECTS
Tables Stored Procedures Indexes Views User Defined Functions Columns Triggers Foreign Keys User Defined Data Types Primary Keys Default And Check Constraints Variables

2. TABLES USED IN THIS BOOK
SQL> select * from EMP;
EMPNO ENAME JOB SAL MGR COMM HIREDATE DEPTNO ----------------------------------------------------------------------------------------------------------------------------------------------7369 SMITH CLERK 900 7902 17-DEC-80 20 7499 LLEN SALESMAN 1600 7698 300 20-FEB-81 30 7521 WARD SALESMAN 1250 7698 500 22-FEB-81 30 7566 JONES MANAGER 2975 7839 02-APR-81 20 7654 MARTIN SALESMAN 1250 7698 1400 28-SEP-81 30 7698 BLAKE MANAGER 2850 7839 01-MAY-81 30 7782 CLERK MANAGER 2450 7839 09-JUN-81 10 7788 SCOTT ANALYST 4000 7566 19-APR-87 20 7839 KING PRESIDENT 5000 17-NOV-81 10 7844 TURNER SALESMAN 1500 7698 0 08-SEP-81 30 7876 DAMS CLERK 1100 7788 23-MAY-87 20 7900 JAMES CLERK 950 7698 03-DEC-81 30 7902 FORD ANALYST 4000 7566 03-DEC-81 20 7934 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

By A.G.Reddy

SQL Quick Reference

11

3. COMPONENTS OF SQL
DATA DEFINITION LANGUAGE:
Set of SQL commands used to create, modify and delete database structure is called data definition language. Create Alter Drop Truncate

DDL Commands

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.
By A.G.Reddy

SQL Quick Reference

12

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));

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:
By A.G.Reddy

SQL Quick Reference

13

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.

DML Commands

Insert Update Delete

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.
• • •

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:
By A.G.Reddy

SQL Quick Reference

14

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 1 2 3 DELETE TRUNCATE DELETE is a DML command TRUNCATE is a DDL command Can be rolled back We can use WHERE clause Cannot be rolled back We can't use WHERE clause

DATA QUERY LANGUAGE:
Used to retrieve data from tables.

DQL Commands

Select

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;
By A.G.Reddy

SQL Quick Reference

15

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

DCL Commands

Grant Revoke

The following things can be GRANTED TO or REVOKED FROM a user or role: • ALTER • SELECT • 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:
By A.G.Reddy

SQL Quick Reference •

16

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 Rollback Save Point

TCL Commands

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. • 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;

By A.G.Reddy

SQL Quick Reference

17

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 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:

Union All Union

Set Operators:

Minus Intersect

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.
By A.G.Reddy

SQL Quick Reference

18

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

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.

By A.G.Reddy

SQL Quick Reference

19

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 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

Mathematical Logical Range

SQL Arithmetic Operators: Operator Example Result + 7+7 = 14 7-7 =0 * 7*7 = 49 / 7/7 =1 % 7%7 =0

Definition Addition Subtraction Multiplication Division Modulus

By A.G.Reddy

SQL Quick Reference

20

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 < 7 < 4 7 less than 4? > 7 > 4 Greater than 4? <= 7 <= 11 Is 7 less than or equal to 11? >= 7 >= 11 Are 7 greater than or equal to 11? SQL Equality Operators: Operator Example = <> 5=5 7 <> 2

Result False True True False

Defined

Result True True

Are 5 equal to 5? Are 7 not equal to 2?

SQL Logical Operators: Defined Operator AND OR

Example

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

By A.G.Reddy

SQL Quick Reference

21

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. 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
1 2 3 4 5

Function Name
ABS(n) CEIL(n) FLOOR(n) MOD(m,n) POWER(m,n)

Description
ABS returns the absolute value of n. CEIL returns smallest integer greater than or equal to n. FLOOR returns largest integer equal to or less than n. MOD returns the remainder of m divided by n. Returns m if n is 0. 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

Example
ABS(-9)=9 CEIL(9.5)=10 FLOOR(10.5)=10 MOD(7,5)=2 POWER(3,3)=27

By A.G.Reddy

SQL Quick Reference

22

6 ROUND(m,n)

7

TRUNC(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. 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.

ROUND(10.586,2) =10.59 ROUND(10.586, -2) =200 TRUNC(10.586,2) =10.58 TRUNC(10.586, -2)=100

8

SGN(n)

9 10 11 12

SQRT(n) SIN(n) COS(n) TAN(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. SQRT returns the square root of n.

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

SIN returns the sine of n (an angle SIN(30*3.142/180) expressed in radians). = COS returns the cosine of n (an angle COS(30*3.142/180) expressed in radians). = TAN returns the tangent of n (an angle TAN(30*3.142/180) expressed in radians). =

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
1 2 3 4

Function Name
ASCII

Description
Returns the ASCII code of a character. Returns the character associated with the specified collating code. Sets the first letter of each word to uppercase. All other letters are set to lowercase. Returns the location in a string of the specified substring.
By A.G.Reddy

CHR
INITCAP INSTR

SQL Quick Reference LENGTH

23

Returns the length of a string. Converts all letters to lowercase. Pads a string on the left with the specified characters. Pads a string on the right with the specified characters. Trims the left side of a string of all specified characters. Trims the right side of a string of all specified characters. Returns the "soundex" of a string.

5
LOWER

6
LPAD

7 8 9 10 11

RPAD LTRIM RTRIM SOUNDEX

12 13 14 15 16 17

SUBSTR UPPER TRANSLATE REPLACE TRIM CONCAT

Returns the specified portion of a string. Converts all letters in the string to uppercase. Translates single characters in a string to different characters. Replaces a character sequence in a string with a different set of characters. TRIM enables you to trim leading or trailing characters (or both) from a character string. 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
1 2 3 4 5 6

Function Name
ADD_MONTHS LAST_DAY MONTHS_ BETWEEN NEW_TIME NEXT_DAY ROUND

Description
Adds the specified number of months to a date. Returns the last day in the month of the specified date. Calculates the number of months between two dates. Returns the date/time value, with the time shifted as requested by the specified time zones. Returns the date of the first weekday specified that is later than the date. Returns the date rounded by the specified format unit.
By A.G.Reddy

SQL Quick Reference

24

7 8

SYSDATE TRUNC

Returns the current date and time in the Oracle Server. 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:

S.No
1

Function Name

Description
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: 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. TO_CHAR (character) converts NCHAR, NVARCHAR2, CLOB, or NCLOB data to the database character set. 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. 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
By A.G.Reddy

TO_CHAR (datetime)

2

TO_CHAR (number)

3

TO_CHAR (character)

4

TO_DATE

TO_NUMBER

5

SQL Quick Reference

25

specified by the optional format model fmt. 6
CAST

7 8

ASCIISTR

TO_TIMESTAMP

CAST converts one built-in datatype or collection-typed value into another built-in datatype or collection-typed value. 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. 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:
S.No
1 2 3 4
NVL

Function Name

Description
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. GREATEST returns the greatest of the list of exprs LEAST returns the least of the list of exprs. 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. 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. NULLIF 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. 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.

DECODE GREATEST LEAST

5

COALESCE

6

NULLIF

7

NVL2

By A.G.Reddy

SQL Quick Reference

26

7. PSEUDO COLUMNS
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:
By A.G.Reddy

SQL Quick Reference

27

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
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 Min Sum Avg Count

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.
By A.G.Reddy

SQL Quick Reference • SELECT MIN ( sal ) FROM emp; • SELECT MIN ( DISTINCT sal ) FROM emp; • SELECT MIN( ALL sal ) FROM emp;

28

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. • 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;

By A.G.Reddy

SQL Quick Reference

29

9. ANALYTICAL FUNCTIONS
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.

By A.G.Reddy

SQL Quick Reference

30

 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. • employees; Select rank () over (order by salary desc) rk, salary from

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. 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. • employees; select dense_rank() over(order by salary desc) rk,salary from

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
By A.G.Reddy

SQL Quick Reference

31

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 COVAR_POP COUNT FIRST LAG LAST_VALUE MAX NTILE PERCENTILE_CONT RATIO_TO_REPORT STDDEV STDDEV_SAMP VAR_POP VARIANCE CORR COVAR_SAMP CUME_DIST FIRST_VALUE LAST LEAD MIN PERCENT_RANK PERCENTILE_DISC REGR_ (Linear Regression) STDDEV_POP SUM VAR_SAMP

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.
By A.G.Reddy

SQL Quick Reference

32

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;

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 Primary enforced by the appropriate can be Key constraints. Microsoft SQL Server supports the followingUnique Key constraints

Foreign Key Not Null Check Default
By A.G.Reddy

SQL Quick Reference

33

Integrity constraints

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

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:
By A.G.Reddy

SQL Quick Reference 34 • 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:
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:

By A.G.Reddy

SQL Quick Reference

35

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:
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.
By A.G.Reddy

SQL Quick Reference

36

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:
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) );
By A.G.Reddy

SQL Quick Reference

37

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.
 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;
By A.G.Reddy

SQL Quick Reference

38

12. PERFORMANCE TUNING
INDEXES:
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 table 3. 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.
By A.G.Reddy

SQL Quick Reference

39

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). • Data warehousing. • Time-series applications. Types of Indexes: S.No Index Name Duplicate / Unique Index Simple Index Composite Index Reverse Key Index Bitmap Index Function Based Index

TYPES OF INDEXES

1. 2. 3. 4. 5. 6.

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
By A.G.Reddy

SQL Quick Reference

40

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. 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 twodimensional 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.
By A.G.Reddy

SQL Quick Reference • CREATE BITMAP INDEX i_deptno On emp(deptno);

41

 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;

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 1 NAME OF THE VIEW READ ONLY VIEW DESCRIPTION a view is used to only to look at the table data then it is called readonlyview. if a view is used to look at the table data as well as INSERT, UPDATE and DELETE table data is called updatable views.
By A.G.Reddy

2

UPDATABLE VIEW

SQL Quick Reference

42

3 4

INLINE VIEW FORCE 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. 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. • 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
By A.G.Reddy

SQL Quick Reference

43

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 ---------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);
By A.G.Reddy

SQL Quick Reference

44

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 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:
By A.G.Reddy

SQL Quick Reference

45

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 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. Readonly 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 AS SELECT * FROM hr.employees@orc1.world;
Advantages:

• There is no possibility for conflicts as they cannot be updated. • Complex materialized views are supported 2). Updateable materialized views:
By A.G.Reddy

SQL Quick Reference

46

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 hr.departments@orc1.world;
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: 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
By A.G.Reddy

SQL Quick Reference

47

• Enable Disconnected Computing Ease Network Loads If 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. 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 Environment Deployment 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 Subsetting Materialized 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 Computing
By A.G.Reddy

SQL Quick Reference

48

Materialized 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 ondemand 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.  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.
By A.G.Reddy

SQL Quick Reference

49

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 1. 2. 3.

Join Method
Inner/natural/Equi Joins Outer Join

Sub Type
----Left Outer join Right Outer Join Full Outer Join -----

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.
By A.G.Reddy

SQL Quick Reference

50

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:
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.

By A.G.Reddy

SQL Quick Reference 51  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. Figure shows the execution plan for this statement using a nested loops join:
• SELECT * FROM emp, dept WHERE emp.deptno = dept.deptno;

By A.G.Reddy

SQL Quick Reference

52

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;

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.
By A.G.Reddy

SQL Quick Reference

53

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;

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 rulebased 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.
By A.G.Reddy

SQL Quick Reference

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

Figure shows the execution plan for this statement using a hash join:

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.

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;
By A.G.Reddy

SQL Quick Reference 55 • 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);

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 =
By A.G.Reddy

SQL Quick Reference

56

(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.

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;
By A.G.Reddy

SQL Quick Reference

57

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;

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 ALL INTO 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_date FROM 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.
By A.G.Reddy

SQL Quick Reference

58

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

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 ---------1 2 4 8 SEX ----M F M

SQL> SELECT * FROM T2; SNO SEX ---------- ----1 F By A.G.Reddy

SQL Quick Reference 3 F 4 M 6 H SQL>MERGE INTO T1 A 1. USING (SELECT SNO, SEX FROM T2) B 2. ON (A.SNO=B.SNO) 3. WHEN MATCHED THEN 4. UPDATE SET A.SEX=B.SEX 5. WHEN NOT MATCHED THEN INSERT VALUES (B.SNO, B.SEX); SQL> select * from t1; SNO S ---------- 1F 2F 4M 8M 6H 3F

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 char, varchar2 char, varchar2 number X X number X X
By A.G.Reddy

FROM datetime / interval X raw X rowid, urowid X nchar, nvarchar2

SQL Quick Reference

60

datetime / interval raw rowid, urowid nchar, nvarchar2

X X X X

X X 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.

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
By A.G.Reddy

SQL Quick Reference 61 • 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. 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 database 2) adding new data type such as BLOB/CLOB 3) new administrative options like moving tables between tablespaces 4) many NEW dbms packages 5) writing JAVA code inside Oracle 6) passing parameters to sp with the NOCOPY Option 7) smart sql loader options 8) can work with array types 9) 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.
By A.G.Reddy

SQL Quick Reference

62

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
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 -------14 • 1980 -----------1 1981 -----------10 1982 --------2 1983 ------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; By A.G.Reddy

SQL Quick Reference

63

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);

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; By A.G.Reddy

SQL Quick Reference

64

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;

19. SELECT Query for counting No of words:
SELECT ename, NVL(LENGTH(REPLACE(TRANSLATE(UPPER(RTRIM(ename)),'ABCDEFGHIJKLMNOPQRSTU VWXYZ'' ',' @'),' ',''))+1,1) word_length FROM 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)),'ABCDEFGHIJKLMNOPQRSTUVWX YZ'' ',' @'),' ',''))+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; By A.G.Reddy

SQL Quick Reference

65

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;

33. Query to SELECT last N rows FROM a table:
• SELECT empno FROM emp WHERE ROWID in (SELECT ROWID FROM emp MINUS SELECT 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 off set feedback off set colsep ' ' set termout off By A.G.Reddy

SQL Quick Reference set verify off spool c:\srini.txt SELECT empno,ename FROM emp; /* Write your Query here */ spool off

66

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 MINUS SELECT ROWID FROM EMP WHERE ROWNUM < 5); SELECT ename FROM emp GROUP BY ROWNUM, ename HAVING ROWNUM > 5 and ROWNUM < =7

OR •

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

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' Open file oracle_home\plus32\glogin.sql and add this set linesize 100 set pagewidth 20 and save the file and exit from sql and reload then it will set it.

44. Change Settings

45. Table comparison
By A.G.Reddy

SQL Quick Reference The table in both the schemas should have exactly the same structure. The data in it could be same or different

67

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 Round
I 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 year
select trunc(sysdate, 'y') from dual; 01-jan-2002 last year this month through a select statement select add_months(sysdate, -12) from dual; 05-APR-01

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; By A.G.Reddy

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

20. FREQUENTLY ASKED QUESTIONS
Difference between Char, Varchar and varchar2 What is view and its types Difference between sub query and correlated subquery Difference between Truncate , delete and drop Difference between Substr and Instr Difference between Translate and Replace Difference between Round and Trunc Difference between Ceil and Floor 9. What is In line view 10. what is Force View 11. Explain Check Constraint 12. Query to find nth max salary 13. Query to find max salary of each Department 14. Query to delete Duplicate rows 15. When we delete a Table , view will work or not 16. What are the Pseudo columns 17. Query to retrieve Nth Row in a Table 18. Query to ret rive first n rows 19. Query to ret rive last n rows
1. 2. 3. 4. 5. 6. 7. 8. By A.G.Reddy

SQL Quick Reference 20. Query to retrieve records fro nth row to mth row

69

21. Query to retrieve alternate rows 22. Query to retrieve odd rows, even rows, last row, first row 23. Query to find number of words in a string 24. Query to select records according to the month 25. 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 years 28. Query to select only duplicate rows 29. What is Join, types of joins 30. Query to select employee and their managers names 31. What is set Operators 32. Difference between WHERE,GROUP BY and HAVING 33. Difference between Primary, Unique and Not null, Foreign key constrains 34. Difference between Decode and Case 35. What is INDEX 36. What is SEQUENCE 37. 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? 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

SQL Quick Reference

70

21. USER DICTIONARY TABLES
S.N o
1 2 3 4 5 6 7 8 9 10 11

Table Name
USER_ALL_TABLES USER_ARGUMENTS USER_ASSOCIATIONS USER_AUDIT_OBJECT USER_AUDIT_POLICIES USER_AUDIT_POLICY_COLUMNS USER_AUDIT_SESSION USER_AUDIT_STATEMENT USER_AUDIT_TRAIL USER_AWS USER_AW_PS

Description of the table
Description of all object and relational tables owned by the user's Arguments in object accessible to the user All assocations defined by the user Audit trail records for statements concerning objects, specifically: table, cluster, view, index, sequence etc All fine grained auditing policies for objects in user schema Users fine grained auditing policy columns in the database All audit trail records concerning CONNECT and DISCONNECT Audit trail records concerninggrant, revoke, audit, noaudit and alter system Audit trail entries relevant to the user Analytic Workspaces owned by the user Pagespaces in Analytic Workspaces owned by By A.G.Reddy

SQL Quick Reference 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

71 the user All materialized views with log(s) owned by USER_BASE_TABLE_MVIEWS the user in the database Tables, Views, Synonyms and Sequences USER_CATALOG owned by the user change notification registrations for current USER_CHANGE_NOTIFICATION_REGS user USER_CLUSTERS Descriptions of user's own clusters USER_CLUSTER_HASH_EXPRESSIONS Hash functions for the user's hash clusters USER_CLU_COLUMNS Mapping of table columns to cluster columns Description of the user's own named USER_COLL_TYPES collection types Comments on columns of user's tables and USER_COL_COMMENTS views Grants on columns for which the user is the USER_COL_PRIVS owner, grantor or grantee All grants on columns of objects owned by the USER_COL_PRIVS_MADE user Grants on columns for which the user is the USER_COL_PRIVS_RECD grantee USER_CONSTRAINTS Constraint definitions on user's own tables Information about accessible columns in USER_CONS_COLUMNS constraint definitions List of types an object column or attribute is USER_CONS_OBJ_COLUMNS constrained to in the tables owned by the user USER_DATAPUMP_JOBS Datapump jobs for current user USER_DB_LINKS Database links owned by the user USER_DEPENDENCIES Dependencies to and from a users objects Description of the dimension objects USER_DIMENSIONS accessible to the DBA Representation of the relationship between a USER_DIM_ATTRIBUTES dimension level anda functionally dependent column Representaion of a 1:n hierarchical USER_DIM_CHILD_OF relationship between a pair of levels in a dimension USER_DIM_HIERARCHIES Representation of a dimension hierarchy Representation of a join between two USER_DIM_JOIN_KEY dimension tables. Description of dimension levels visible to USER_DIM_LEVELS DBA Representations of columns of a dimension USER_DIM_LEVEL_KEY level Encryption information on columns of tables USER_ENCRYPTED_COLUMNS owned by the user USER_EPG_DAD_AUTHORIZATION DADs authorized to use the user's privileges Current errors on stored objects owned by the USER_ERRORS user USER_EVALUATION_CONTEXTS rule evaluation contexts owned by user USER_EVALUATION_CONTEXT_TABLES tables in user rule evaluation contexts By A.G.Reddy

SQL Quick Reference 41 USER_EVALUATION_CONTEXT_VARS 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 USER_EXTENTS USER_EXTERNAL_LOCATIONS USER_EXTERNAL_TABLES USER_FILE_GROUPS USER_FILE_GROUP_EXPORT_INFO USER_FILE_GROUP_FILES USER_FILE_GROUP_TABLES USER_FILE_GROUP_TABLESPACES USER_FILE_GROUP_VERSIONS USER_FREE_SPACE USER_HISTOGRAMS USER_INDEXES USER_INDEXTYPES USER_INDEXTYPE_ARRAYTYPES USER_INDEXTYPE_COMMENTS USER_INDEXTYPE_OPERATORS USER_IND_COLUMNS USER_IND_EXPRESSIONS USER_IND_STATISTICS USER_INTERNAL_TRIGGERS USER_JOBS USER_JOIN_IND_COLUMNS USER_LIBRARIES USER_LOBS USER_LOG_GROUPS USER_LOG_GROUP_COLUMNS USER_METHOD_PARAMS USER_METHOD_RESULTS USER_MVIEWS USER_MVIEW_AGGREGATES USER_MVIEW_ANALYSIS USER_MVIEW_COMMENTS

72 variables in user rule evaluation contexts Extents comprising segments owned by the user Description of the user's external tables locations Description of the user's own external tables Details about file groups Details about export information of file group versions Details about file group files Details about the tables in the file group repository Details about the transportable tablespaces in the file group repository Details about file group versions Free extents in tablespaces accessible to the user Synonym for USER_TAB_HISTOGRAMS Description of the user's own indexes All user indextypes All array types specified by the indextype Comments for user-defined indextypes All user indextype operators COLUMNs comprising user's INDEXes and INDEXes on user's TABLES Functional index expressions in user's indexes and indexes on user's tables Optimizer statistics for user's own indexes Description of the internal triggers on the user's own tables All jobs owned by this user Join Index columns comprising the join conditions Description of the user's own libraries Description of the user's own LOBs contained in the user's own tables Log group definitions on user's own tables Information about columns in log group definitions Description of method parameters of the user's own types Description of method results of the user's own types All materialized views in the database Description of the materialized view aggregates created by the user Description of the materialized views created by the user Comments on materialized views owned by the user By A.G.Reddy

SQL Quick Reference 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 USER_MVIEW_DETAIL_RELATIONS USER_MVIEW_JOINS USER_MVIEW_KEYS USER_MVIEW_LOGS USER_MVIEW_REFRESH_TIMES USER_NESTED_TABLES USER_NESTED_TABLE_COLS USER_OBJECTS USER_OBJECT_SIZE USER_OBJECT_TABLES USER_OBJ_AUDIT_OPTS USER_OBJ_COLATTRS USER_OPANCILLARY USER_OPARGUMENTS USER_OPBINDINGS USER_OPERATORS USER_OPERATOR_COMMENTS USER_OUTLINES USER_OUTLINE_HINTS USER_PARTIAL_DROP_TABS USER_PASSWORD_LIMITS USER_PENDING_CONV_TABLES USER_PLSQL_OBJECT_SETTINGS USER_POLICIES USER_POLICY_CONTEXTS USER_POLICY_GROUPS USER_PROCEDURES USER_PROXIES USER_PUBLISHED_COLUMNS USER_QUEUES USER_QUEUE_SUBSCRIBERS

73 Description of the materialized view detail tables of the materialized views created by the user Description of a join between two columns in the WHERE clause of a materialized view created by the Description of the columns that appear in the GROUP BY list of a materialized viewcreated by the u All materialized view logs owned by the user Materialized views and their last refresh times for each master table that the user can look at Description of nested tables contained in the user's own tables Columns of nested tables Objects owned by the user Sizes, in bytes, of various pl/sql objects Description of the user's own object tables Auditing options for user's own tables and views with atleast one option set Description of object columns and attributes contained in tables owned by the user All ancillary opertors defined by user All operator arguments of operators defined by user All binding functions or methods on operators defined by the user All user operators Comments for user-defined operators Stored outlines owned by the user Hints stored in outlines owned by the user User tables with unused columns Display password limits of the user All user's tables which are not upgraded to the latest type version Compiler settings of stored objects owned by the user All row level security policies for synonyms, tables, or views owned by the user All policy driving context defined for synonyms, tables, or views in current schema All policy groups defined for any synonym, table, or view Description of the users own procedures Description of connections the user is allowed to proxy Source columns available for Change Data Capture All queues owned by the user queue subscribers under a user'schema By A.G.Reddy

SQL Quick Reference 105 USER_QUEUE_TABLES 106 USER_RECYCLEBIN 107 USER_REFRESH 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 USER_REFRESH_CHILDREN USER_REFS USER_REGISTERED_MVIEWS USER_REGISTERED_SNAPSHOTS USER_REPAUDIT_ATTRIBUTE USER_REPAUDIT_COLUMN USER_REPCATLOG USER_REPCOLUMN USER_REPCOLUMN_GROUP USER_REPDDL USER_REPFLAVORS USER_REPFLAVOR_COLUMNS USER_REPFLAVOR_OBJECTS USER_REPGENERATED USER_REPGENOBJECTS USER_REPGROUP USER_REPGROUPED_COLUMN USER_REPGROUP_PRIVILEGES USER_REPKEY_COLUMNS USER_REPOBJECT USER_REPPARAMETER_COLUMN USER_REPPRIORITY USER_REPPRIORITY_GROUP USER_REPPROP USER_REPRESOLUTION USER_REPRESOLUTION_METHOD

74 All queue tables created by the user User view of his recyclebin All the refresh groups All the objects in refresh groups, where the user owns the refresh group Description of the user's own REF columns contained in the user's own tables Remote materialized views of local tables currently using logs owned by the user Remote snapshots of local tables currently using logs owned by the user Information about attributes automatically maintained for replication Information about columns in all shadow tables for user's replicated tables Information about the current user's asynchronous administration requests Replicated columns for the current user's table in ascending order All column groups of user's replicated tables Arguments that do not fit in a single repcat log record Flavors current user created for replicated object groups Replicated columns from current user's tables in flavors Replicated user objects in flavors Objects generated for the current user to support replication Objects generated for the current user to support replication Replication information about the current user Columns in the all column groups of user's replicated tables Information about users who are registered for object group privileges Primary columns for a table using columnlevel replication Replication information about the current user's objects All columns used for resolving conflicts in user's replicated tables Values and their corresponding priorities in user's priority groups Information about user's priority groups Propagation information about the current user's objects Description of all conflict resolutions for user's replicated tables All conflict resolution methods accessible to By A.G.Reddy

SQL Quick Reference 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

75 the user Statistics for conflict resolutions for user's USER_REPRESOLUTION_STATISTICS replicated tables Information about statistics collection for USER_REPRESOL_STATS_CONTROL conflict resolutions for user's replicated tables N-way replication information about the USER_REPSCHEMA current user N-way replication information about the USER_REPSITES current user USER_RESOURCE_LIMITS Display resource limit of the user Resumable session information for current USER_RESUMABLE user Description of all rewrite equivalence owned USER_REWRITE_EQUIVALENCES by the user USER_ROLE_PRIVS Roles granted to current user Switch privileges for consumer groups for the USER_RSRC_CONSUMER_GROUP_PRIVS user system privileges for the resource manager for USER_RSRC_MANAGER_SYSTEM_PRIVS the user USER_RULES Rules owned by the user Rulesets owned by the user: maintained for USER_RULESETS backward compatibility USER_RULE_SETS Rule sets owned by the user USER_RULE_SET_RULES Rules in user rule sets All scheduler chains owned by the current USER_SCHEDULER_CHAINS user All rules from scheduler chains owned by the USER_SCHEDULER_CHAIN_RULES current user All steps of scheduler chains owned by the USER_SCHEDULER_CHAIN_STEPS current user USER_SCHEDULER_JOBS All scheduler jobs in the database All arguments with set values of all scheduler USER_SCHEDULER_JOB_ARGS jobs in the database USER_SCHEDULER_JOB_LOG Logged information for all scheduler jobs USER_SCHEDULER_JOB_RUN_DETAILS The details of a job run USER_SCHEDULER_PROGRAMS Scheduler programs owned by the current user All arguments of all scheduler programs in the USER_SCHEDULER_PROGRAM_ARGS database All steps of chains being run by jobs owned USER_SCHEDULER_RUNNING_CHAINS by the current user USER_SCHEDULER_SCHEDULES Schedules belonging to the current user USER_SECONDARY_OBJECTS All secondary objects for domain indexes Security Relevant columns of VPD policies USER_SEC_RELEVANT_COLS for tables or views owned by the user USER_SEGMENTS Storage allocated for all database segments USER_SEQUENCES Description of the user's own SEQUENCEs USER_SNAPSHOTS Snapshots the user can look at USER_SNAPSHOT_LOGS All snapshot logs owned by the user Synonym for USER_SNAPSHOT_REFRESH_TIMES USER_MVIEW_REFRESH_TIMES By A.G.Reddy

SQL Quick Reference 166 USER_SOURCE 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 USER_SOURCE_TABLES USER_SQLJ_TYPES USER_SQLJ_TYPE_ATTRS USER_SQLJ_TYPE_METHODS USER_SQLSET_DEFINITIONS USER_STORED_SETTINGS USER_SUBSCRIBED_COLUMNS USER_SUBSCRIBED_TABLES USER_SUBSCRIPTIONS USER_SUMMARIES USER_SYNONYMS USER_SYS_PRIVS USER_TABLES USER_TABLESPACES USER_TAB_COLS USER_TAB_COLUMNS USER_TAB_COL_STATISTICS USER_TAB_COMMENTS USER_TAB_HISTOGRAMS USER_TAB_MODIFICATIONS USER_TAB_PRIVS USER_TAB_PRIVS_MADE USER_TAB_PRIVS_RECD USER_TAB_STATISTICS USER_TAB_STATS_HISTORY USER_TRIGGERS USER_TRIGGER_COLS USER_TS_QUOTAS USER_TUNE_MVIEW USER_TYPES USER_TYPE_ATTRS USER_TYPE_METHODS USER_TYPE_VERSIONS USER_UNUSED_COL_TABS USER_UPDATABLE_COLUMNS USER_USERS USER_USTATS USER_VARRAYS

76 Source of stored objects accessible to the user Source tables available for Change Data Capture Description of the user's own types Description of attributes of the user's own types Description of methods of the user's own types Synonym for USER_SQLSET Parameter settings for objects owned by the user Change Data Capture subscribed columns Change Data Capture subscribed tables Change Data Capture subscriptions Description of the summaries created by the user The user's private synonyms System privileges granted to current user Description of the user's own relational tables Description of accessible tablespaces Columns of user's tables, views and clusters Columns of user's tables, views and clusters Columns of user's tables, views and clusters Comments on the tables and views owned by the user Histograms on columns of user's tables Information regarding modifications to tables Grants on objects for which the user is the owner, grantor or grantee All grants on objects owned by the user Grants on objects for which the user is the grantee Optimizer statistics of the user's own tables History of table statistics modifications Triggers owned by the user Column usage in user's triggers Tablespace quotas for the user tune_mview catalog view owned by the user Description of the user's own types Description of attributes of the user's own types Description of methods of the user's own types Description of each version of the user's types User tables with unused columns Description of updatable columns Information about the current user All statistics on tables or indexes owned by the user Description of varrays contained in the user's own tables By A.G.Reddy

SQL Quick Reference 205 USER_VIEWS 206 207 208 209 210 211 212 USER_WARNING_SETTINGS USER_XML_INDEXES USER_XML_SCHEMAS USER_XML_TABLES USER_XML_TAB_COLS USER_XML_VIEWS USER_XML_VIEW_COLS .

77 Description of the user's own views Warning Parameter settings for objects owned by the user Description of the user's own XMLType indexes Description of XML Schemas registered by the user Description of the user's own XMLType tables Description of the user's own XMLType tables Description of the user's own XMLType views Description of the user's own XMLType views

By A.G.Reddy

Sign up to vote on this title
UsefulNot useful