You are on page 1of 21

Introduction to 9i SQL Handbook

• Oracle server supports ANSI standard SQL and contains extensions


• SQL used to communicate server to access, manipulate and control data
• SQL SELECT STATEMENT CAPABILITIES: PROJECTION, SELECTION, JOINING
• SELECT* from orders; Use this statement to retrieve data from a data table for Viewing/Inserting
• KEYWORD USED IN UPPERCASE NO USE OF ABBREVIATION OR SPILT ACROSS LINES
• CLAUSE SEPARATE LINE
• SQL STATEMENT USED BY 1 OR NORE LINE NOT CASE SENSETIVE UNLESS INDICATED
• INDENTS USED TO MAKE CODE MORE RELIABLE
• ARTIHMETIC EXPRESSIONS/OPERATOR BY PRECEDENCE * / + -
• DATE & CHARACTER LITERAL IN ‘02-12-2006’ single quotes
• DISTINCT TO ELIMINATE DUPLICATE ROWS
• SQL*Plus commands are used to manipulate data in tables, to manipulate table definitions in the database.
• ISQL*PLUS ORACLE TOOL
• DESCRIBE Isql*plus command
• WHERE CONDITION TO LIMITING ROWS/SORTING ROWS/restrict ROWS
• SQL*Plus feature used to replace values in WHERE clause? Ans.Substitution variables
COMPARISON CONDITIONS
1. EQUAL TO =
2. GREATER THAN >
3. GREATER THAN EQUAL TO >=
4. LESS THAN <
5. LESS THAN EQUAL TO <=
6. NOT EQUAL TO <> / ^= / !=
7. BETWEEN A AND B ONLY 2 VALUES
8. IN (SET) LIST OF VALUES
9. LIKE A CHARACTER PATTERN
10. IS NULL
WILDCARD SEARCH
% DENOTES 0 OR MANY CHARACTER | _ DENOTES 1 CHARACTER [underscore]
‘\_P%’ ESCAPE ’\’ [HERE ESCAPE CHARACTER \ ]
LOGICAL CONDITION
1. AND
2. OR
3. NOT
PRECEDENCE OF OPERATOR
1. Arithmetic
2. Concatenation
3. Comparison Cond.
4. Is [not] null, like, [not] in
5. [Not] between
6. NOT LOGICAL CONDITION
7. AND LOGICAL CONDITION
8. OR LOGICAL CONDITION
Order by [asc] desc to sort rows in select statement/multiple columns/column also not in select [column list]
Sort by column/column alias/column number.
True regarding the ORDER BY clause?
• The sort is in ascending by order by default, executes at last after WHERE and GROUP BY clause
• The ORDER BY clause comes last in SELECT statement, executes on server side as whole SQL
statement
DUAL IS A DUMMY TABLE
Functions
• Calculations on data
• Modify individual data item
• Manipulate o/p for group of rows
• Format date and no to display
-1-
Introduction to 9i SQL Handbook
• Convert column data type
• Always return values
Single Row Functions
• return one value
• act on each row returned
• return one result per row
• can be nested
• arguments- columns or expressions
• A single row subquery can retrieve only one row but many columns.
• A single row subquery can retrieve data from more than one table.
• SINGLE ROW FUNCTION NESTED TO ANY DEPTH
Argument
• User supplied constant
• Variable value
• Column name
• Expression
1. Character Function
a. Case Manipulation
Lower Upper initcap
b. Character Manipulation
Concat SUBSTR LENGTH INSTR LPAD | RPAD TRIM REPLACE
2. Number Function
ROUND TRUNC MOD
3. Date Function
• Sysdate RETURNS CURRENT DATABASE SERVER DATE AND TIME
• INTERNAL NUMERIC FORMAT 7 BYTES
• CENTURY YEAR MONTH DAY HOURS MINUTES SECONDS
• VALID DATE BETWEEN January 1,4712 B.C. TO December 31,9999 A.D.
• DEFAULT DATE FORMAT DD-MON-RR 01-JUL-06
• DATE + OR – NUMBER = DATE
• DATE – DATE = DAYS
• DATE+NUMBER/24 = DATE
a. MONTHS_BETWEEN
b. ADD_MONTHS
c. NEXT_DAY
d. LAST_DAY
e. ROUND
f. TRUNC
4. Conversion DATA TYPE Function
a. IMPLICIT Function
i. VARCHAR2 OR CHAR TO NUMBER TO_NUMBER
ii. VARCHAR2 OR CHAR TO DATE TO_DATE
iii. NUMBER TO VARCHAR2 TO_CHAR
iv. DATE TO VARCHAR2 TO_CHAR
FORMAT MODEL
TO_CHAR(DATE,’FORMAT MODEL’)
TO_NUMBER(CHAR[, ‘FORMAT MODEL’])
TO_NUMBER(‘12345.52’,’$999999.99’)
TO_DATE(CHAR[, ‘FORMAT MODEL’]) fx FOR EXACT MATCH
TO_DATE(‘MAY 24, 2006’,’MONTH DD,YYYY’)
TO_CHAR(NUMBER,’FORMAT MODEL’)
9 0 $ L . , MI PR EEEE V B
b. EXPLICIT
5. General Function
a. NVL(EX1,EX2) EX1 NULL PUT/RETURN EX2
-2-
Introduction to 9i SQL Handbook
b. NVL2(EX1,EX2,EX3) EX1 NOT NULL RETURN EX2 EX1 NULL RETURN EX3
c. NULLIF(EX1,EX2) EX1 = EX2 RETURN NULL ELSE RETURN EX1
d. COALESCE(EX1,EX2,…EXn) EX1 NULL RETURN EX2 EX1,EX2 NULL RETURN EX3
SELECT COALESCE (COMM_PCT,SALARY,10) COMMISSION FROM EMP;
CASE COL/EXP WHEN IF_EXP THEN RETURN_EXP
ELSE ELSE_EXP
END ALIAS_NAME
DECODE (COL/EXP,
SEARCH1,RESULT1,
SEARCH2,RESULT2,
DEFAULT_RESULT) ALIAS_NAME
Use: Select /where/order by with case and decode
Multiple Row Functions
• A multiple row subquery can retrieve multiple rows and multiple columns.
• A multiple row subquery can be compared by using the “>” operator (only case of all/any).
• The multiple-row subquery cannot be used with the comparison operator
• A multiple-row subquery cannot be used in an INSERT statement to insert multiple rows at a time.
• Group / AGGREGATE functions:
 SET OF ROWS ONE RESULT PER GROUP, IGNORE NULL VALUES
 AUTOMATICALLY SORT RESULT IN ASCENDING ORDER
 Mix single row columns with aggregate functions in the column list of a SELECT
statement by grouping on the single row columns.
 Pass column names, expressions, constants, or functions as parameters to an aggregate
function.
 AVG NUMBER
 COUNT (*)/(EXPR)/(DISTINCT expr) (*) number of rows including duplicate rows [DATE]
 MAX NUMBER [DATE]
 MIN NUMBER [DATE]
 STDDEV NUMBER
 SUM NUMBER
 VARIANCE NUMBER
Format of using Group Function
Select / From / Where / [Having] Group by/Having /Order by;
Group by
• Divide/spilt table info in groups
• Grouping can be more than 1 column
• Mix of individual item and group function must use a group by clause
• Without group function can use a group by clause
• Can use nesting group functions
• Include columns in group by clause
• If column not in select list still apply group by on this column
• Using where exclude rows before divide into groups
• Can’t use alias
• AUTOMATICALLY SORT RESULT IN ASCENDING ORDER
• To restrict groups or ROWS use having after/before group by clause don’t use where
• Match criteria in having are displayed
Operator used in Functions
Single row
• EQUAL TO =
• GREATER THAN >
• GREATER THAN EQUAL TO >=
• LESS THAN <
• LESS THAN EQUAL TO <=
• NOT EQUAL TO <> / ^= / !=
Subquery Retrieve data based on an unknown condition

-3-
Introduction to 9i SQL Handbook
Multiple row
• Subquery or inner query includes Where / Having/ From / Operator
• Subquery in parenthesis ( )
• RHS of comparison condition.
• If Top-N analysis then order by needed otherwise not
• Single row operator with Single row Subquery (return one row)
• Multiple row operator with Multiple row Subquery (return multiple rows)
• Executes sub queries first
• Common Error: More than one row returned for a single row subquery
Single row operator with Multiple row sub query Use IN/NOT IN instead of =, LIKE, BETWEEN, IS, <> [can’t use]
• *Comparison of two null values yields a null then where condtn. Is not true
• in
• any <any less than the maximum >any more than the maximum =any as IN
• all <all more than the maximum >all less than the maximum <>ALL as NOT IN
• not operator can be use with in any all
<ANY EQUIVALANCE
select ename,sal,job from emp where sal<(select max(sal) from emp group by job having job='SALESMAN')
and job !='SALESMAN';
select ename,sal,job from emp where sal<any (select sal from emp where job='SALESMAN');
>ANY EQUIVALANCE
select ename,sal,job from emp where sal>(select min(sal) from emp group by job having job='SALESMAN');
select ename,sal,job from emp where sal>any (select sal from emp where job='SALESMAN');
<All EQUIVALANCE
select ename,sal,job from emp where sal<(select min(sal) from emp group by job having job='SALESMAN');
select ename,sal,job from emp where sal<all (select sal from emp where job='SALESMAN') ;
> All EQUIVALANCE
select ename,sal,job from emp where sal< (select min(sal) from emp group by job having job='SALESMAN');
select ename,sal,job from emp where sal> all (select sal from emp where job='SALESMAN') ;
Cartesian product
Join condtn omitted/invalid
All rows in 1st table joined to all rows in 2nd table
Type of joins
Equijoin simple join /inner join based on primary keys and foreign keys
You can join n tables (all having single column primary keys) in a SQL statement by
specifying a minimum of n-1 join conditions
Non-Equijoin don’t use = between is simplest process for non-equijoin
Outer Join (+) placed on the side of the join that is deficient/missing in information
in/or operator prohibited
Self Join
*If common column define qualifying ambiguous column names with table aliases upto 30 char Sql 1999
ANSI SQL Join EQUIVALANCE ORACLE SQL
Cross same as Cartesian product
Natural common column (same name and datatype) used
ON clause Join on (col name) Equijoin
Using clause join using Non-equijoin
Left/Right/Full outer join Left outer join Outer join

• FULL OUTER JOIN TO VIEW all unmatched data from both tables.
• Arbitary join condtn. On outer join And expression
• Outer join can appear only one side of the expression
• In OUTER JOIN Cannot use IN operator/cannot be linked with OR operator
• You cannot link a condition that is involved in an outer join to another condition by using the OR operator.
Equivalence in Outer joins:
SELECT last_name, department_name FROM employees e RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id);
-4-
Introduction to 9i SQL Handbook
Same as
SELECT e.last_name,d.department_name FROM employees e,departments d
Where e.department_id(+) = d.department_id;
SELECT last_name, department_name FROM employees e LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id);
Same as SELECT e.last_name,d.department_name FROM employees e,departments d where
e.department_id = d.department_id(+);

Isql*plus environment browser/internet/net environment


• Temporary store values substitution variables & && define
• substitution variables used anywhere in select statement
• define variable CHAR type available for the session or until undefine
• define x = a define x DEFINE X = "a" (CHAR)
• define undefine x
• Alias always in “ Alias name” {select ename [as] “employee Name” from emp;}
• Isql*plus does not support validation check on user input
• Altering dynamically headers and footers
• Passing values to one sql to another
• Verify on: force to show toggle between old & new substitution values
• Verify off
• Set to control current session
• SET ECHO ON ECHO is system variable
• Show echo/all to verify the set variables
Example of Define command
DEFINE _CONNECT_IDENTIFIER = "ORADB" (CHAR)
DEFINE _SQLPLUS_RELEASE = "902000100" (CHAR)
DEFINE _EDITOR = "Notepad" (CHAR)
DEFINE _O_VERSION = "Oracle9i Enterprise Edition Release 9.2.0.1.0 – Production With the Partitioning, OLAP and Oracle Data
Mining options JServer Release 9.2.0.1.0 - Production" (CHAR)
DEFINE _O_RELEASE = "902000100" (CHAR)
DEFINE SAL = "aa" (CHAR)
DEFINE X = "a" (CHAR) */
Change column name
COLUMN column_name HEADING EMPLOYEE_ID
COLUMN column_name HEADING SALARY FORMAT $9999
COL[UMN]
COL column_name
COL column_name CLEAR
CLE[AR] COL
COL column_name NOPRINT
COL column_name PRINT
• Header ttitle text|off|on ttitle ‘salary|report’
• Footer btitle text|off|on btitle ‘confidential’
• Lengthy sql*plus command in script divide by hyphen(-)
• ORACLE SERVER Uses POUND SIGN # in place of whole number exceeds or numeric represented by
alphanumeric (actual format)
• BREAK TO DIVIDE ROWS INTO SECTIONS TO SUPRESS DUPLICATE VALUES
• CLEAR BREAK
• REM  REMARK
Sample report
SET PAGESIZE 50
SET LINESIZE 50
SET FEEDBACK OFF
TTITLE 'NIC REPORT'
BTITLE 'CONFIDENTIAL.'
BREAK ON DEPTNO
COLUMN DEPTNO HEADING Department|Name FORMAT 999

-5-
Introduction to 9i SQL Handbook
COLUMN ENAME HEADING Employee|Name FORMAT A10
COLUMN SAL HEADING Employee|Salary FORMAT $99,999.99
SPOOL C:\SCRIPT1.LST
REM ‘it is the salary table from emp’
SELECT DEPTNO,ENAME,SAL FROM EMP WHERE SAL<1500 GROUP BY DEPTNO,ENAME,SAL;
SPOOL OFF
HOST EDIT C:\SCRIPT1.LST
EXIT

DML statements (insert,update,delete,merge) form a logical unit of work  Transaction


DELETE:
• Delete all existing rows from a table, if no rows are deleted a message 0 rows deleted is returned.
• Used by specifying where / ANY SUBQUERY or not specifying where clause.
• DELETE FROM EMP WHERE DEPTNO = 10; DELETE FROM EMP;
• If table is parent of referential integrity constraint, Cannot DELETE must disable the constraint before DELETE

Insert :
• sub query in where clause WITH CHECK OPTION on which column must be in values(list)
• DEFAULT keyword to identify a default column value use only in insert or update command
• No default value oracle sets the column null
Merge:
• Avoids separate value updates
• Increase performance and ease of use
• Useful in Data warehousing applications
• Need both insert or update privilege
• Alternative approach to use PL/SQL blocks or loops
Sample Merge
MERGE INTO new_employees c
USING employees e
ON (c.employee_id = e.employee_id)
WHEN MATCHED THEN
UPDATE SET c.name = e.first_name ||’,’|| e.last_name
WHEN NOT MATCHED THEN
INSERT VALUES(e.employee_id, e.first_name ||’,‘||e.last_name);
Transaction
• Ensures data consistency based on Transactions (user process failure/system failure)
• consists one of 1. DML STATEMENTS 2. only one DDL 3.only one DCL statements
• begin when first DML executes
• Commit/rollback
• DDL or DCL statements (automatic commit)
• Exits iSQL*Plus/abnormal termination of iSQL*Plus
• System Crashes entire transaction rolled back
• Transaction Control (Commit/rollback/savepoint savepoint_name /rollback to savepoint_name)
• Autocommit [on|off]
• Commit/rollback Ensures data consistency/preview data changes/group logically related operations
• Creating second savepoint with same name earlier savepoint is deleted
Example of Transactional statements:
CREATE table new_emp ( employee_id NUMBER, name VARCHAR2(30));
INSERT INTO new_emp SELECT employee_id , last_name from employees;
Savepoint s1;
UPDATE new_emp set name = UPPER(name);
Savepoint s2;
Delete from new_emp;
Rollback to s2;
Delete from new_emp where employee_id =180;
UPDATE new_emp set name = 'James';

-6-
Introduction to 9i SQL Handbook
Rollback to s2;
UPDATE new_emp set name = 'James' WHERE employee_id =180;
Rollback;
At the end of this transaction, you have no rows in the table.
Before Commit /Rollback
• Affect the database buffer so Previous state of data can be recovered
• Current user can review results of DML by querying
• Other user cannot view the results of DML by Current user
• Affected row rows are locked
After Commit
• Data changes written to database
• Previous state of data lost permanently
• All user view the results
• Locks are released
• Savepoint are erased
After Rollback
• Previous state of data recovered
• Data changes are undone
• All pending transactions are deleted.
• Locks are released
Statement level rollback
• Single DML fails, only that statement rolled back
• Oracle server issues an implicit commit or savepoint before or after DDL
Read Consistency
1. An automatic implementation
2. insert,update,delete issued oracle server takes a copy of unchanged data in undo segment
3. All users except the issuer view data from rollback segment as snapshot
4. After commit space occupied by undo segment is freed for reuse
5. Oracle server Guarantees a consistent view of data at all times
6. Changes made by one user do not conflict Changes made by other user
7. Read operation(select)/write operation (insert,update,delete)
8. Readers don’t wait for writers/Writers don’t wait for readers

Locks:
• Prevent destructive interaction between concurrent transactions
• Require no user action
• Use automatically the lowest level of restrictiveness
• Held when transaction in progress
• Lock Two types Explicit & Implicit
• Implicit locking occurs for all SQL statements except SELECT
o Exclusive: locks out other users
o Share: Allows other user to access
o High level of data concurrency
o DML: table share row exclusive
o Queries: no lock
o DDL: protects object definitions
o Locks held until commit or rollback
• Explicit locking User puts manual lock
Database Objects: Table Basic unit of storage; rows and columns
• Table can be created anytime, online structure modification no need to specify memory size of table, size
ultimately defined by amount of space allocated to the database
Naming Rules:
o Must be 1-30 characters long. Object names or Qualifier are case insensitive EMP or emp same
o Should not be an Oracle Server reserved word.
o Must contain only A-Z, a-z, 0-9, _, $, and #.
o Must begin with a letter.(use descriptive name)
-7-
Introduction to 9i SQL Handbook
o Must not a duplicate name of another object owned by same user.
• Before construct a table see 1. Create table privilege 2. Storage area
• Input: Table name, column data type, name and size.
• Create DDL statement: to store structure, immediate effect on database, record information in data-
dictionary.
• Create table DDL command Auto commit happens
Schema is collection of objects, the logical structures that directly refer to data in a database.
Schema Objects: TABLES, VIEWS, SYNONYMS, SEQUENCES, STORED PROCEDURES, INDEXES, CLUSTERS, DATABASE LINKS
Schema is owned by user and has the same name as user name, tables belonging to other users not in current
user schema, to access use user name as prefix user.Obj_name
• Default value for a column during an insert as Hire_date DATE DEFAULT SYSDATE User_name varchar2(10)
DEFAULT USER
• Default value accepts Literal values, expressions, SQL functions [legal values]
• Default value does not accept another column’s name or a pseudo column [illegal values]
• Default data type must match column data type

Tables in Oracle database


User table collections of tables created and maintained by user/ contain user information
Data dictionary collections of tables created and maintained by Oracle server/ contain database information
Data dictionary tables’ owner is SYS user
Data dictionary information: Names of Oracle server users, privileges granted, database object names,
Table Constraints, Auditing information
4 categories of Data dictionary views (with distinct prefix)
USER_ views contain user’s object information
ALL_ views contain all tables (object & relational) information accessible to user
DBA_ restricted views accessible by DBA role granted users
V$ views contain dynamic performance views, Database server performance, memory, locking
Imp query: select table_name from USER_TABLES; | select distinct object_type from USER_OBJECTS;
select * from USER_catalog; USER_catalog=synonym=CAT | select distinct type from all_source;
Create table using subquery:
• Column definitions can contain only column name and default value
• Integrity rules are not passed onto new table.
• If in subquery any function or calculation used as sal*10 or upper (name) then a new column alias must
be used.
Add a new column ALTER TABLE table_name ADD (col_name data_type(size));
• Add or modify but can’t specify where the column is to appear (as last column)
• If table already contains rows then added column is initially null for all the rows
Modify an existing column ALTER TABLE table_name modify (col_name data_type(size));
• Change data type, size, and A change to the DEFAULT value affects only subsequent insertions to table.
• Increase width of numeric or character/ precision of a numeric column
• Decrease width of column if column contains only null values or has no rows
• Change data type if column contains only null
• Data type change possible for: CHAR TO VARCHAR2 or VARCHAR2 TO CHAR if column contains only null
values or the size is same.
Drop a column ALTER TABLE table_name DROP COLUMN col_name; (from Oracle 8i)
• Column may/may not contain data
• Only one column dropped at a time
• Must have one column remaining after alter
• Dropped column cant be recovered.
UNUSED COLUMN IN TABLE
• To mark a column as unused so that it can be dropped when system resource is lower.
• Treated as they are dropped even they exists.
• If column marked as unused user has no access to those columns.
• Both in desc table_name and Select * from table_name command user cannot view those used column.
• User can also add a new column using same name of unused column
-8-
Introduction to 9i SQL Handbook
• Unused column information stored in USER_UNUSED_COL_TABS dictionary view.
• UNUSED statements complete a transaction
ALTER TABLE TABLE_NAME SET UNUSED (COLUMN_NAME);
ALTER TABLE TABLE_NAME SET UNUSED COLUMN COLUMN_NAME;
ALTER TABLE TABLE_NAME DROP UNUSED COLUMNS; (If table contains no UNUSED columns, statement returns with no error)
DROP TABLE: DROP TABLE TABLE_NAME
• All data & structure is deleted, All Indexes associated with it are dropped, view and synonym remain but
invalid.
• Any pending transactions are committed, as DROP DDL command Auto commit happens, can’t rollback.
• Creator/Owner user or high level privileged user (DROP ANY TABLE) can DROP table.
• Rename of Object (TABLES, VIEWS, SYNONYMS, SEQUENCES)
• RENAME old_table_name to new_table_name; // Owner user can do it. DDL command Auto commit
happens.
Truncate: TRUNCATE TABLE TABLE_NAME
• Remove all rows from a table
• Owner user or high level privileged user (DELETE TABLE) can DROP table.
• DDL command Auto commit happens, CANNOT ROLLBACK
• Release storage space used by that table
• If table is parent of referential integrity constraint, Cannot truncate, must disable the constraint before TRUNCATE.
The Main Difference between DELETE & TRUNCATE are:-
1. DELETE - is a DML Command & TRUNCATE - is a DDL Command
2. After DELETE - can rollback the Records & After TRUNATE - cannot rollback the records
3. In DELETE Command you can give the conditions in WHERE Clause & In TRUNCATE you cannot give conditions
4. After using DELETE Command the memory will be occupied till the user does not give ROLLBACK or COMMIT & after
using TRUNCATE Command the memory released immediately.
5. TRUNCATE Command is faster than DELETE Command because it does not fire the delete triggers of the table.
COMMENTS:
• Add comment up to 2000 bytes about a column, table, view or snapshot
• Comment can be viewed from following data dictionary views:
• ALL_COL_COMMENTS USER_COL_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS

• Add Comment: COMMENT ON TABLE table_name is ‘Table Information’;


• COMMENT ON COLUMN table_name.column_name is ‘Column Information’;
• Drop Comment (empty string): COMMENT ON TABLE table_name is ‘ ’;

Constraints
• Oracle server uses constraints to prevent invalid data entry into tables.
• Constraints must be satisfied for the operation to succeed.
• Enforce rules at table and view level. (Row insertion, deletion, updating).
• To prevent DELETION OF A TABLE if there are dependencies.
• Provide rules for Oracle Tools (e.g. Oracle Developer).
• Constraints stored in data dictionary (USER_CONSTRAINTS).
• Provide a meaningful name follow standard object-naming rules.
• If not specify name Oracle server generates a name as SYS_Cn [n is integer to make the name unique]
• Create a constraint at the same time or after of table creation.
• Define a Constraint in table or column level.
• Create table schema.table_name (column_name data type(size) [default expr] [column_constraint], …,
[table_constraint]);
• column_constraint level: reference a single column defined within a specification for owning column,
define any type of integrity constraint. column [constraint constraint_name] constraint_type
e.g. create table t1(Emp_id number(6) constraint emp_id_uk unique, ename char(10) not null);
here constraint for Emp_id is user named & constraint for ename system named
table_constraint level: reference one or more columns defined separately from definitions of column, any type of
integrity constraint except NOT NULL. [constraint constraint_name] constraint_type (column_name)
e.g. create table t1(Emp_id number(6), ename char(10) not null, constraint emp_id_uk unique(Emp_id));
-9-
Introduction to 9i SQL Handbook

• NOT NULL can be specified only in column level not in table level
• UNIQUE every value in a column must be unique
• Single column (set of columns) uses this constraint is called unique key if two or more column comprises
this groups of columns is called composite unique key.
• UNIQUE can be specified in column or table level. Composite unique key specified table level
• Unique Constraints allow the input of nulls because nulls are not considered equal to anything. So
user also defines NOT NULL to prevent null acceptance
• Oracle server enforces UNIQUE constraints by implicitly creating a unique index on the unique key
column or columns.
• Primary key constraint is a column or sets of columns, only one primary key is defined.
• Enforce uniqueness for column or column combination but don’t accept null values.
• Primary key can be specified in column or table level. Composite Primary key specified table level
• Table contains only one primary key constraint but several unique constraints.
• A UNIQUE index is automatically created for a Primary key column.
• Foreign Key referential integrity designates a column or combination of columns & establishes a
relationship between a primary key or a unique key in same or different table.
• Foreign Key must match an existing value in the parent table or be NULL.
• Foreign Key are based on data values and are purely logical, not physical, pointers.
• Foreign key can be specified in column or table level. Composite Foreign key specified table level
• create table t1(Emp_id number(6) constraint emp_id_fk references dept (Emp_id));
• create table t1(Emp_id number(6), constraint emp_id_fk Foreign key (Emp_id) references
dept (Emp_id));
• FOREIGN KEY: Defines the column in the child table at the table constraint level
• REFERENCES: Identifies the table and column in the parent table
• ON DELETE CASCADE: deletes the dependent rows in the child table when a row in parent table
is deleted
• ON DELETE SET NULL: converts dependent foreign key values to null when parent table is deleted
• Default behavior of Foreign Key is called Restrict rule.
• CHECK is a condition that each row must satisfy (both column or table level)
• References to CURRVAL, NEXTVAL, LEVEL, ROWNUM pseudocolumns
• Calls to SYSDATE, UID, USER AND USERENV functions
• Queries that refer to other values in other rows
• Single column can have multiple CHECK Constraints which refer to the column in its definition.
• No limit to the no. of CHECK Constraints which user can define on a column.
• salary number(8) check (salary>0) | city varchar2(10), constraint emp_city_ck check (city
in (‘Kol’,’Delhi’,’Mumbai’))
• Add or Drop a constraint but can’t modify its structure
• ALTER TABLE ADD constraint constraint_name constraint_type (COLUMN_NAME[s]);
• ALTER TABLE EMP ADD CONSTRAINT EMP_MANAGER_FK FOREIGN KEY (MGRID) REFERENCES
EMP(EMPID);
• If user doesn’t specify constraint_name system itself generate a name.
• Change existing column to not null constraint if the table is empty or column has value for every row.
• Add a NOT NULL constraint only by using MODIFY clause of ALTER TABLE statement
• ALTER TABLE T1 MODIFY NAME CONSTRAINT NAME_NN NOT NULL;
• ALTER TABLE TABLE_NAME DROP CONSTRAINT constraint_name
• CASCADE option used to drop dependent constraints (referential integrity to PK or UK).
• CASCADE CONSTRAINTS used along DROP COLUMN clause/to drop multicolumn constraints.
• ALTER TABLE TABLE_NAME DROP primary key|unique(column)| CONSTRAINT constraint_name [cascade];
• ALTER TABLE TABLE_NAME DROP (column_name) CASCADE CONSTRAINTS;
• After dropping a constraint it no longer available by Oracle server data dictionary
- 10 -
Introduction to 9i SQL Handbook
• DISABLE Clause to deactivate an integrity constraint/ apply cascade to disable dependent constraint
• Alter table table_name disable constraint constraint_name cascade;
• Disabling a unique or primary key constraint removes the unique index
• Enable Clause to activate an integrity constraint used both in CREATE TABLE or ALTER TABLE statement
• After enabling constraint, data must fit to it otherwise report error.
• Enabling a unique or primary key constraint create the unique index
• Enabling a primary key constraint disabled with CASCADE option does not enable foreign keys dependent
on this primary key.
• Data dictionary views to view constraints for user given or system-assigned name
• Select CONSTRAINT_name, CONSTRAINT_type, search_condition from USER_CONSTRAINTS;
o Here C CHECK, P PRIMARY KEY, RREFERENTIAL INTEGRITY, UUNIQUE KEY
o NOT NULL also CHECK type CONSTRAINT.
• Select CONSTRAINT_name, column_name from USER_CONS_COLUMNS;
Database Objects: View logically represents subsets of data from one or more tables
• A view itself contains no data but a window through which data from another table can viewed or
changed.
• Tables are called base table. View is stored as SELECT statement in data dictionary.
• Use views to restrict data access, to make complex queries easy, to provide data independence for ad
hoc users and application programs, to present different views of the sane data according particular
criteria.
• Simple View derived data from one table, Contains no functions or groups of data, allow DML
operations.
• Complex View derived data from many tables, Contains functions or groups of data, not always allow
performing DML operations (Select, insert, delete, update) through view.
• Cannot remove a row if view contains:
o Group Functions, Group by clause, distinct clause, ROWNUM keyword

• Cannot modify/update data if view contains:


o Group Functions, Group by clause, distinct clause, ROWNUM keyword, column
defined by expressions (as sal*12)

Cannot add data if view contains:


o Group Functions, Group by clause, distinct clause, ROWNUM keyword, column
defined by expressions (as sal*12), not null columns without default values in base
tables not selected by the view
• Embed a subquery (containing complex select statement) within create view statement.

CREATE OR REPLACE FORCE [NOFORCE by default] VIEW EMPVU80


(EMPLOYEE_ID80,LAST_NAME80,SALARY80) //(Alias)
AS SELECT EMPLOYEE_ID,LAST_NAME,SALARY FROM emp WHERE employee_ID=1
WITH CHECK OPTION CONSTRAINT constraint_name
WITH READ ONLY CONSTRAINT constraint_name;
• Use or replace to recreate the views with new values from table
• If no column exists in table but used in subquery user uses FORCE command result:
• “Warning: View created with compilation errors.” By default NOFORCE used as base tables exist.
Alias column names must match the number of expressions selected by the view and aliases are listed in the
same order as columns in subquery.
WITH CHECK OPTION specifies that only rows accessible to the view can be inserted or updated. Acts upon
where clause, to perform referential integrity checks through views, enforces constraints in database level. Data
validation check, if user want to modify employee_ID=2 it results error.
WITH READ ONLY to deny DML operations, if DML operations performed results Oracle server error “virtual
column not allowed here”

- 11 -
Introduction to 9i SQL Handbook
• Complex views contains group functions, joins to display values from two tables
• Remove/Drop view without data loss because view is based on underlying tables in database
• DROP VIEW view_name; remove view definitions from database.
• Creator or user with DROP ANY VIEW privilege can drop a view
• Inline view is a subquery with an alias or correlation name use within SQL statement
• Placing a subquery in the from clause and giving the subquery an alias
• Subquery defines a data source referred in main query.
• E.g. Select a.last_name, a.salary, b.maxsal from employees a, (select department_id, max(salary)
maxsal from employees group by department_id) b where a.department_id = b.department_id;
• Top-n analysis to display n top-most or n bottom-most records from a table based on condition
• Top-n queries use a consistent nested query structure (High level structure) as
• A subquery/ outer query or inline view to generate sorted list of data and ORDER BY clause
• Outer query to limit no. of rows in final result set including ROWNUM pseudo column assigns a sequential
value starting from 1 to each of the rows returned from the subquery
• An Outer where clause specifies the n rows to be returned, must use < or <= operator.
• E.g1. select last_name,salary, rownum from (select last_name,salary from employees order by salary
desc) where rownum<=&n;
• E.g2. SELECT LAST_NAME,SALARY FROM EMPLOYEES WHERE SALARY = (SELECT MIN(SALARY) FROM
(SELECT DISTINCT(SALARY) FROM EMPLOYEES ORDER BY SALARY DESC) WHERE ROWNUM <=&X);
• Data dictionary view: user_views select VIEW_NAME,TEXT from user_views;
• SET LONG 1000 OR Select VIEW_NAME,TEXT from user_views ORDER BY LINE;
• You want to look at the definition of the EMP_DEPT_VU view?
• Query the USER_VIEWS data dictionary view to search for the EMP_DEPT_VU view
Database Objects: Sequence Numeric value generator
• Generate unique sequential numbers
• Sharable object for multiple tables as created independently of tables.
• used to create primary key value, belong to a specific schema
• time saving object as reduce or replaces application code needed to write a sequence generating routine
• speeds up efficiency of accessing sequence values when cached in memory
• incremented or decremented by internal oracle routine
• caching sequence values in memory gives faster execution
• gaps created when rollback occurs, system crashes, sequence used in another table,
CREATE SEQUENCE sequence_EX
increment by 10
Start with 100
Maxvalue 1000
Nocycle | CYCLE
Nocache | CACHE 25
CREATE SEQUENCE sequence_name
increment by a
Start with b
Maxvalue c |nomaxvalue [10^27 ascending sequence -1 descending sequence]
Minvalue d |nominvalue [1 ascending sequence – (10^26) descending sequence]
Nocycle | Cycle [continue to generate values after reaching its max or min value]
Cache e | nocache [oracle server preallocates and keep values in memory default 20 values]

• If SEQUENCE used in primary key don’t use CYCLE option


• Do not use MAXVALUE AND MINVALUE AT SAME TIME.
• CONFIRM SEQUENCE FROM user_objects then user_sequences DATA DICTIONARY TABLE
select SEQUENCE_NAME,MIN_VALUE, MAX_VALUE, INCREMENT_BY, CYCLE_FLAG, CACHE_SIZE,
LAST_NUMBER from user_sequences;
• LAST_NUMBER column displays next available sequence no if Nocache is specified
NEXTVAL & CURRVAL are pseudo columns

- 12 -
Introduction to 9i SQL Handbook
o NEXTVAL RETURNS next available sequence value, different/unique for each time even for
different users by actually retrieving the value from the sequence.
o CURRVAL obtains current available sequence value, without affecting the further values to be
generated from the sequence.
o NEXTVAL must be issued for a sequence 1st time before CURRVAL contains a value.
• select SEQUENCE_EX.NEXTVAL from dual;
• select SEQUENCE_EX.CURRVAL from dual;
• Usage in : select list of a select statement not a part of subquery
o select list of a subquery in an INSERT statement
o values clause in an INSERT statement
o set clause of an update statement
• Not Usage in : select list of a view
o Select statement with distinct keyword, group by, having, order by clause
o subquery in SELECT, UPDATE, DELETE statement
o DEFAULT expression in create table or alter table
• Insert into dept(deptno,dname) values (dept_seq.nextval,’AMC’);
• Modify sequence only increment value, maxvalue, minvalue, cycle or cache option.
• To modify user must have ALTER privilege
• Only future sequence numbers are affected
• If Maxvalue limit is reached modify maxval to continue, cant modify start with once created.
• Then sequence dropped and re-created to restart sequence at a different number
• Validation like maxvalue can’t less than current value performed
• Remove a sequence user must have DROP SEQUENCE privilege
• DROP SEQUENCE sequence_name; //no longer be referenced upon deletion
Database Objects: Index Improve performance of some queries
• Index is a schema object, used and maintained automatically by oracle server to speed up the retrieval of
rows by using a pointer
• Can reduce disk I/O by using rapid path access method to locate data quickly
• Is logically and physically independent of the table it indexes
• Can drop any time without affecting the base tables or indexes
• Direct and fast access to rows, without index on a column a full table scan occurs
• Created explicitly or automatically; after creation no direct activity required by user
• Automatically unique index created when primary key or unique constraints are used
• Name of index same as constraint name
• User explicitly creates non-unique index on column to fast access to rows
• CREATE INDEX index_name ON table_name (column_name1,…, column_nameN);
• Function base index based on expression (table columns, constants, SQL function, user-defined
functions)
• CREATE INDEX index_name ON table_name UPPER(column_name1); //case-insensitive search
• ORACLE SERVER TREATS INDEXES WITH COLUMNS MARKED desc AS Function base index
• More indexes mean more effort to oracle server to update those indexes, because when DML statement
committed to table index must be updated.
When to create index:
• When column contains wide range of values, large no. of null values, one or more columns are frequently
together in a WHERE or JOIN condition, large table and most of queries uses less than 2-4% of the rows.
• Better approach to make a column applied unique constraint
When not to create index:
• Table is small, updated frequently, columns are not often used in where or JOIN clause, most of queries
uses more than 2-4% of the rows, indexed columns are referenced as apart of an expression.
Data dictionary views: USER_INDEXES (INDEX_NAME, INDEX_TYPE, TABLE_NAME, UNIQUENESS)
USER_IND_COLUMNS (INDEX_NAME, TABLE_NAME, COLUMN_NAME, COLUMN_POSITION)
• Cannot modify an index must drop then recreate it.
• Remove AN INDEX user must have DROP ANY INDEX privilege
• DROP INDEX index_name; //to remove index definition from data dictionary
- 13 -
Introduction to 9i SQL Handbook
• If any table is dropped dependent indexes , constraints also dropped, but vies and sequences
remain.
Database Objects: Synonym Alternative names to objects
• Simplify access to objects by creating synonym
• Ease referring to a table owned by another user
• Shorten lengthy object names
• Object cannot be contained in a package
• Public synonym accessible to all users, CREATES ONLY BY DATABASE ADMINISTRATOR
• Private synonym must be distinct from all other objects owned by same user
• CREATE SYNONYM synonym_name FOR object_name;
• CREATE PUBLIC SYNONYM synonym_name FOR user. object_name;
• DATABASE ADMINISTRATOR only drop public synonym
• DROP [PUBLIC] SYNONYM synonym_name;
• View public synonyms from all_synonyms and user created synonyms from user_synonyms tables.
SPECIAL Cases
• DBA CREATE PUBLIC SYNONYM xyz FOR userA.object_name;
• userB has a user object named xyz.
• userB queries select * from xyz;
• result from userB.xyz object not from public synonym;
DATABASE LINKS
CONN SYS/SYS AS SYSDBA
SQL> CREATE PUBLIC DATABASE LINK HQ.ACME.COM USING 'ORADB'; //ORADB SERVICE NAME
Database link created.
TABLE_NAME in DICTIONARY 1.ALL_DB_LINKS 2.DBA_DB_LINKS 3.USER_DB_LINKS
SQL> SELECT * FROM ALL_DB_LINKS;
SQL>SELECT * FROM DBA_DB_LINKS;
OWNER DB_LINK
------------------------------ ----------------------------------
PUBLIC HQ.ACME.COM
SQL> CONN HR/HR
Connected.
SQL> SELECT * FROM EMPLOYEES@HQ.ACME.COM;
Controlling user access
• Oracle server database security: control database access
• Give access to specific objects
• Confirm given and received privileges with the data dictionary
• Create synonyms for database objects
• System security: use of database at system level username password disk space allocation system
operations
• Data Security: access and use of database objects actions taken by user on those database objects
• Privilege is the right to execute particular SQL statement [DBA is high-level user ability to grant user
access to database and its objects

System Privilege: gaining access to database


• More than 100 Privileges available for users and roles
• Only DBA provides System Privileges  CREATE USER, DROP USER, DROP ANY TABLE, BACKUP
ANY TABLE, SELECT ANY TABLE, CREATE ANY TABLE
• DBA can create user as CREATE USER user_name IDENTIFIED BY password
• Change password by user: alter user user_name identified by new_password; or command
password
• After creating user, user has no privilege or can’t action on database
• GRANT user certain privilege: GRANT privilege_name to user_name|role_name|PUBLIC;
• SOME privileges name: CREATE SESSION|TABLE|VIEW|SEQUENCE|PROCEDURE
- 14 -
Introduction to 9i SQL Handbook
• Public means grant privilege to all database user
• Users also be given the privilege to grant additional privilege to other user or to roles, role is named
group of related privileges that can be granted to the user
• Is a method to make easier revoke or maintain privileges
• Only DBA can Create role as CREATE ROLE role_name;
• Grant privilege_name[s] to role_name; Grant role_name to user _name[s];
• A user can have access to several roles, and several users can be assigned the same role.
• Granted current system privilege can be viewed from SESSION_PRIVS data dictionary view
Object Privilege: To Manipulate content of database objects
• Perform particular action on a specific TABLE|VIEW|SEQUENCE|PROCEDURE
• Some Object Privileges: ALTER|DELETE|EXECUTE|INDEX|INSERT|REFERENCES|SELECT|UPDATE
• TABLE/SYNONYM: ALTER|DELETE|INDEX|INSERT|REFERENCES|SELECT|UPDATE
• VIEW: DELETE|INSERT|REFERENCES|SELECT|UPDATE
• SEQUENCE: ALTER|SELECT
• PROCEDURE: EXECUTE
• Owner of an object has all privilege or all object in it’s schema, can give specific privilege on that object
• GRANT object_privilege(s)|ALL on object_name TO user_name(s)|role_name(s)|PUBLIC
[with grant option];
• with grant option It allows the grantee to grant object privileges to other users and roles.
• E.g. GRANT SELECT ON EMP TO SCOTT; EMP is a HR user’s table
Now scott access the emp table as select * from HR.EMP;
DBA generally allocate System privileges and User grants object privileges
Granted Object privileges can be viewed from following data dictionary view
USER_COL_PRIVS_MADE
USER_COL_PRIVS_RECD
USER_ROLE_PRIVS
USER_SYS_PRIVS
USER_TAB_PRIVS
USER_TAB_PRIVS_MADE
USER_TAB_PRIVS_RECD
ROLE_ROLE_PRIVS
ROLE_SYS_PRIVS
ROLE_TAB_PRIVS
Revoke privilege
REVOKE { privilege [,privilege…]|ALL} on object from {user[,user…]|role|PUBLIC}[CASCADE CONSTRAINTS];
CASCADE CONSTRAINTS is required to remove any referential integrity constraints made to object by means of
the REFERENCES privilege Revoke select, insert On dept from scott;

Data types
ROWID: A hexadecimal string representing the unique address of a row in its table.
Which three are DATETIME data types that can be used when specifying column definitions?
1. TIMESTAMP
2. INTERVAL DAY TO SECOND
3. INTERVAL YEAR TO MONTH

Statements:
Data Retrieval SELECT
DML INSERT, UPDATE, MERGE, DELETE
DDL CREATE, ALTER, DROP, RENAME, TRUNCATE
Transaction Control COMMIT, ROLLBACK, SAVEPOINT
DCL GRANT, REVOKE

- 15 -
Introduction to 9i SQL Handbook

DELETE employee_id, salary, job_id FROM employees WHERE dept_id = 90;


DELETE statement fail because user cannot specify column names in the DELETE clause of the DELETE
statement.
DELETE FROM employees WHERE dept_id = 90; if no rows are deleted a message 0 rows deleted
is returned.

Self Join:
Which statement lists the ID, name, and salary of the employee, and the ID and name of the
employee's manager, for all the employees who have a manager and earn more than 4000?

SELECT e.employee_id "Emp_id", e.last_name "Employee", e.salary,


m.employee_id "Manager_id", m.last_name "Manager"
FROM employees e, employees m
WHERE e.manager_id = m.employee_id
AND e.salary > 4000;
Which statement shows the department ID, minimum salary, and maximum salary paid in that department, only
of the minimum salary is less then 3000 and the maximum salary is more than 7000?
SELECT department_id, MIN(salary), MAX(salary) FROM employees GROUP BY department_id
HAVING MIN(salary) < 3000 aND MAX(salary) >7000; OR
SELECT department_id, MIN(salary), MAX(salary) FROM employees HAVING MIN(salary) < 3000 aND
MAX(salary) >7000 GROUP BY department_id ;
RESULT:
DEPARTMENT_ID MIN(SALARY) MAX(SALARY)
------------- ----------- -----------
30 2500 11000
50 2100 8200
SELECT department_id, MIN(salary), MAX(salary) FROM employees GROUP BY department_id, salary
HAVING MIN(salary) < 3000 AND MAX(salary) >7000;
no rows selected
select &1,&2 from &3 where ename = '&4';
SELECT ROUND(456.953,-1) FROM DUAL; 460 SELECT TRUNC (456.953,-1) FROM DUAL; 450
SELECT ROUND(456.953,-2) FROM DUAL; 500 SELECT TRUNC (456.953,-2) FROM DUAL; 400
SELECT ROUND(456.953,-3) FROM DUAL; 0 SELECT TRUNC (456.953,-3) FROM DUAL; 0
SUBSTR(‘RAKESH’,-1 = SUBSTR(‘RAKESH’,-1,1) H

Subquery used in
1. From clause of a select statement
2. Where clause of a select statement
3. Update clause of a set statement
4. Values clause of a insert statement
IT WORKS:
SELECT ENAME,SAL FROM EMP WHERE SAL IN (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO);

Examine the data in the EMPLOYEES and DEPARTMENTS tables.


You want to retrieve all employees' last names, along with their manager's last names
and their department names. Which query would you use?
SELECT e.last_name, m.last_name, department_name
FROM employees e
LEFT OUTER JOIN employees m on ( e.managaer_id = m.employee_id)
LEFT OUTER JOIN departments d ON (e.department_id = d.department_id);

SQL> SELECT SUM(SAL), MAX(SAL) FROM EMP WHERE HIREDATE > '17-DEC-80';
SUM(SAL) MAX(SAL)
---------- ----------
28225 5000
SQL> SELECT SUM(SAL), MAX(SAL) FROM EMP WHERE HIREDATE BETWEEN '17-DEC-80' AND '17-DEC-83';
SUM(SAL) MAX(SAL)
---------- ----------
- 16 -
Introduction to 9i SQL Handbook
24925 5000

SELECT D.DEPARTMENT_NAME
FROM EMPLOYEES E JOIN DEPARTMENTS D
ON (E.DEPARTMENT_ID = D.DEPARTMENT_ID)
WHERE E.JOB_ID LIKE 'SA_REP'
GROUP BY DEPARTMENT_NAME
HAVING COUNT(EMPLOYEE_ID)>5;

SELECT TEXT FROM USER_SOURCE where NAME LIKE 'ADDIT' ORDER BY LINE;

Inline view

select a.ename,a.sal,a.deptno,b.maxsal from emp a,


(select deptno, max(sal) maxsal from emp group by emp.deptno)b
where a.deptno = b.deptno
and a.sal<b.maxsal

1 CLARK 2695.00 10 5000


2 MILLER 1300.00 10 5000
3 SMITH 800.00 20 3000
4 ADAMS 1100.00 20 3000
5 JONES 2975.00 20 3000
6 ALLEN 1600.00 30 2850
7 MARTIN 1250.00 30 2850

TOP N Analysis

select rownum as rank,ename , sal


from (select ename,sal from emp order by sal desc)
where rownum<=3

1 1 KING 5000.00
2 2 SCOTT 3000.00
3 3 FORD 3000.00

select ename,sal, rownum from (select ename,sal from emp order by sal desc) where rownum<=&n; --4

1 KING 5000.00 1
2 SCOTT 3000.00 2
3 FORD 3000.00 3
4 JONES 2975.00 4

SELECT ename,SAL FROM EMP WHERE SAL =


(SELECT MIN(SAL) FROM (SELECT DISTINCT(SAL) FROM EMP ORDER BY SAL DESC) WHERE ROWNUM <=&X); -- 2

1 SCOTT 3000.00
2 FORD 3000.00

--Inline view
select a.ename,a.sal,a.deptno,b.maxsal from emp a,
(select deptno, max(sal) maxsal from emp group by emp.deptno)b
where a.deptno = b.deptno
and a.sal<b.maxsal;

--TOP N Analysis

select rownum as rank,ename , sal


from (select ename,sal from emp order by sal desc)
where rownum<=3;

select ename,sal, rownum from (select ename,sal from emp order by sal desc) where rownum<=&n; --4

SELECT ename,SAL FROM EMP WHERE SAL =


(SELECT MIN(SAL) FROM (SELECT DISTINCT(SAL) FROM EMP ORDER BY SAL DESC) WHERE ROWNUM <=&X); -- 2
- 17 -
Introduction to 9i SQL Handbook
SELECT MIN(SAL) "2nd Highest" FROM (SELECT DISTINCT(SAL) FROM EMP
ORDER BY SAL DESC) WHERE ROWNUM <=2;

SELECT MAX(SAL) "2nd lowest" FROM (SELECT DISTINCT(SAL) FROM EMP


ORDER BY SAL ASC) WHERE ROWNUM <=2;

--connect by prior

select sal from emp


connect by prior sal<sal
group by sal

select max(sal) "2nd Highest" from emp


where level = 2
connect by prior sal>sal

select min(sal) "2nd Lowest" from emp


where level = 2
connect by prior sal<sal

select level, max(sal) "2nd Highest" from emp


where level=2 connect by prior sal > sal
group by level

----------------------------
--CONNECT BY PRIOR
--A condition that identifies the relationship between parent rows and child rows of the hierarchy
CONNECT BY <child_value> = <parent_value>
--conn hr/hr

SELECT employee_id, last_name, manager_id


FROM employees
CONNECT BY PRIOR employee_id = manager_id;

--START WITH
--Specifies a condition that identifies the row(s) to be used as the root(s) of a hierarchical query
START WITH (column_name) = <value>
--conn hr/hr

SELECT last_name, employee_id, manager_id, LEVEL


FROM employees
- 18 -
Introduction to 9i SQL Handbook
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id;

SELECT last_name, employee_id, manager_id, LEVEL


FROM employees
START WITH employee_id = 101
CONNECT BY PRIOR employee_id = manager_id;

set pagesize 0
col last_name format a30

SELECT LEVEL, LPAD(' ', LEVEL*3) || LAST_NAME AS LAST_NAME


FROM employees
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id;

set pagesize 20

--ORDER SIBLINGS BY
--SIBLINGS BY preserves any ordering specified in the hierarchical query clause and then applies the
order_by_clause to the siblings of the hierarchy ORDER SIBLINGS BY (column_name)
--conn hr/hr

SELECT last_name, employee_id, manager_id, LEVEL


FROM employees
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id
ORDER SIBLINGS BY last_name;

--CONNECT_BY_ROOT
--CONNECT_BY_ROOT is a unary operator that is valid only in hierarchical queries. When you qualify a
column with this operator, Oracle returns the column value using data from the root row.

--Cannot be specified with the START WITH or CONNECT BY condition. The following example returns
the last name of each employee in department 110, each manager above that employee in the hierarchy, the
number of levels between manager and employee, and the path between the two:
--conn hr/hr

set linesize 121


col emp format a20
col mgr format a20

SELECT "Name", SUM(salary) "Total_Salary"


FROM (
SELECT CONNECT_BY_ROOT last_name "Name", salary
FROM employees
WHERE department_id = 110
CONNECT BY PRIOR employee_id = manager_id)
GROUP BY "Name";

-- Thanks Colin for the correction

--CONNECT_BY_ISCYCLE Pseudocolumn
--The CONNECT_BY_ISCYCLE pseudocolumn returns 1 if the current row has a child which is also its
ancestor. Otherwise it returns 0
--conn hr/hr

UPDATE employees SET manager_id = 145


WHERE employee_id = 100;

set linesize 121


col path format a50

SELECT last_name, LEVEL, SYS_CONNECT_BY_PATH(last_name, '/') "Path"


FROM employees
WHERE LEVEL <= 3 AND department_id = 80
START WITH last_name = 'King'
CONNECT BY PRIOR employee_id = manager_id AND LEVEL <= 4;
--ERROR:
--ORA-01436: CONNECT BY loop in user data

SELECT last_name, CONNECT_BY_ISCYCLE "Cycle", LEVEL, SYS_CONNECT_BY_PATH(last_name, '/') "Path"


FROM employees
WHERE LEVEL <= 3 AND department_id = 80
START WITH last_name = 'King'
CONNECT BY NOCYCLE PRIOR employee_id = manager_id
AND LEVEL <= 4;
- 19 -
Introduction to 9i SQL Handbook
ROLLBACK;

--CONNECT_BY_ISLEAF Pseudocolumn
--The CONNECT_BY_ISLEAF pseudocolumn returns 1 if the current row is a leaf of the tree defined by the
CONNECT BY condition. Otherwise it returns 0. This information indicates whether a given row can be
further expanded to show more of the hierarchy.
--conn hr/hr

SELECT last_name "Employee", CONNECT_BY_ISLEAF "IsLeaf",


LEVEL, SYS_CONNECT_BY_PATH(last_name, '/') "Path"
FROM employees
WHERE level <= 3
AND department_id = 80
START WITH last_name = 'King'
CONNECT BY PRIOR employee_id = manager_id
AND LEVEL <= 4;

--LEVEL Pseudocolumn
--For each row returned by a hierarchical query, the LEVEL pseudocolumn returns 1 for a root row, 2 for
a child of a root, and so on
--conn hr/hr

SELECT employee_id, last_name, manager_id, LEVEL


FROM employees
CONNECT BY PRIOR employee_id = manager_id;

SELECT LPAD(' ',2*(LEVEL-1)) || last_name ORG_CHART,


employee_id, manager_id, job_id
FROM employees
START WITH job_id = 'AD_VP'
CONNECT BY PRIOR employee_id = manager_id;

--SYS_CONNECT_BY_PATH
--Returns the path of a column value from root to node, with column values separated by char for each
row returned by CONNECT BY condition
--SYS_CONNECT_BY_PATH(<column>, <char>)
--conn scott/tiger

col empname format a20


col cbp format a30

SELECT LPAD(' ', 2*LEVEL, ' ' ) || ename empName, dname, job,
sys_connect_by_path( ename, '/' ) cbp
FROM emp e, dept d
WHERE e.deptno = d.deptno
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr
ORDER SIBLINGS BY job;

SELECT LPAD(' ', 2*LEVEL, ' ' ) || ename empName, dname, job,
sys_connect_by_path(empno, '.') cbp
FROM scott.emp emp, scott.dept dept
WHERE emp.deptno = dept.deptno
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr
ORDER SIBLINGS BY ename;

--Function Demo
--Use A Function To Receive The Current Node and Search for Parents of the Current Node
CREATE OR REPLACE FUNCTION permissions_sub_tree_root (
the_id IN NUMBER,
the_level IN NUMBER)
RETURN NUMBER IS

sub_tree_root NUMBER(10);

BEGIN
SELECT id
INTO sub_tree_root
FROM hierarchy
WHERE level = the_level
-- Connect 'upwards', i.e. find the parent
CONNECT BY PRIOR PARENT = id
START WITH ID = the_id;

RETURN sub_tree_root;
- 20 -
Introduction to 9i SQL Handbook
END permissions_sub_tree_root;
/

SELECT id, name, username


FROM (
SELECT ID, PARENT, NAME,
permissions_sub_tree_root(id, LEVEL) ROOT
FROM hierarchy
CONNECT BY PRIOR id = PARENT) HIERARCHY, permissions
WHERE ROOT = hierarchy_id;

--GROUP BY Demo
--Group By Demo with CONNECT_BY_ROOT and CONNECT_BY_PRIOR conn hr/hr
SELECT name, SUM(salary) "Total_Salary"
FROM (
SELECT CONNECT_BY_ROOT last_name name, salary
FROM employees
WHERE department_id = 110
CONNECT BY PRIOR employee_id = manager_id)
GROUP BY name;

--Demos
--Indenting conn hr/hr

col lname format a30

SELECT LPAD(' ', level*2, ' ') || last_name LNAME, d.department_id


FROM employees e, departments d
WHERE e.department_id = d.department_id
START WITH employee_id = 100
CONNECT BY PRIOR e.employee_id = e.manager_id;

--Hierarchical Query with IN In a [NOT] IN condition in a WHERE clause, if the right-hand side of the
condition is a subquery, you cannot use LEVEL on the left-hand side of the condition. However, you can
specify LEVEL in a subquery of the FROM clause to achieve the same result. For example, the following
statement is not valid:

SELECT employee_id, last_name FROM employees


WHERE (employee_id, LEVEL)
IN (SELECT employee_id, 2 FROM employees)
START WITH employee_id = 2
CONNECT BY PRIOR employee_id = manager_id;
--But the following statement is valid because it encapsulates the query containing the LEVEL
information in the FROM clause:

SELECT v.employee_id, v.last_name, v.lev


FROM (
SELECT employee_id, last_name, LEVEL lev
FROM employees v
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id) v
WHERE (v.employee_id, v.lev) IN (

SELECT employee_id, 2 FROM employees);

- 21 -

You might also like