Professional Documents
Culture Documents
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
PAGE NO.
3-18
PSUDO COLUMNS
18-19
SQL OPERATORS
19-21
SQL FUNCTIONS
21-37
SET OPERATORS
37-40
CONSTRAINTS
40-42
JOINS
42-46
SUB QUERIES
47-50
VIEWS
50-54
10
SYNONYMS
54-56
11
INDEXES
56-64
12
DICTIONARY TABLES
64
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Introduction of SQL:
Structured English Query Language (SEQUEL) was developed by IBM Corporation
Inc., to use Codds model.SEQUEL later becomes SQL (still pronounced as
sequel). SQL (Structured Query Language) is an ANSI and ISO standard computer
language for accessing, manipulating and controlling datas in database
systems.SQL works with database programs like Oracle, MS SQL Server, My
SQL,Teradata, MS Access, DB2, Informix, Sybase, etc.
SQL is a Standard - BUT....
Note:
Most of the SQL database programs also have their own proprietary extensions in
Addition to the SQL standard!
SQL Queries:
With SQL, We can query a database and have a result set returned.
SQL Advantages:
SQL has the following advantages:
Efficient
Easy to Learn & Use(SQL is simple English-like commands make it easy to
design and manage the information)
Functionally complete(You can define, retrieve, and manipulate data in the
tables)
SQL in Oracle:
The Oracle Server supports ANSI standard SQL and contains extensions.
Oracle SQL statements complies with industry-accepted standards.
Five Sub-Languages in SQL:
SQL provides 5 Sub-Languages for a variety of database tasks such as:
DDL Data Definition Language
DML Data Manipulation Language
DRL/DQL Data Retrieval/Query Language
TCL Transaction Control Language
DCL Data Control Language
3
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
DDL:
DDL statements are used to provide Structure and Structure-Oriented changes to
the objects like Tables, Views etc,
Statements are:
Create - Used to create objects like Table, View, Index and Synonyms
Alter - Used to alter definition of an object.
Drop - Used to drop the definition of an object along with its data.
Truncate - Used to remove all the rows from the object & its structure
remains
Rename - Used to rename the objects
Rules for creating a table:
Table names & column names must begin with a letter and be 130
characters.
Table names must begin with a character AZ or az.
Names may contain characters, numerals and special characters like AZ, a
z,
09, _ (underscore), $, and # (legal characters, but their use is
discouraged).
The name must not be same as the name of any other object in your
schema.
Names must not be an Oracle Server reserved word.
Table names are not case sensitive. If you create a table with upper, lower or
a mixed case the tables names are stored only the upper case in the data
dictionary.
If you want to create a table with the name in lower case characters, then
you
must enclose the table name within double quotes while creating the table.
The no of columns in a table can be up to a maximum of 1000.
The column names in the table must be unique. However, column names can
be
duplicated across tables.
Syntax:
CREATE TABLE [schema.]<table_name>
(
<column_name> <data_type(size)> [DEFAULT <expr>] [,..]
);
E.g: CREATE TABLE dept
(
4
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13)
);
The DEFAULT Option:
This Default clause lets you specify a value to be assigned to the column if
the
user omits the value for the column.
This option prevents null values from entering the columns if a row is
inserted
without a value for the column.
The default value can be a literal value, an expression, or a SQL function,
such as
SYSDATE and USER.
But the value cannot be the name of another column or a pseudo column
such as
LEVEL, ROWNUM, PRIOR, NEXTVAL or CURRVAL.
The default expression must match the data type of the column.
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Note:
It invalidates all objects that depend on the renamed column.
You must be the owner of the object that you rename.
It works Oracle 9i ver 9.2.0.1.0 and prior.
The DROP command:
The DROP TABLE statement removes the definition of a table from the
database.When you drop a table, the database loses all the data in the table and all
the indexes associated with it. Dropping table invalidates the tables dependent
objects like views, synonyms etc The DROP TABLE statement, once executed, is
irreversible. To drop a table, the table should be in your own schema or you should
have DROP ANY TABLE system privilege. The Oracle Server does not question the
action when you issue the DROP TABLE statement.
Syntax: DROP TABLE <table_name>;
E.g: DROP TABLE emp;
7
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
DML:
DML statements enable the manipulation of data in the existing object or used to
provide Record and Record-Oriented changes.
Statements are:
Insert - Used to add rows to a table
Update - Used to modify the existing values in a table
Delete - Used to remove one or more rows from a table
Merge (9i) - Used to select rows & those rows are update/insert into another
table
Insert Command:
Insert statement is used for adding new row in an existing table.
Syntax: INSERT INTO [schema.]{<table_name>|<view_name>}
[(column [, column])]
[VALUES (value [, expr|DEFAULT])] | [sub_query];
E.g: INSERT INTO dept VALUES (50, 'HRD', 'Chennai');
Note:
This statement with the VALUES clause adds only one row at a time to a
table.
Character data should be enclosed within single quotes.
Date and Time stamp datas can be provided with single quotes or you can
use the conversion functions.
Number values should not be enclosed in single quotes; because implicit
conversion may take place for numeric values assigned to NUMBER data type
columns if single quotes are included.
If you want to insert a new row that contains values for each column, the
column list is not required in the INSERT clause.
However, if you do not use the column list, the values must be listed
according to the default order of the columns in the table, and a value must
be provided for each column.
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
10
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
SQL *Plus substitution variable & allow the user to add values interactively
in an Insert statement.
The SQL *Plus prompts for the value of the variable, accepts it and
substitutes into the variable.
Any number of rows can be inserted one after another by using the /. Which
executes the last executed statement. But supply a different set of values
each time you run it.
E.g: INSERT INTO dept (deptno, dname, loc) VALUES (&deptno, '&dname', '&loc');
Copying Rows from Another Table:
You can use the INSERT statement to add rows to a table where the values
arederived from existing tables. In place of the VALUES clause, use a subquery.
The number of columns and their data types in the column list of the INSERT
clause must match the number of values and their data types in the subquery.
Syntax: INSERT INTO table [column (, column)] subquery;
E.g: INSERT INTO emp2 SELECT * FROM emp;
INSERT INTO emp2 (empno, ename, job, sal)
SELECT empno, ename, job, sal FROM scott.emp;
Update Command:
Update statement is used to change or modify the existing values in a table.
Values of a single column or a group of columns can be updated.
Updates can be carried out for all the rows in a table or selected rows.
Syntax: UPDATE [schema.]{<table_name> | <view_name>}
SET column = <expr | (sub-query) | DEFAULT>
[, column = <expr | (sub-query) | DEFAULT>,]
[WHERE <condition>];
Note:
Condition identifies the rows to be updated and is composed of column
names expressions, constants, sub-queries, and comparison operators
In general, use the primary key to identify a single row. Using other columns
can unexpectedly cause several rows to be updated.
11
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
12
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
TCL:
TCL statements enable to manage the changes made by DML statements, which is
called as Transactions. Transactions can change a set data from one state to
another.A transaction helps to store the data permanently in the database.
Statements is:
Commit - Used to make the changes permanent to the database
Rollback - Used to undo or cancel the transactions
Save point - Used to divide a transaction into smaller sub-units
When Does a Transaction Start?
A transaction begins when the first DML statement is encountered or first DML
statement issued after the previous transactions.
15
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
16
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Rollback to Savepoint:
ROLLBACK TO SAVEPOINT allows to Roll back the current transaction to the
specified savepoint, thereby discarding any changes and or savepoints
created after the savepoint to which you are rolling back.
If you omit the TO SAVEPOINT clause, the ROLLBACK statement rolls back
the entire transaction.
As savepoints are logical, there is no way to list the savepoints you have
created.
Syntax: ROLLBACK TO <savepoint_name>;
E.g: ROLLBACK TO rainforest;
Implicit Transaction Processing
Automatic commit:
The action that will force a commit to occur, even without issuing the COMMIT is:
Any DDL or DCL statements issued.
SQL*Plus exited normally.
Connecting to other user.
Disconnecting from Oracle.
Automatic rollback:
The action that will force a rollback to occur, even without issuing the
ROLLBACK is:
Abnormal termination of SQL*Plus
A machine fails or the system crashes
System failure
Network failure
DCL:
DCL statements enable to control the access to the database and its objects.
Statements are:
Grant - Used to give access of the database object from one user to another
Revoke - Used to remove the object privileges granted to other user
Creating a User:
The DBA creates the user by executing the CREATE USER statement.
The user does not have any privileges at this point.
The DBA can then grant privileges to that user.
These privileges determine what the user can do at the database level.
Syntax: CREATE USER user IDENTIFIED BY password;
17
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
ROWID Maintains Unique Rowid for each and every record. Its Permanent.
ROWNUM Displays Sequence number of the records. Its Temporary.
LEVEL and SYSDATE
CURRVAL and NEXTVAL
18
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
E.g:
E.g:
E.g:
E.g:
You can use wild card characters multiple times either before & after the
pattern.
SELECT
SELECT
SELECT
SELECT
ename,
ename,
ename,
ename,
sal
sal
sal
sal
FROM
FROM
FROM
FROM
emp
emp
emp
emp
WHERE
WHERE
WHERE
WHERE
ename
ename
ename
ename
LIKE('S%');
LIKE('S_%');
LIKE('_I%');
LIKE('%R');
Escape Option:
You can include the actual characters "%" or "_" in the pattern by using the
ESCAPE clause, which identifies the escape character.
If the escape character appears in the pattern before the character "%" or
"_" then Oracle interprets this character literally in the pattern, rather than
as a special pattern matching character.
The ESCAPE clause identifies the backslash (\) as the escape character.
To search for employees with the pattern 'A_B' in their name:
E.g: SELECT ename FROM emp WHERE ename LIKE '%A\_B%' ESCAPE '\';
E.g: SELECT ename FROM emp WHERE ename LIKE 'S%\_%' ESCAPE '\';
E.g: SELECT ename FROM emp WHERE ename LIKE '\%S%' ESCAPE '\';
IS NULL:
E.g: SELECT ename, sal FROM emp WHERE comm IS NULL;
Logical Operators:
AND Returns TRUE if both component conditions are true
OR Returns TRUE if either component condition is true
NOT Returns TRUE if the following condition is false
AND:
E.g: SELECT ename, sal, job FROM emp WHERE sal > 1600 AND deptno = 30;
OR:
E.g: SELECT ename, sal, job FROM emp WHERE sal >1600 AND deptno = 30;
NOT:
E.g: SELECT ename, sal, comm FROM emp WHERE comm IS NOT NULL;
Rules of Precedence:
1st Arithmetic operators
2nd Concatenation operator
3rd Comparison conditions
4th IS [NOT] NULL, LIKE, [NOT] IN, EXIXTS
5th [NOT] BETWEEN
6th NOT logical condition
20
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
DECODE:
Syntax: DECODE(expr | column, search1, result1 [,search 2, result2,..] [, default])
E.g: SELECT empno, ename, sal, job, DECODE( job, 'MANAGER', 'Admin',
'CLERK', 'Accounts',
'SALESMAN', 'Marketing') Trade
FROM emp;
E.g: SELECT empno, ename, sal, job, DECODE( job, 'MANAGER', 'Admin',
'CLERK', 'Accounts', 'Others') Trade
FROM emp;
E.g: SELECT empno, ename, sal, job, DECODE( job, 'MANAGER', 'Admin',
'CLERK', 'Accounts', job) Trade
FROM emp;
LEAST:
Syntax: LEAST(exp1, exp2,..)
E.g: SELECT LEAST('HARRY', 'HARRIOT', 'HAROLD') FROM DUAL;
SELECT LEAST(25, 14, 84, 12, 54 ,7) "LEAST" FROM DUAL;
GREATEST:
Syntax: GREATEST (exp1, exp2,..)
E.g: SELECT GREATEST('HARRY', 'HARRIOT', 'HAROLD') FROM DUAL;
SELECT GREATEST(25, 14, 84, 12, 54 ,7) FROM DUAL;
UID: This function returns the User ID of the session user, generated by system.
E.g: SELECT UID FROM DUAL;
USER: This function returns the name of the session user.
E.g: SHOW USER;
SELECT USER FROM DUAL;
Character Functions:
Case - Manipulation Functions:
LOWER
UPPER
INITCAP
Character - Manipulation Functions:
CHR TRIM
CONCAT LTRIM
SUBSTR RTRIM
LPAD REPLACE
RPAD TRANSLATE
REVERSE
Character Functions Returning Numerical Values:
ASCII
LENGTH
INSTR
23
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
LOWER:
Syntax: LOWER (char)
E.g: SELECT LOWER(ename) FROM emp WHERE LOWER(job) = 'manager';
UPPER:
Syntax: UPPER (char)
E.g: SELECT UPPER('oracle') FROM DUAL;
INITCAP:
Syntax: INITCAP (char)
E.g: SELECT empno, INITCAP(ename) FROM emp;
SELECT INITCAP('ORACLE SERVER') FROM DUAL;
CHR:
Syntax: CHR(n)
E.g: SELECT CHR(67) || CHR(65) || CHR(84) "Dog" FROM DUAL;
CONCAT:
Syntax: CONCAT (char1, char2)
E.g: SELECT CONCAT(empno, ename) FROM emp;
SUBSTR:
Syntax: SUBSTR(string, position[, substring_length])
E.g: SELECT SUBSTR('ABCDEFG', 3, 4) "Substring" FROM DUAL;
SELECT SUBSTR('ABCDEFG', -4, 3) "Substring" FROM DUAL;
SELECT SUBSTR('ABCDEFG', 5) "Substring" FROM DUAL;
LPAD:
Syntax: LPAD(char1, n[, char2])
E.g: SELECT LPAD(job, 12, '*') FROM emp;
RPAD:
Syntax: RPAD(char1, n[, char2])
E.g: SELECT RPAD(job, 12, '*') FROM emp;
REVERSE:
Syntax: REVERSE(string)
E.g: SELECT REVERSE(ename) FROM emp;
TRIM:
Syntax: TRIM([LEADING | TRAILING]<trim_character> FROM <trim_source>)
E.g: SELECT TRIM(LEADING 'S' FROM ename)FROM emp;
24
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
ASCII:
Syntax: ASCII(char)
E.g: SELECT ASCII('A') FROM DUAL;
LENGTH:
Syntax: LENGTH(char)
E.g: SELECT ename, LENGTH(ename) FROM emp
WHERE LENGTH(ename) = 5;
INSTR:
Syntax: INSTR(string, substring[, position[, occurrence]])
E.g: SELECT INSTR('CORPORATE FLOOR', 'OR') "Instring" FROM DUAL;
SELECT INSTR('CORPORATE FLOOR', 'OR', 3)"Instring" FROM DUAL;
SELECT INSTR('CORPORATE FLOOR', 'OR', 3, 2)"Instring" FROM dual;
SELECT INSTR('CORPORATE FLOOR', 'OR', -3, 2)
"Reversed Instring" FROM DUAL;
25
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Number Functions:
ABS
CEIL
FLOOR
MOD
POWER
SQRT
SIGN
TRUNC
ROUND
ABS:
Syntax: ABS (n)
E.g: SELECT ABS(-15) "Absolute" FROM DUAL; o/p: 15
CEIL:
Syntax: CEIL(n)
E.g: SELECT CEIL(15.7) "Ceiling" FROM DUAL; o/p: 16
FLOOR:
Syntax: FLOOR(n)
E.g: SELECT FLOOR(15.7) "Floor" FROM DUAL; o/p: 15
MOD:
Syntax: MOD(m, n)
E.g: SELECT sal, MOD(sal, 3) "Modulus" FROM emp;
POWER:
Syntax: POWER(m, n)
E.g: SELECT sal, POWER(sal, 2) "Salary Raised" FROM emp;
SQRT:
Syntax: SQRT(n)
E.g: SELECT SQRT(24) "Square root" FROM DUAL; o/p: 4.89897949
SIGN:
Syntax: SIGN(n)
E.g: SELECT SIGN(-15) "Sign" FROM DUAL; o/p: -1
SELECT SIGN(0) "Sign" FROM DUAL; o/p: 0
SELECT SIGN(15) "Sign" FROM DUAL; o/p: 1
26
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
TRUNC:
Syntax: TRUNC(n[, m])
E.g: SELECT sal, sal / 3, TRUNC((sal / 3), 1) "Truncate" FROM emp;
ROUND:
Syntax: ROUND(n[, m])
E.g: SELECT sal, sal / 3, ROUND((sal / 3),1) "Round" FROM emp;
Matrix Query using General Function DECODE:
E.g: SELECT job,
SUM(DECODE(deptno, 10, sal)) dept10,
SUM(DECODE(deptno, 20, sal)) dept20,
SUM(DECODE(deptno, 30, sal)) dept30,
SUM(DECODE(deptno, 40, sal)) dept40
FROM emp
GROUP BY job;
Date Functions:
Arithmetic with Dates
Operation Result Description
date + number Date Adds a no. of days to a date
date - number Date Subtracts a no. of days from a date
date - date No. of days Subtracts one date from another
date + number/24 Date Adds a no. of hours to a date
E.g: SELECT hiredate, hiredate + 5 FROM emp;
SELECT hiredate, hiredate - 5 FROM emp;
SELECT hiredate, (SYSDATE - hiredate) FROM emp;
SELECT SYSDATE, SYSDATE + 12 / 24 FROM DUAL;
Type of Date Functions:
MONTHS_BETWEEN Number of months between two dates
ADD_MONTHS Add calendar months to date
NEXT_DAY Next day of the date specified
LAST_DAY Last day of the month
ROUND Round date
TRUNC Truncate date
MONTHS_BETWEEN:
Syntax: MONTHS_BETWEEN(date1, date2)
E.g: SELECT MONTHS_BETWEEN(SYSDATE, hiredate)FROM emp;
27
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
ADD_MONTHS:
Syntax: ADD_MONTHS(date, n)
E.g: SELECT hiredate, ADD_MONTHS(hiredate, 2)FROM emp;
NEXT_DAY:
Syntax: NEXT_DAY(date, 'char')
E.g: SELECT hiredate, NEXT_DAY(hiredate, 'WEDNESDAY')FROM emp;
LAST_DAY:
Syntax: LAST_DAY(date)
E.g: SELECT hiredate, LAST_DAY(hiredate) FROM emp;
ROUND:
Syntax: ROUND(date[,'fmt'])
E.g: SELECT hiredate, ROUND(hiredate, 'YEAR') FROM emp;
SELECT hiredate, ROUND(hiredate, 'MONTH') FROM emp;
SELECT ROUND(SYSDATE) FROM DUAL;
TRUNC:
Syntax: TRUNC(date[,'fmt'])
E.g: SELECT hiredate, TRUNC(hiredate, 'YEAR') FROM emp;
SELECT hiredate, TRUNC(hiredate, 'MONTH') FROM emp;
Conversion Functions:
Implicit data-type conversion
From To
VARCHAR2 or CHAR NUMBER or DATE
NUMBER or DATE VARCHAR2
Although implicit data-type conversion is available, it is recommended that you
do explicit data type conversion to ensure the reliability of your SQL statements.
Explicit data-type conversion
Functions:
TO_CHAR
TO_NUMBER
TO_DATE
TO_CHAR:
Syntax: TO_CHAR(date | number [, fmt[, 'nlsparam']])
28
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Connecting to SQL*Plus:
CONN [ECT] logs on to another user account without exiting SQL*Plus
Syntax: CONN <user_name> / <password> @ <host_string>;
E.g: CONN scott/tiger@oracle;
To connect with oracle without exiting SQL*Plus
SQL>conn
Enter user-name: SCOTT
Enter password: *****
SQL> conn scott
Enter password: ****
Aggregating Data using Group Functions
Unlike single-row functions, group functions operate on sets of rows to give one
result per group. These sets may be the whole table or the table split into groups.
Types of Group Functions:
AVG Average value of n, ignoring null values
COUNT Count No. of Rows
MAX Maximum value of expr, ignoring null values
MIN Minimum value of expr, ignoring null values
STDDEV Standard deviation of n, ignoring null values
SUM Sum values of n, ignoring null values
VARIANCE Variance of n, ignoring null values
AVG:
Syntax: AVG([DISTINCT | ALL] n)
E.g: SELECT AVG(sal) "Average" FROM emp;
SELECT AVG(comm) "Average" FROM emp;
SELECT AVG(NVL(comm, 0)) "Average" FROM emp;
SELECT AVG(DISTINCT sal) "D.AVG" FROM emp;
COUNT:
Syntax: COUNT(* |{ [DISTINCT | ALL] expr})
E.g: SELECT COUNT(*) "Total" FROM emp;
SELECT COUNT(DISTINCT deptno) "DIST.COUNT" FROM emp;
SELECT COUNT(*) FROM emp WHERE comm IS NULL;
MAX:
Syntax: MAX([DISTINCT | ALL] expr)
E.g: SELECT MAX(sal) "Maximum" FROM emp;
30
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
MIN:
Syntax: MIN([DISTINCT | ALL] expr)
E.g: SELECT MIN(sal) "Minimum" FROM emp;
STDDEV:
Syntax: STDDEV([DISTINCT | ALL] x)
E.g: SELECT STDDEV(sal) "Deviation" FROM emp;
SUM:
Syntax: SUM([DISTINCT | ALL] n)
E.g: SELECT SUM(sal) "Total" FROM emp;
SELECT SUM(DISTINCT sal) "D.SUM" FROM emp;
VARIANCE:
Syntax: VARIANCE([DISTINCT | ALL] expr)
E.g: SELECT VARIANCE(sal) "Variance" FROM emp;
Guidelines for Using Group Functions:
DISTINCT makes the function consider only non-duplicate values; ALL makes
it consider every value including duplicates. The default is ALL and therefore
does not need to be specified.
The data types for the functions with an expr argument may be
CHAR,VARCHAR2, NUMBER, or DATE.
All group functions (expect COUNT function) ignore null values. To substitute
a value for null values, use the NVL, NVL2, or COALESCE functions.
COUNT (*) counts all selected rows including duplicates and rows with nulls.
The default group is the whole set of records in the table. Thus any
aggregate functions will apply to the whole table if no GROUP BY clause is
specified.
Creating Groups of Data by Using GROUP BY Clause
All group functions have treated the table as one large group of information.
At times, you need to split rows in a table into smaller groups or subsets.
Syntax: SELECT <column, group_function(column)>
FROM <table_name>
[WHERE <condition>]
[GROUP BY <group_by_expression>]
[ORDER BY <column>];
31
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Guidelines:
If you include a group function in a SELECT clause, you cannot select
individual
results as well, unless the individual column appears in the GROUP BY clause.
You receive an error message if you fail to include the individual column list
inthe GROUP BY clause.
Using a WHERE clause, you can exclude rows before dividing them into
groups.
The GROUP BY clause must be specified after WHERE clause.
You must include the individual columns in the GROUP BY clause.
You cannot use a column alias in the GROUP BY clause.
By default, rows are sorted by ascending order of the columns included in the
GROUP BY list. You can override this by using the ORDER BY clause.
You cannot use the WHERE clause to restrict groups.
You cannot use group functions in the WHERE clause.
You use the HAVING clause to restrict groups.
E.g: SELECT deptno, SUM(sal) FROM emp GROUP BY deptno;
Using the group function in the ORDER BY clause:
SELECT job, SUM(sal) FROM emp GROUP BY job ORDER BY SUM(sal);
Using the Group By Clause on Multiple Columns:
SELECT deptno, job, SUM(sal) FROM emp GROUP BY deptno, job;
Restrict Groups Using HAVING Clause
You use the HAVING clause to specify which groups are to be displayed,and thus,
you further restrict the groups on the basis of aggregate information.
Note: WHERE clause conditions cant be used in Having clause & vice versa.
The Oracle performs the following steps when you use the HAVING clause:
1. Rows are grouped.
2. The group function is applied to the grouped rows.
3. The groups that match the criteria in the HAVING clause are displayed.
Syntax: SELECT column, group_function FROM table_name
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
E.g: SELECT deptno, SUM(sal) FROM emp
GROUP BY deptno HAVING SUM(sal) > 1500;
32
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
E.g: SELECT deptno, job, SUM(sal) FROM emp WHERE deptno < > 10
GROUP BY deptno, job HAVING SUM(sal) > 2000 ORDER BY 3;
To Find nth row in a table using Group By Clause:
E.g: SELECT * FROM emp
GROUP BY empno, ename, job, mgr, hiredate, sal, comm, deptno, rownum
HAVING rownum = &N;
Nesting Group Functions:
E.g: SELECT MAX(AVG(sal)) FROM emp GROUP BY deptno;
Why should group functions are not allowed in WHERE clause?
SELECT Statement Execution Flow:
A) Because while executing where clause there is no group function results.
Advance Group By Function
The ROLLUP Operator:
The ROLLUP operator delivers aggregates and super-aggregates for
expressions within a GROUP BY statement.
The ROLLUP operator can be used by report writers to extract statistics and
summary information from results sets.
ROLLUP grouping produces a result set containing the regular grouped rows
and subtotal rows.
E.g: SELECT deptno, job, SUM(sal) FROM emp
WHERE deptno > 10
GROUP BY ROLLUP(deptno, job);
The CUBE Operator:
The CUBE operator can be applied to all aggregate functions, including
AVG,SUM, MAX, MIN, and COUNT.
It is used to produce results sets that are typically used for cross-tabular
reports.
Columns included in the GROUP BY clause are cross-referenced to produce a
superset of groups.
The aggregate function specified in the select list is applied to these groups
to produce summary values for the additional super-aggregate rows.
The CUBE groups the selected rows based on the values of all possible
combinations of expressions in the specification and returns a single row of
summary information for each group.
E.g: SELECT deptno, job, SUM(sal) FROM emp
WHERE deptno > 10
33
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
34
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
35
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
CURRENT_DATE:
The CURRENT_DATE returns the current date in the sessions time zone.
CURRENT_DATE is sensitive to the session time zone.
The TIME_ZONE parameter specifies the default local time zone displacement
for the current SQL session.
The TIME_ZONE parameter is set as follows:
TIME_ZONE = '[+ | -] hh:mm'
E.g: SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;
Output:
SESSIONTIMEZONE CURRENT_D
+05:30 11-NOV-06
CURRENT_TIMESTAMP:
The CURRENT_TIMESTAMP function returns the current date and time in the
session time zone, as a value of the data type TIMESTAMP WITH TIME ZONE.
The syntax of the CURRENT_TIMESTAMP function is:
CURRENT_TIMESTAMP (precision)
Where, precision is an optional argument that specifies the fractional second
precision of the time value returned. If you omit precision, the default is 6.
Otherwise it Accepts values are 0 to 9.
E.g: SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM DUAL;
Output:
SESSIONTIMEZONE CURRENT_TIMESTAMP
+05:30 11-NOV-06 02.04.30.000000 AM +05:30
LOCALTIMESTAMP:
The LOCALTIMESTAMP function returns the current date and time in the
session time zone in a value of data type TIMESTAMP.
The TIMESTAMP WITH TIME ZONE data type has the following format:
TIMESTAMP [ (fractional_seconds_precision) ] WITH TIME ZONE
The syntax of the LOCAL_TIMESTAMP function is:
LOCAL_TIMESTAMP (TIMESTAMP_precision)
E.g: SELECT CURRENT_TIMESTAMP, LOCALTIMESTAMP FROM DUAL;
Output:
CURRENT_TIMESTAMP LOCALTIMESTAMP
11-NOV-06 02.06.20.000000 AM +05:30 11-NOV-06 02.06.20.000000 AM
Difference between LOCALTIMESTAMP and CURRENT_TIMESTAMP is
LOCALTIMESTAMP returns a TIMESTAMP value,
CURRENT_TIMESTAMP returns a TIMESTAMP WITH TIME ZONE value.
36
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
DBTIMEZONE:
The DBTIMEZONE function returns the value of the database time zone.
The default database time zone is the same as the operating system's time zone.
You can set the database's default time zone by specifying the SET TIME_ZONE
clause of the CREATE DATABASE statement.
E.g: SELECT DBTIMEZONE, SESSIONTIMEZONE FROM DUAL;
Output: see the output in session time zone.
SESSIONTIMEZONE:
The SESSIONTIMEZONE returns the value of the current sessions time zone.
E.g: SELECT DBTIMEZONE, SESSIONTIMEZONE FROM DUAL;
DBTIME SESSIONTIMEZONE
-05:00 +05:30
EXTRACT:
The EXTRACT expression extracts and returns the value of a specified datetime
field from a datetime or interval value expression.
Syntax:
EXTRACT ( [YEAR] [MONTH] [DAY] [HOUR] [MINUTE] [SECOND]
[TIMEZONE_HOUR] [TIMEZONE_MINUTE] [TIMEZONE_REGION]
[TIMEZONE_ABBR]
FROM [datetime_value_expression] [interval_value_expression] )
E.g: SELECT EXTRACT (YEAR FROM SYSDATE),
EXTRACT (MONTH FROM SYSDATE),
EXTRACT (DAY FROM SYSDATE) FROM DUAL;
Output:
(YEARFROMSYSDATE) (MONTHFROMSYSDATE) (DAYFROMSYSDATE)
The SET Operators
The SET operators combine the results of two or more component queries into one
result. Queries containing SET operators are called compound queries.
Note: In the slide, the light color (gray) in the diagram represents the query result.
Operator Returns
UNION All distinct rows selected by either query
UNION ALL All rows selected by either query, including all duplicates
INTERSECT All distinct rows selected by both queries
MINUS All distinct rows that are selected by the first SELECT statement and that
are not selected in the second SELECT statement
37
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Guidelines:
All SET operators have equal precedence.
If multiple SET operators used, the Oracle evaluates them from left (top) to right
(bottom)
You should use parentheses to specify the order of evaluation explicitly.
The UNION SET Operator:
The UNION operator returns all rows selected by either query. Use the UNION
operator to return all rows from multiple tables and eliminate any duplicate rows.
Guidelines:
The number of columns and the data types of the columns being selected
must be identical in all the SELECT statements used in the query. The names
of the columns need not be identical.
NULL values are not ignored during duplicate checking.
The IN operator has a higher precedence than the UNION operator.
By default, the output is sorted in ascending order of the first column of the
SELECT clause.
Guidelines:
Unlike UNION, duplicate rows are not eliminated and the output is not sorted
by default.
The DISTINCT keyword cannot be used.
Note: With the exception of the above, the guidelines for UNION and UNION ALL
are
the same.
E.g: SELECT job FROM emp WHERE deptno = 20
UNION ALL
SELECT job FROM emp WHERE deptno = 30;
38
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
The number of columns and the data types of the columns being selected by
the SELECT statements in the queries must be identical in all the SELECT
statements used in the query. The names of the columns need not be
identical.
All of the columns in the WHERE clause must be in the SELECT clause for the
MINUS operator to work.
39
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
The set operators are not valid on columns of type BLOB, CLOB,
BFILE,VARRAY, or Nested Table.
The UNION, INTERSECT, and MINUS operators are not valid on LONG
columns.
To reference a column, you must use an alias to name the column.
You cannot specify the order by clause in the sub-query of these operators.
You cannot use these operators in SELECT statements containing TABLE
collection expressions.
Integrity Constraints
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Example
Create a table using Primary Key and Not null constraints
create table employee
(empno number(4),
ename varchar2(30) not null,
Job varchar2(30) unique ,
deptno number(2) not null,
constraint Emp_pk_id primary key (empno)) ;
- For foreign key , create the master table first and after that child table.
create table department
(deptno number(2) primary key ,
dname varchar2(30) not null,
location varchar2(30)) ;
- Creating a table using foreign key, primary key, unique , check and default
constraint
create table employee
(empno number(4) primary key,
ename varchar2(30) not null,
Job varchar2(30) unique ,
sal number(5,2) check (sal > 0) ,
DOJ date default sysdate,
deptno number(2) ,
constraint EmpNO_fk foreign key (deptno) references department(deptno) on
delete cascade) ;
Note: If a user is not giving the constraint name, Oracle automatically create a
constraint named as SYS_C0 (some number)
Dropping the Primary key constraint
SQL> alter table employee drop primary key ;
or
alter table employee drop constraint constraintname;
alter table employee add constraint Dept_pk primary key (deptno) ;
41
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
from
user_constraints
where
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
inner join :
When we join two tables or datasets together on an equality (i.e. column or set of
columns) we are performing an inner join. The ANSI method for joining EMP and
DEPT is as follows.
Example1 :
SELECT d.dname
,d.loc
,e.ename
,e.job
FROM dept d
,emp e
WHERE d.deptno = e.deptno;
Example2 :
SELECT d.dname
,d.loc
,e.ename
,e.job
FROM dept d INNER JOIN emp e USING(deptno);
SELECT d.dname
,d.loc
,e.ename
,e.job
FROM dept d INNER JOIN emp e ON(e.deptno=d.deptno)
Example3 :
SELECT COUNT(deptno)
FROM dept d INNER JOIN emp e USING(deptno);
Example3 :
SELECT d.dname
,d.loc
,e.ename
,e.job
FROM dept d INNER JOIN emp e ON(d.deptno = e.deptno);
Example4 :
SELECT d.dname
,d.loc
,e.ename
,e.job
FROM dept d INNER JOIN emp e ON(d.deptno = e.deptno)
WHERE d.loc = 'DALLAS';
43
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
natural join
A natural join will join two datasets on all matching column names, regardless of
whether the columns are actually related in anything other than name. For
example, the EMP and DEPT tables share one common column name and a natural
join between the two tables would be correct in this scenario.
The following example converts our INNER JOIN from previous examples to a
NATURAL JOIN.
Example1 :
SELECT d.dname
,d.loc
,e.ename
,e.job
FROM dept d NATURAL JOIN emp e;
Cross join:
A join without having any condition is known as cross join, in cross join every row
in first table is joins with every row in second table. Cross join is nothing but
cortizion product.
Example1:
select *from emp,dept
Outer
Outer
Outer
join:
join produces the results, which contains matched rows and unmatched rows.
join is further classified as three types.They are
left outer join
right outer join
full outer join.
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
SELECT deptno
,d.dname
,d.loc
,e.ename
,e.job
FROM dept d LEFT OUTER JOIN emp e USING(deptno);
In traditional Oracle syntax, outer joins are indicated by (+) and this can
sometimes cause issues when attempting to outer join multiple tables or includeg
expressions in join predicates. Oracle outer joins have no concept of direction,
whereas ANSI-compliant outer joins do. In the following example, we will outer join
DEPT to EMP using the ANSI LEFT OUTER JOIN. The way to interpret this is to read
the tables in the FROM clause from left to right. The left-hand table is the superset
and the table on the right is the potentially deficient set.
Right outer join:
Right outer join produces the resultset, which contains all the rows from right table
and matched rows from left table.
Example1 :
SELECT d.deptno
,d.dname
,d.loc
,e.ename
,e.job
FROM dept d
,emp e
WHERE d.deptno(+) = e.deptno
Example2 :
SELECT deptno
,d.dname
,d.loc
,e.ename
,e.job
FROM emp e RIGHT OUTER JOIN dept d USING(deptno);
As its name suggests, a right outer join is an outer join where datasets are driven
from right to left (i.e. related to the ordering in the query). There are a few
occasions where we might want to use RIGHT OUTER JOIN, but generally, there is
nothing to be gained from switching the ordering of the tables in this way.
Everything described in the left outer join section of this article applies equally to
right outer joins so we will not spend too much time on these. The following
example simply shows how to use this type of join. Again, the OUTER keyword is
optional.
45
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
You cannot specify the (+) operator in a query block that also contains ANSI
JOIN syntax.
If A and B are joined by multiple join conditions, you must use the (+)
operator in all of these conditions. If you do not, Oracle will return only the
rows resulting from a simple join, but without a warning or error to advise
you that you do not have the results of an outer join.
A condition containing the (+) operator cannot be combined with another
condition using the OR logical operator.
A condition cannot use the IN comparison condition to compare a column
marked with the (+) operator with an expression.
A condition cannot compare any column marked with the (+) operator with a
sub-query.
46
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Subqueries:
Sub queries can be used to answer queries such as "who has a salary more
than Tom's". For such query, two queries have to be executed: the first query finds
Tom's salary and the second finds those whose salary is greater than Tom's. Sub
query is an approach provides the capability of embedding the first query into the
other: Oracle executes the sub query first, making the result of the sub query
available to the main query and then executing the main query.
The syntax of sub query is
SELECT <column, ...>
FROM <table>
WHERE expression operator
( SELECT <column, ...>
FROM <table>
WHERE <condition>)
For example, the following statement answers the described query above.
Note that:
a subquery must be enclosed in the parenthesis.
a subquery must be put in the right hand of the comparison operator, and
a subquery cannot contain a ORDER-BY clause.
a query can contain more than one sub-queries.
three types subqueries:
single-row subquery, where the subquery returns only one row.
multiple-row subquery, where the subquery returns multiple rows,.and
multiple column subquery, where the subquery returns multiple columns.
Single-Row Subquery:
Single-row subqueries can only be used with single-row comparison operators, and
multiple-row subqueries can be used only with multiple-row operators. They are to
be described separately in the following.
The operators that can be used with single-row subqueires are =, >, >=, <, <=,
and <>.
Group functions can be used in the subquery. For example, the following statement
retrieve the details of the employee holding the highest salary.
SELECT * FROM emp WHERE sal = (SELECT MIN(sal) FROM emp)
Having-clause can also be used with the single-row subquery. For example, the
following statement returns all departments in where the minimum salary is more
than the minimum salary in the department 5.
47
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
SELECT deptno
,MIN(sal)
FROM emp
GROUP BY deptno
HAVING MIN(sal) > (SELECT MIN(sal)
FROM emp
WHERE deptno = 5);
SELECT empno
,ename
,job
,sal
,deptno
FROM emp
WHERE deptno IN(SELECT deptno
FROM dept
WHERE loc = 'CHICAGO');
Multiple-Row Subquery:
Note the following statement is illegal, because the operator = cannot be used with
subquery returns multiple rows.
Some operators that can be used with multipe-row subqueries are:
1. IN, equal to any member in the list,
2. ANY, compare values to each value returned by the subquery.
3. ALL, compare values to each value returned by the subquery.
Example:
SELECT ename,sal
FROM emp
WHERE sal IN(SELECT MIN(sal)
FROM emp GROUP BY deptno)
Operators:
<ANY
<ALL
>ANY
>ALL
<ANY : Maximum Value of Subquery(1300)
SELECT * FROM emp WHERE sal <ANY(SELECT MIN(sal) FROM emp GROUP BY
deptno);
<ALL : Minimum Value of Subquery(800)
SELECT * FROM emp WHERE sal <ALL(SELECT MIN(sal) FROM emp GROUP BY
deptno);
>ANY : Minimum Value of Subquery(800)
48
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
SELECT * FROM emp WHERE sal >ANY (SELECT MIN(sal) FROM emp GROUP BY
deptno)
>ALL : Maximum Value of Subquery(1300)
SELECT * FROM emp WHERE sal >ALL (SELECT MIN(sal) FROM emp GROUP BY
deptno)
Multiple-Column Subquery:
In multiple-column subqueries, rows in the subquery results are evaluated in the
main query in pair-wise comparison. That is, column-to-column comparison and
row-to-row comparison.
Note that you can put a subquery in the FROM clause in the main query.
For example, the following statement finds all employees in each department where
their salary is above the average.
Example :
SELECT a.ename
,a.sal
,a.deptno
,b.sal_avg
FROM emp a
,(SELECT deptno
,AVG(sal) sal_avg
FROM emp
GROUP BY deptno) b
WHERE a.deptno = b.deptno
AND a.sal > b.sal_avg;
Correlated Oracle subquery:
A correlated Oracle subquery is evaluated once FOR EACH ROW as opposed to a
normal subquery which is evaluated only once for each table.
You can reference the outer query inside the correlated subquery using an alias
which makes it so handy to use.
Let's select all employees whose salary is less than the average of all the
employees' salaries in the same department.
SELECT ename
,sal
,deptno
FROM emp a
WHERE a.sal < (SELECT AVG(sal)
49
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
FROM emp b
WHERE a.deptno = b.deptno);
Using a correlated subquery in an update:
UPDATE emp a
SET sal = (SELECT AVG(sal)
FROM emp b
WHERE a.deptno = b.deptno)
WHERE sal < (SELECT AVG(sal)
FROM emp c
WHERE a.deptno = c.deptno);
correlated subquery in a delete:
Lets delete the highest earning employees in each department.
DELETE FROM emp a
WHERE a.sal = (SELECT MAX(sal)
FROM emp b WHERE a.deptno = b.deptno);
Views:
Views are known as logical tables. They represent the data of one of more
tables. A view derives its data from the tables on which it is based. These tables are
called base tables. Views can be based on actual tables or another view also.
Whatever DML operations you performed on a view they actually affect the base
table of the view. You can treat views same as any other table. You can Query,
Insert, Update and delete from views, just as any other table.
Views are very powerful and handy since they can be treated just like any other
table but do not occupy the space of a table.
A view is a named and validated SQL query which is stored in the Oracle data
dictionary. Views do not contain any data - it is just a stored query in the database
that can be executed when called. One can think of a view as a virtual table or
mapping of data from one or more tables.
Views are useful for security and information hiding, but can cause problems if
nested too deeply. Some of the advantages of using views:
50
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Types of Views:
Simple View
Complex View
Inline view
Materialized View
Simple View:
Simple view derives data from only one table and simple view contain no functions
or group of data simple view always allow DML operation through the view.
Example1:
CREATE VIEW myview
AS
SELECT empno employee_no
,ename NAME
,sal salary
,job job
FROM emp
WHERE deptno = 20;
Example2:
CREATE VIEW myview1(emloyee_no
,NAME
,salary
,job
)
AS
SELECT empno
,ename
,sal
,job
FROM emp
WHERE deptno = 20;
Complex View:
Complex view derives data from many table and complex view contain function or
group of data and Complex view does not always allow.
Complex views can be constructed on more than one base table. In particular,
complex views can contain:
join conditions
group by clause
order by clause
51
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
One cannot perform DML operations against complex views directly. To enable DML
operations on complex views one needs to write INSTEAD OF triggers to tell Oracle
how the changes relate to the base table(s).
Example1:
CREATE VIEW v3
AS
SELECT e.*
FROM emp e
,dept d
WHERE e.deptno = d.deptno
Inline View:
An inline view is a SELECT statement in the FROM-clause of another SELECT
statement. In-line views are commonly used simplify complex queries by removing
join operations and perform several separate queries into a single query.
Example1 :
SELECT *
FROM (SELECT deptno
,COUNT(*) emp_count
FROM emp
GROUP BY deptno) emp
,dept
WHERE dept.deptno = emp.deptno;
Example2:
SELECT a.ename
,a.sal
,a.deptno
,b.maxsal
FROM emp a
,(SELECT deptno
,MAX(sal) maxsal
FROM emp
GROUP BY deptno) b
WHERE a.deptno = b.deptno
AND a.sal = b.maxsal;
Materialized View:
A materialized view is a database object that contains the results of a query. The
FROM clause of the query can name tables, views, and other materialized
views.There are three steps involved in creating a materialized view
Grant the necessary privileges
Create the materialized view log
52
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Privilege
exec dbms_mview.refresh('m_dept','F');
F = Fast refresh
C = Complete refresh
? = Force refresh
A = Always refresh
exec dbms_mview.refresh.estimate_mview_size (
stmt_id IN VARCHAR2,
select_clause IN VARCHAR2,
num_rows OUT NUMBER,
num_bytes OUT NUMBER);
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
There are NOT NULL columns in the base tables that are not selected
by the view.
Synonyms:
Synonyms are aliases for objects within the database, they are used to make life
easier
for
users,
they
hide
the
objects
identity
and
can
be
either public or private. public are accessible to all users, and private synonyms are
part on an individual users schema, so the user has to grant privilege right to other
users. Synonyms can be created for
tables
views (including materialized views)
stored code (packages and procedures)
They are used to allow users access to objects that lie outside their own schema.
There are two major uses of synonyms
Object transparency - keep original names from the users
Location transparency - hide the location of the object as it could be on
another database not the local one.
Creating public
Creating private
Removing
Sequences
Oracle has a automatic sequence generator that can produce a unique set of
numbers, normally the numbers are used for primary keys. It is possible to cache
the sequence numbers making the numbers ready and available in memory which
improves performance, however if the system was to crash those sequences
numbers are lost forever so be careful if the application requires no loss of
sequence numbers.
There are a number of options that can be used when creating a sequence
Creating
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
increment by 1
nomaxvalue
nocycle;
start with - you can choose any number you like to start with
increment by - you can increment by any number
nomaxvalue - just keep on going
nocycle - you can recycle the list
Removing
caching
(default 20)
Using
Oracle Indexes:
Oracle indexes provides faster access to table rows by storing sorted values
in specific columns and using those sorted values to easily lookup the associated
table rows. This means that you can lookup data without having to look at more
than a small fraction of the total rows within the table, they are completely
optional.
The trade off is that you get faster retrieval but inserting data is slower as the index
needs to be updated, this slower inserting is bad news for OLTP type of databases
but in a data warehouse type of database where inserting is at a minimal indexes
can be used heavily.
Index Types
Unique/non-Unique
Primary/Secondary
Composite
(concatenated)
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Index Guidelines:
Here are some guidelines from creating efficient indexes:
Index if you need to access no more than 10-15% of the data in the table. A
full table scan (read all the table) is better if you intend to retrieve a high
percentage of the table data, this is because a index read requires two reads
Do not use indexes on small tables, a full table scan would be fine.
Create primary keys for all tables as a index will be created by default.
Index the columns that are involved in multi-table join operations
Index columns that are used frequently in where clauses.
Index columns that are involved in order by, group by,
union and distinct operations.
Columns that have long character strings are bad for indexing
Columns that are frequently update are bad for indexing
Choose tables where few rows have similar values
Keep the number of indexes small, to many will cause performance problems
on inserting data.
Index size estimation:
Just like oracle tables you can estimate the size of an index using the DBMS_SPACE
package
estimating
set serveroutput on
declare
l_index_ddl varchar2(1000);
l_used_bytes number;
l_allocated_bytes number;
begin
dbms_space.create_index_cost (
ddl=>'create index persons_idx on test01.emp(emp_id)',
used_bytes=>l_used_bytes,
alloc_bytes=>l_allocated_bytes);
dbms_output.put_line ('used = ' || l_used_bytes || 'bytes'
|| ' allocated = ' || l_allocated_bytes || 'bytes');
end;
/
Note:
used - shows the number of bytes that the index data actually represents
allocated - show the number of bytes the index will take up in the
tablespace when you actual create it
57
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Bitmap Index
Easy to update
Difficult to update
B*Tree Indexes:
In general B*Tree index would be placed on columns that were frequently used in
the predicate of a query and expect some small fraction of the data from the table
to be returned. It's purely a function on how large of a percentage of the table you
will need to access via the index and how the data happens to be laid out. If you
can use the index to answer the question accessing a large percentage of the rows
makes sense, since you are avoiding the extra scattered I/O to read the table. If
you use the index to access the table you will need to ensure you are processing a
small percentage of the total table.
Reserve key indexes are the same as B-tree indexes except that the byes of the
key column data are reserved during indexing, the column order is kept intact only
58
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
the bytes are reserved. A big advantage is that data is distributed evenly which
avoid hot spots within the index.
Creating
Removing
Moving
Renaming
Coalescing
Rebuilding
Rebuilding online
Index Usage
DBA_IND_COLUMNS
DB_IND_EXPRESSONS
INDEX_STATS
v$OBJECT_USAGE
You can use this view to monitor index usage. The view
displays statistics about index usage gathered from the
database. All indexes that have been used at least once can be
monitored and displayed in this view.
59
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Bitmap Indexes:
Bitmap indexes are structures that store pointers to many rows with a single index
key entry. In a bitmap index there will be a very small number of index entries,
each of which point to many rows. Bitmap indexes are best used on low cardinality
data, this is were the number of distinct items in the set of rows divided by the
number of rows is a small number for example a gender column may have MF, F
and NULL. If you had a table with 20000 rows you would find that 3/20000 =
0.00015, this would be an ideal candidate for a bitmap index.
Remember also that a single bitmap entry key points to many rows. If a session
modifies the index then all of the rows that the index points to are effectively
locked. Oracle cannot lock an individual bit in a bitmap index entry; it locks the
entire bitmap, this will seriously inhibit concurrency as each update will appear to
lock potentially hundreds of rows preventing their bitmap columns from being
concurrently updated.
An Oracle bitmap index would look like
Value/Row
10
11
12
13
14
Analyst
Clerk
Manager
President
Saleman
Using the above table you can see that rows 1, 4, 6, 7, 11, 12 and 14 would
represent a manager and clerk.
Creating
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Creating
Partition Indexes:
There are two types of index global and local
Local - Indexes are partitioned against the partitions, so for an example if a
table is partitioned 12 ways using a range then there will be 12 indexes one
for each partition, so they have a one-to-one relationship.
Global - Global indexes have no such relationship, but can be either
partitioned or non-partitioned
There is substantial maintenance involved when using globally partitioned indexes,
when ever there is DDL (update, add, coalesce, exchange, merge, move, split or
truncate) against the table the whole index has to be rebuilt as the DDL will mark
the index unusable. To stop the DDL marking the table unusable you need to
include the UPDATE GLOBAL INDEX statement otherwise the entire index will be
invalidated. You can also hash the index which will reduce high contention of the
leaf blocks. Local indexes have a one-to-one relationship, if any DDL activity is used
against the partition only the index for that partition is invalidated, oracle will also
automatically rebuild the partition, these are the big advantages to using local
partition indexing.
61
www.askhareesh.blogspot.com
www.facebook.com/askhareesh
Dictionary tables:
62
www.askhareesh.blogspot.com
www.facebook.com/askhareesh