Oracle9i Introduction To 9i SQL Handbook
Oracle9i Introduction To 9i SQL Handbook
-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(+);
-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
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
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, RREFERENTIAL INTEGRITY, UUNIQUE 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
- 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]
- 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 [email protected];
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
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
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?
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);
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
TOP N Analysis
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
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 ename,sal, rownum from (select ename,sal from emp order by sal desc) where rownum<=&n; --4
--connect by prior
----------------------------
--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
--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
set pagesize 0
col last_name format a30
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
--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
--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
--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
--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
--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
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;
/
--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
--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:
- 21 -