displaying data from multiple tables (join ) sub queries creating sequences creating views
DESCRIPTION
CH3 Part2. Displaying Data from Multiple Tables (Join ) Sub queries Creating Sequences Creating Views Dynamic SQL Queries Controlling User Access. Displaying Data from Multiple Tables (Join). Objectives. After completing this lesson, you should be able to do the following: - PowerPoint PPT PresentationTRANSCRIPT
Displaying Data from Multiple Tables (Join))
Sub queries Creating Sequences Creating Views Dynamic SQL Queries Controlling User Access
Displaying Data from Multiple Tables (Join))
Sub queries Creating Sequences Creating Views Dynamic SQL Queries Controlling User Access
CH3 Part2CH3 Part2CH3 Part2CH3 Part2
Displaying Data from Multiple Tables
(Join)
Displaying Data from Multiple Tables
(Join)
ObjectivesObjectivesObjectivesObjectives
After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Write SELECT statements to Write SELECT statements to
access data from more than one access data from more than one table using equality and table using equality and nonequality joinsnonequality joins
View data that generally does not View data that generally does not meet a join condition by using meet a join condition by using outer joinsouter joins
Join a table to itselfJoin a table to itself
After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Write SELECT statements to Write SELECT statements to
access data from more than one access data from more than one table using equality and table using equality and nonequality joinsnonequality joins
View data that generally does not View data that generally does not meet a join condition by using meet a join condition by using outer joinsouter joins
Join a table to itselfJoin a table to itself
EMPNO DEPTNO LOC----- ------- -------- 7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO...14 rows selected.
EMPNO DEPTNO LOC----- ------- -------- 7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO...14 rows selected.
Obtaining Data from Obtaining Data from Multiple TablesMultiple Tables
Obtaining Data from Obtaining Data from Multiple TablesMultiple Tables
EMP EMP DEPT DEPT EMPNO ENAME ... DEPTNO------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10
DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON
What Is a Join?What Is a Join?What Is a Join?What Is a Join?
Use a join to query data from Use a join to query data from more than one table.more than one table.
Write the join condition in the Write the join condition in the WHERE clause.WHERE clause.
Prefix the column name with the Prefix the column name with the table name when the same column table name when the same column name appears in more than one name appears in more than one table.table.
Use a join to query data from Use a join to query data from more than one table.more than one table.
Write the join condition in the Write the join condition in the WHERE clause.WHERE clause.
Prefix the column name with the Prefix the column name with the table name when the same column table name when the same column name appears in more than one name appears in more than one table.table.
SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;
SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;
Cartesian ProductCartesian ProductCartesian ProductCartesian Product
A Cartesian product is formed A Cartesian product is formed when:when: A join condition is omittedA join condition is omitted A join condition is invalidA join condition is invalid All rows in the first table are joined to All rows in the first table are joined to
all rows in the second tableall rows in the second table To avoid a Cartesian product, To avoid a Cartesian product,
always include a valid join always include a valid join condition in a WHERE clause.condition in a WHERE clause.
A Cartesian product is formed A Cartesian product is formed when:when: A join condition is omittedA join condition is omitted A join condition is invalidA join condition is invalid All rows in the first table are joined to All rows in the first table are joined to
all rows in the second tableall rows in the second table To avoid a Cartesian product, To avoid a Cartesian product,
always include a valid join always include a valid join condition in a WHERE clause.condition in a WHERE clause.
Generating a Cartesian Generating a Cartesian ProductProduct
Generating a Cartesian Generating a Cartesian ProductProduct
ENAME DNAME------ ----------KING ACCOUNTINGBLAKE ACCOUNTING ...KING RESEARCHBLAKE RESEARCH...56 rows selected.
ENAME DNAME------ ----------KING ACCOUNTINGBLAKE ACCOUNTING ...KING RESEARCHBLAKE RESEARCH...56 rows selected.
EMP (14 rows) EMP (14 rows) DEPT (4 rows) DEPT (4 rows)
EMPNO ENAME ... DEPTNO------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10
EMPNO ENAME ... DEPTNO------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10
DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON
DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON
““CartesianCartesianproduct: product:
14*4=56 rows”14*4=56 rows”
Types of JoinsTypes of JoinsTypes of JoinsTypes of Joins
EquijoinEquijoin Non-equijoinNon-equijoin Outer joinOuter join Self joinSelf join
What Is an Equijoin?What Is an Equijoin?What Is an Equijoin?What Is an Equijoin?EMP EMP DEPT DEPT EMPNO ENAME DEPTNO------ ------- ------- 7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20...14 rows selected.
DEPTNO DNAME LOC ------- ---------- -------- 10 ACCOUNTING NEW YORK 30 SALES CHICAGO 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 20 RESEARCH DALLAS 20 RESEARCH DALLAS...14 rows selected.
Foreign keyForeign key Primary keyPrimary key
Retrieving Records Retrieving Records with Equijoinswith Equijoins
Retrieving Records Retrieving Records with Equijoinswith Equijoins
SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno=dept.deptno;
EMPNO ENAME DEPTNO DEPTNO LOC----- ------ ------ ------ --------- 7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS...14 rows selected.
Qualifying Ambiguous Qualifying Ambiguous Column NamesColumn Names
Qualifying Ambiguous Qualifying Ambiguous Column NamesColumn Names
Use table prefixes to qualify Use table prefixes to qualify column names that are in multiple column names that are in multiple tables.tables.
Improve performance by using Improve performance by using table prefixes.table prefixes.
Distinguish columns that have Distinguish columns that have identical names but reside in identical names but reside in different tables by using column different tables by using column aliases.aliases.
Use table prefixes to qualify Use table prefixes to qualify column names that are in multiple column names that are in multiple tables.tables.
Improve performance by using Improve performance by using table prefixes.table prefixes.
Distinguish columns that have Distinguish columns that have identical names but reside in identical names but reside in different tables by using column different tables by using column aliases.aliases.
Additional Search Additional Search ConditionsConditions
Using the AND Operator Using the AND Operator
Additional Search Additional Search ConditionsConditions
Using the AND Operator Using the AND Operator EMP EMP DEPT DEPT EMPNO ENAME DEPTNO------ ------- ------- 7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20...14 rows selected.
DEPTNO DNAME LOC ------ --------- -------- 10 ACCOUNTING NEW YORK 30 SALES CHICAGO 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 20 RESEARCH DALLAS 20 RESEARCH DALLAS...14 rows selected.
Using Table AliasesUsing Table AliasesUsing Table AliasesUsing Table Aliases Simplify queries by using table Simplify queries by using table
aliases.aliases.
Simplify queries by using table Simplify queries by using table aliases.aliases.SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 WHERE emp.deptno=dept.deptno;
SQL> SELECT e.empno, e.ename, e.deptno,
2 d.deptno, d.loc
3 FROM emp e, dept d
4 WHERE e.deptno= d.deptno;
Joining More Than Two Joining More Than Two TablesTables
Joining More Than Two Joining More Than Two TablesTables
NAME CUSTID----------- ------JOCKSPORTS 100TKB SPORT SHOP 101VOLLYRITE 102JUST TENNIS 103K+T SPORTS 105SHAPE UP 106WOMENS SPORTS 107... ...9 rows selected.
NAME CUSTID----------- ------JOCKSPORTS 100TKB SPORT SHOP 101VOLLYRITE 102JUST TENNIS 103K+T SPORTS 105SHAPE UP 106WOMENS SPORTS 107... ...9 rows selected.
CUSTOMER CUSTOMER
CUSTID ORDID------- ------- 101 610 102 611 104 612 106 601 102 602 106 604 106 605... 21 rows selected.
CUSTID ORDID------- ------- 101 610 102 611 104 612 106 601 102 602 106 604 106 605... 21 rows selected.
ORD ORD
ORDID ITEMID------ ------- 610 3 611 1 612 1 601 1 602 1...64 rows selected.
ORDID ITEMID------ ------- 610 3 611 1 612 1 601 1 602 1...64 rows selected.
ITEM ITEM
Non-EquijoinsNon-EquijoinsNon-EquijoinsNon-EquijoinsEMPEMP SALGRADESALGRADE
““salary in the EMP salary in the EMP table is between table is between low salary and high low salary and high salary in the SALGRADEsalary in the SALGRADEtable”table”
EMPNO ENAME SAL------ ------- ------ 7839 KING 5000 7698 BLAKE 2850 7782 CLARK 2450 7566 JONES 2975 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950...14 rows selected.
GRADE LOSAL HISAL----- ----- ------1 700 12002 1201 14003 1401 20004 2001 30005 3001 9999
Retrieving Records Retrieving Records with Non-Equijoinswith Non-EquijoinsRetrieving Records Retrieving Records with Non-Equijoinswith Non-Equijoins
ENAME SAL GRADE---------- --------- ---------JAMES 950 1SMITH 800 1ADAMS 1100 1...14 rows selected.
SQL> SELECT e.ename, e.sal, s.grade
2 FROM emp e, salgrade s
3 WHERE e.sal
4 BETWEEN s.losal AND s.hisal;
Outer JoinsOuter JoinsOuter JoinsOuter JoinsEMP EMP DEPT DEPT
No employee in theNo employee in theOPERATIONS departmentOPERATIONS department
ENAME DEPTNO----- ------KING 10BLAKE 30CLARK 10JONES 20...
DEPTNO DNAME------ ----------10 ACCOUNTING30 SALES10 ACCOUNTING20 RESEARCH...40 OPERATIONS
Outer JoinsOuter JoinsOuter JoinsOuter Joins You use an outer join to also see You use an outer join to also see
rows that do not usually meet the rows that do not usually meet the join condition.join condition.
Outer join operator is the plus sign Outer join operator is the plus sign (+)(+)..
You use an outer join to also see You use an outer join to also see rows that do not usually meet the rows that do not usually meet the join condition.join condition.
Outer join operator is the plus sign Outer join operator is the plus sign (+)(+)..SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column(+) = table2.column;
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column(+) = table2.column;
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column = table2.column(+);
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column = table2.column(+);
Using Outer JoinsUsing Outer JoinsUsing Outer JoinsUsing Outer Joins
SQL> SELECT e.ename, d.deptno, d.dname
2 FROM emp e, dept d
3 WHERE e.deptno(+) = d.deptno
4 ORDER BY e.deptno;
ENAME DEPTNO DNAME---------- --------- -------------KING 10 ACCOUNTINGCLARK 10 ACCOUNTING... 40 OPERATIONS15 rows selected.
Self JoinsSelf JoinsSelf JoinsSelf Joins
EMP (WORKER)EMP (WORKER) EMP (MANAGER)EMP (MANAGER)
““MGR in the WORKER table is equal to EMPNO in the MGR in the WORKER table is equal to EMPNO in the MANAGER table”MANAGER table”
EMPNO ENAME MGR----- ------ ---- 7839 KING 7698 BLAKE 7839 7782 CLARK 7839 7566 JONES 7839 7654 MARTIN 7698 7499 ALLEN 7698
EMPNO ENAME----- --------
7839 KING 7839 KING 7839 KING 7698 BLAKE 7698 BLAKE
Joining a Table to ItselfJoining a Table to ItselfJoining a Table to ItselfJoining a Table to Itself
WORKER.ENAME||'WORKSFOR'||MANAG-------------------------------BLAKE works for KINGCLARK works for KINGJONES works for KINGMARTIN works for BLAKE...13 rows selected.
WORKER.ENAME||'WORKSFOR'||MANAG-------------------------------BLAKE works for KINGCLARK works for KINGJONES works for KINGMARTIN works for BLAKE...13 rows selected.
SQL> SELECT worker.ename||' works for '||manager.ename
2 FROM emp worker, emp manager
3 WHERE worker.mgr = manager.empno;
SummarySummarySummarySummary
EquijoinEquijoin Non-equijoinNon-equijoin Outer joinOuter join Self joinSelf join
SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;
SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;
Sub queriesSub queries
ObjectivesObjectivesObjectivesObjectives
After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Describe the types of problems Describe the types of problems
that subqueries can solvethat subqueries can solve Define subqueriesDefine subqueries List the types of subqueriesList the types of subqueries Write single-row and multiple-row Write single-row and multiple-row
subqueriessubqueries
After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Describe the types of problems Describe the types of problems
that subqueries can solvethat subqueries can solve Define subqueriesDefine subqueries List the types of subqueriesList the types of subqueries Write single-row and multiple-row Write single-row and multiple-row
subqueriessubqueries
Using a Subquery Using a Subquery to Solve a Problemto Solve a ProblemUsing a Subquery Using a Subquery to Solve a Problemto Solve a Problem ““Who has a salary greater than Who has a salary greater than
Jones’?”Jones’?”
““Who has a salary greater than Who has a salary greater than Jones’?”Jones’?”
“Which employees have a salary greater than Jones’ salary?”
Main Query
??
“What is Jones’ salary?”??
Subquery
SubqueriesSubqueriesSubqueriesSubqueries
The subquery (inner query) executes once before the main query.The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer The result of the subquery is used by the main query (outer
query).query).
The subquery (inner query) executes once before the main query.The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer The result of the subquery is used by the main query (outer
query).query).
SELECT select_listFROM tableWHERE expr operator
(SELECT select_list FROM table);
2975
SQL> SELECT ename 2 FROM emp 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno=7566);
Using a SubqueryUsing a SubqueryUsing a SubqueryUsing a Subquery
ENAME----------KINGFORDSCOTT
ENAME----------KINGFORDSCOTT
Guidelines for Using Guidelines for Using SubqueriesSubqueries
Guidelines for Using Guidelines for Using SubqueriesSubqueries
Enclose subqueries in parentheses. Enclose subqueries in parentheses. Place subqueries on the right side Place subqueries on the right side
of the comparison operator.of the comparison operator. Do not add an ORDER BY clause to Do not add an ORDER BY clause to
a subquery.a subquery. Use single-row operators with Use single-row operators with
single-row subqueries.single-row subqueries. Use multiple-row operators with Use multiple-row operators with
multiple-row subqueries.multiple-row subqueries.
Enclose subqueries in parentheses. Enclose subqueries in parentheses. Place subqueries on the right side Place subqueries on the right side
of the comparison operator.of the comparison operator. Do not add an ORDER BY clause to Do not add an ORDER BY clause to
a subquery.a subquery. Use single-row operators with Use single-row operators with
single-row subqueries.single-row subqueries. Use multiple-row operators with Use multiple-row operators with
multiple-row subqueries.multiple-row subqueries.
Types of SubqueriesTypes of SubqueriesTypes of SubqueriesTypes of Subqueries Single-row subquerySingle-row subquery Single-row subquerySingle-row subquery
Main query
Subquery returnsreturns
CLERKCLERK
• Multiple-row subquery• Multiple-row subquery
CLERKCLERKMANAGERMANAGER
Main query
Subquery returnsreturns
• Multiple-column subquery• Multiple-column subquery
CLERK 7900CLERK 7900MANAGER 7698MANAGER 7698
Main query
Subquery returnsreturns
Single-Row SubqueriesSingle-Row SubqueriesSingle-Row SubqueriesSingle-Row Subqueries Return only one rowReturn only one row Use single-row comparison Use single-row comparison
operatorsoperators
Return only one rowReturn only one row Use single-row comparison Use single-row comparison
operatorsoperatorsOperator
=
>
>=
<
<=
<>
Meaning
Equal to
Greater than
Greater than or equal to
Less than
Less than or equal to
Not equal to
Executing Single-Row Executing Single-Row SubqueriesSubqueries
Executing Single-Row Executing Single-Row SubqueriesSubqueries
CLERK
1100
ENAME JOB---------- ---------MILLER CLERK
ENAME JOB---------- ---------MILLER CLERK
SQL> SELECT ename, job 2 FROM emp 3 WHERE job = 4 (SELECT job 5 FROM emp 6 WHERE empno = 7369) 7 AND sal > 8 (SELECT sal 9 FROM emp 10 WHERE empno = 7876);
Using Group Functions Using Group Functions in a Subqueryin a Subquery
Using Group Functions Using Group Functions in a Subqueryin a Subquery
800
ENAME JOB SAL---------- --------- ---------SMITH CLERK 800
ENAME JOB SAL---------- --------- ---------SMITH CLERK 800
SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp);
HAVING Clause with HAVING Clause with SubqueriesSubqueries
HAVING Clause with HAVING Clause with SubqueriesSubqueries
The Oracle Server executes The Oracle Server executes subqueries first.subqueries first.
The Oracle Server returns results The Oracle Server returns results into the HAVING clause of the into the HAVING clause of the main query.main query.
The Oracle Server executes The Oracle Server executes subqueries first.subqueries first.
The Oracle Server returns results The Oracle Server returns results into the HAVING clause of the into the HAVING clause of the main query.main query.
800
SQL> SELECT deptno, MIN(sal) 2 FROM emp 3 GROUP BY deptno 4 HAVING MIN(sal) > 5 (SELECT MIN(sal) 6 FROM emp 7 WHERE deptno = 20);
What Is Wrong What Is Wrong with This Statement?with This Statement?
What Is Wrong What Is Wrong with This Statement?with This Statement?
ERROR:ORA-01427: single-row subquery returns more thanone row
no rows selected
ERROR:ORA-01427: single-row subquery returns more thanone row
no rows selected
SQL> SELECT empno, ename 2 FROM emp 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp 6 GROUP BY deptno);
Single-row operator with
Single-row operator with
multiple-row subquery
multiple-row subquery
Will This Statement Will This Statement Work?Work?
Will This Statement Will This Statement Work?Work?
no rows selectedno rows selected
Subquery returns no values
Subquery returns no values
SQL> SELECT ename, job 2 FROM emp 3 WHERE job = 4 (SELECT job 5 FROM emp 6 WHERE ename='SMYTHE');
Multiple-Row SubqueriesMultiple-Row SubqueriesMultiple-Row SubqueriesMultiple-Row Subqueries Return more than one rowReturn more than one row Use multiple-row comparison Use multiple-row comparison
operatorsoperators
Return more than one rowReturn more than one row Use multiple-row comparison Use multiple-row comparison
operatorsoperatorsOperator
IN
ANY
ALL
Meaning
Equal to any member in the list
Compare value to each value returned by
the subquery
Compare value to every value returned by
the subquery
Using ANY Operator Using ANY Operator in Multiple-Row in Multiple-Row
SubqueriesSubqueries
Using ANY Operator Using ANY Operator in Multiple-Row in Multiple-Row
SubqueriesSubqueries9508001100
1300
EMPNO ENAME JOB--------- ---------- --------- 7654 MARTIN SALESMAN 7521 WARD SALESMAN
EMPNO ENAME JOB--------- ---------- --------- 7654 MARTIN SALESMAN 7521 WARD SALESMAN
SQL> SELECT empno, ename, job 2 FROM emp 3 WHERE sal < ANY 4 (SELECT sal 5 FROM emp 6 WHERE job = 'CLERK') 7 AND job <> 'CLERK';
Using ALL Operator Using ALL Operator in Multiple-Row in Multiple-Row
SubqueriesSubqueries
Using ALL Operator Using ALL Operator in Multiple-Row in Multiple-Row
SubqueriesSubqueries2916.6667
2175
1566.6667
EMPNO ENAME JOB--------- ---------- --------- 7839 KING PRESIDENT 7566 JONES MANAGER 7902 FORD ANALYST 7788 SCOTT ANALYST
EMPNO ENAME JOB--------- ---------- --------- 7839 KING PRESIDENT 7566 JONES MANAGER 7902 FORD ANALYST 7788 SCOTT ANALYST
SQL> SELECT empno, ename, job 2 FROM emp 3 WHERE sal > ALL 4 (SELECT avg(sal) 5 FROM emp 6 GROUP BY deptno);
SummarySummarySummarySummary
Subqueries are useful when a Subqueries are useful when a query is based on unknown query is based on unknown values.values.
Subqueries are useful when a Subqueries are useful when a query is based on unknown query is based on unknown values.values.SELECT select_list
FROM tableWHERE expr operator
(SELECT select_list FROM table);
Creating SequencesCreating Sequences
What Is a Sequence?What Is a Sequence?What Is a Sequence?What Is a Sequence?
Automatically generates unique Automatically generates unique numbersnumbers
Is a sharable objectIs a sharable object Is typically used to create a primary Is typically used to create a primary
key valuekey value Replaces application codeReplaces application code Speeds up the efficiency of accessing Speeds up the efficiency of accessing
sequence values when cached in sequence values when cached in memorymemory
Automatically generates unique Automatically generates unique numbersnumbers
Is a sharable objectIs a sharable object Is typically used to create a primary Is typically used to create a primary
key valuekey value Replaces application codeReplaces application code Speeds up the efficiency of accessing Speeds up the efficiency of accessing
sequence values when cached in sequence values when cached in memorymemory
The CREATE SEQUENCE The CREATE SEQUENCE StatementStatement
The CREATE SEQUENCE The CREATE SEQUENCE StatementStatement
Define a sequence to generate Define a sequence to generate sequential numbers automatically.sequential numbers automatically.
Define a sequence to generate Define a sequence to generate sequential numbers automatically.sequential numbers automatically.
CREATE SEQUENCE sequence[INCREMENT BY n][START WITH n][{MAXVALUE n | NOMAXVALUE}][{MINVALUE n | NOMINVALUE}][{CYCLE | NOCYCLE}][{CACHE n | NOCACHE}];
CREATE SEQUENCE sequence[INCREMENT BY n][START WITH n][{MAXVALUE n | NOMAXVALUE}][{MINVALUE n | NOMINVALUE}][{CYCLE | NOCYCLE}][{CACHE n | NOCACHE}];
Creating a SequenceCreating a SequenceCreating a SequenceCreating a Sequence Create a sequence named DEPT_DEPTNO to be used for the primary Create a sequence named DEPT_DEPTNO to be used for the primary
key of thekey of theDEPT table.DEPT table.
Do not use the CYCLE option.Do not use the CYCLE option.
Create a sequence named DEPT_DEPTNO to be used for the primary Create a sequence named DEPT_DEPTNO to be used for the primary key of thekey of theDEPT table.DEPT table.
Do not use the CYCLE option.Do not use the CYCLE option.
SQL> CREATE SEQUENCE dept_deptno 2 INCREMENT BY 1 3 START WITH 91 4 MAXVALUE 100 5 NOCACHE 6 NOCYCLE;Sequence created.Sequence created.
SQL> CREATE SEQUENCE dept_deptno 2 INCREMENT BY 1 3 START WITH 91 4 MAXVALUE 100 5 NOCACHE 6 NOCYCLE;Sequence created.Sequence created.
Confirming SequencesConfirming SequencesConfirming SequencesConfirming Sequences
Verify your sequence values in the Verify your sequence values in the USER_SEQUENCES data USER_SEQUENCES data dictionary table.dictionary table.
The LAST_NUMBER column The LAST_NUMBER column displays the next available displays the next available sequence number.sequence number.
Verify your sequence values in the Verify your sequence values in the USER_SEQUENCES data USER_SEQUENCES data dictionary table.dictionary table.
The LAST_NUMBER column The LAST_NUMBER column displays the next available displays the next available sequence number.sequence number.
SQL> SELECT sequence_name, min_value, max_value, 2 increment_by, last_number 3 FROM user_sequences;
SQL> SELECT sequence_name, min_value, max_value, 2 increment_by, last_number 3 FROM user_sequences;
NEXTVAL and CURRVAL NEXTVAL and CURRVAL PseudocolumnsPseudocolumns
NEXTVAL and CURRVAL NEXTVAL and CURRVAL PseudocolumnsPseudocolumns
NEXTVAL returns the next NEXTVAL returns the next available sequence value.available sequence value.
It returns a unique value every It returns a unique value every time it is referenced, even for time it is referenced, even for different users.different users.
CURRVAL obtains the current CURRVAL obtains the current sequence value.sequence value.
NEXTVAL must be issued for that NEXTVAL must be issued for that sequence before CURRVAL sequence before CURRVAL contains a value.contains a value.
NEXTVAL returns the next NEXTVAL returns the next available sequence value.available sequence value.
It returns a unique value every It returns a unique value every time it is referenced, even for time it is referenced, even for different users.different users.
CURRVAL obtains the current CURRVAL obtains the current sequence value.sequence value.
NEXTVAL must be issued for that NEXTVAL must be issued for that sequence before CURRVAL sequence before CURRVAL contains a value.contains a value.
Using a SequenceUsing a SequenceUsing a SequenceUsing a Sequence Insert a new department named Insert a new department named
“MARKETING” in San Diego.“MARKETING” in San Diego.
View the current value for the View the current value for the DEPT_DEPTNO sequence.DEPT_DEPTNO sequence.
Insert a new department named Insert a new department named “MARKETING” in San Diego.“MARKETING” in San Diego.
View the current value for the View the current value for the DEPT_DEPTNO sequence.DEPT_DEPTNO sequence.
SQL> INSERT INTO dept(deptno, dname, loc) 2 VALUES (dept_deptno.NEXTVAL, 3 'MARKETING', 'SAN DIEGO');1 row created.1 row created.
SQL> INSERT INTO dept(deptno, dname, loc) 2 VALUES (dept_deptno.NEXTVAL, 3 'MARKETING', 'SAN DIEGO');1 row created.1 row created.
SQL> SELECT dept_deptno.CURRVAL 2 FROM dual;
SQL> SELECT dept_deptno.CURRVAL 2 FROM dual;
Using a SequenceUsing a SequenceUsing a SequenceUsing a Sequence
Caching sequence values in memory Caching sequence values in memory allows faster access to those values.allows faster access to those values.
Gaps in sequence values can occur Gaps in sequence values can occur when:when: A rollback occursA rollback occurs The system crashesThe system crashes A sequence is used in another tableA sequence is used in another table
View the next available sequence, if it View the next available sequence, if it was created with NOCACHE, by was created with NOCACHE, by querying the USER_SEQUENCES querying the USER_SEQUENCES table.table.
Caching sequence values in memory Caching sequence values in memory allows faster access to those values.allows faster access to those values.
Gaps in sequence values can occur Gaps in sequence values can occur when:when: A rollback occursA rollback occurs The system crashesThe system crashes A sequence is used in another tableA sequence is used in another table
View the next available sequence, if it View the next available sequence, if it was created with NOCACHE, by was created with NOCACHE, by querying the USER_SEQUENCES querying the USER_SEQUENCES table.table.
Modifying a SequenceModifying a SequenceModifying a SequenceModifying a Sequence
Change the increment value, Change the increment value, maximum value, minimum value, maximum value, minimum value, cycle option, or cache option.cycle option, or cache option.
Change the increment value, Change the increment value, maximum value, minimum value, maximum value, minimum value, cycle option, or cache option.cycle option, or cache option.
SQL> ALTER SEQUENCE dept_deptno 2 INCREMENT BY 1 3 MAXVALUE 999999 4 NOCACHE 5 NOCYCLE;Sequence altered.Sequence altered.
SQL> ALTER SEQUENCE dept_deptno 2 INCREMENT BY 1 3 MAXVALUE 999999 4 NOCACHE 5 NOCYCLE;Sequence altered.Sequence altered.
Guidelines for Modifying Guidelines for Modifying a Sequencea Sequence
Guidelines for Modifying Guidelines for Modifying a Sequencea Sequence
You must be the owner or have the You must be the owner or have the ALTER privilege for the sequence.ALTER privilege for the sequence.
Only future sequence numbers are Only future sequence numbers are affected.affected.
The sequence must be dropped and The sequence must be dropped and
re-created to restart the sequence re-created to restart the sequence at a different number.at a different number.
You must be the owner or have the You must be the owner or have the ALTER privilege for the sequence.ALTER privilege for the sequence.
Only future sequence numbers are Only future sequence numbers are affected.affected.
The sequence must be dropped and The sequence must be dropped and
re-created to restart the sequence re-created to restart the sequence at a different number.at a different number.
Removing a SequenceRemoving a SequenceRemoving a SequenceRemoving a Sequence
Remove a sequence from the data Remove a sequence from the data dictionary by using the DROP dictionary by using the DROP SEQUENCE statement.SEQUENCE statement.
Once removed, the sequence can Once removed, the sequence can no longer be referenced.no longer be referenced.
Remove a sequence from the data Remove a sequence from the data dictionary by using the DROP dictionary by using the DROP SEQUENCE statement.SEQUENCE statement.
Once removed, the sequence can Once removed, the sequence can no longer be referenced.no longer be referenced.
SQL> DROP SEQUENCE dept_deptno;Sequence dropped.Sequence dropped.
SQL> DROP SEQUENCE dept_deptno;Sequence dropped.Sequence dropped.
Creating ViewsCreating Views
What Is a View?What Is a View?What Is a View?What Is a View?
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ------- --------- ----- --------- ----- ----- -------
7839 KING PRESIDENT 17-NOV-81 5000 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ------- --------- ----- --------- ----- ----- -------
7839 KING PRESIDENT 17-NOV-81 5000 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
EMP TableEMP TableEMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- -------- --------- ---- --------- ------ ----- -------
7839 KING PRESIDENT 17-NOV-81 5000 10
7782 CLARK MANAGER 7839 09-JUN-81 1500 300 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- -------- --------- ---- --------- ------ ----- -------
7839 KING PRESIDENT 17-NOV-81 5000 10
7782 CLARK MANAGER 7839 09-JUN-81 1500 300 10
7934 MILLER CLERK 7782 23-JAN-82 1300 10
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
EMPNO ENAME JOB ------ -------- ----------- 7839 KING PRESIDENT 7782 CLARK MANAGER 7934 MILLER CLERK
EMPVU10 ViewEMPVU10 View
Why Use Views?Why Use Views?Why Use Views?Why Use Views?
To restrict data accessTo restrict data access To make complex queries easyTo make complex queries easy To allow data independenceTo allow data independence To present different views of the To present different views of the
same datasame data
To restrict data accessTo restrict data access To make complex queries easyTo make complex queries easy To allow data independenceTo allow data independence To present different views of the To present different views of the
same datasame data
Simple Views Simple Views and Complex Viewsand Complex Views
Simple Views Simple Views and Complex Viewsand Complex Views
Feature Simple ViewsComplex Views
Number of tables One One or more
Contain functions No Yes
Contain groups of data No Yes
DML through view Yes Not always
Creating a ViewCreating a ViewCreating a ViewCreating a View You embed a subquery within the CREATE VIEW statement.You embed a subquery within the CREATE VIEW statement.
The subquery can contain complex SELECT syntax.The subquery can contain complex SELECT syntax. The subquery cannot contain an ORDER BY clause.The subquery cannot contain an ORDER BY clause.
You embed a subquery within the CREATE VIEW statement.You embed a subquery within the CREATE VIEW statement.
The subquery can contain complex SELECT syntax.The subquery can contain complex SELECT syntax. The subquery cannot contain an ORDER BY clause.The subquery cannot contain an ORDER BY clause.
CREATE [OR REPLACE] VIEW view_nameAS subquery;
CREATE [OR REPLACE] VIEW view_nameAS subquery;
Creating a ViewCreating a ViewCreating a ViewCreating a View Create a view, EMPVU10, that contains Create a view, EMPVU10, that contains
details of employees in department 10.details of employees in department 10.
Create a view, EMPVU10, that contains Create a view, EMPVU10, that contains details of employees in department 10.details of employees in department 10.
• Describe the structure of the view by using the SQL*Plus DESCRIBE command.
• Describe the structure of the view by using the SQL*Plus DESCRIBE command.
SQL> DESCRIBE empvu10SQL> DESCRIBE empvu10
SQL> CREATE VIEW empvu10 2 AS SELECT empno, ename, job 3 FROM emp 4 WHERE deptno = 10;View created.View created.
Creating a ViewCreating a ViewCreating a ViewCreating a View Create a view by using column Create a view by using column
aliases in the subquery.aliases in the subquery.
Select the columns from this view Select the columns from this view by the given alias names.by the given alias names.
Create a view by using column Create a view by using column aliases in the subquery.aliases in the subquery.
Select the columns from this view Select the columns from this view by the given alias names.by the given alias names.
SQL> CREATE VIEW salvu30 2 AS SELECT empno EMPLOYEE_NUMBER, ename NAME, 3 sal SALARY 4 FROM emp 5 WHERE deptno = 30;View created.View created.
Retrieving Data from a Retrieving Data from a ViewView
Retrieving Data from a Retrieving Data from a ViewView
EMPLOYEE_NUMBER NAME SALARY--------------- ---------- --------- 7698 BLAKE 2850 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 7521 WARD 1250
6 rows selected.
EMPLOYEE_NUMBER NAME SALARY--------------- ---------- --------- 7698 BLAKE 2850 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 7521 WARD 1250
6 rows selected.
SQL> SELECT * 2 FROM salvu30;
Querying a ViewQuerying a ViewQuerying a ViewQuerying a View
USER_VIEWSUSER_VIEWS EMPVU10EMPVU10SELECT empno, ename, jobFROM empWHERE deptno = 10;
USER_VIEWSUSER_VIEWS EMPVU10EMPVU10SELECT empno, ename, jobFROM empWHERE deptno = 10;
SQL*PlusSQL*Plus
SELECT *FROM empvu10;
EMP
7839 KING PRESIDENT7782 CLARK MANAGER7934 MILLER CLERK
Modifying a ViewModifying a ViewModifying a ViewModifying a View Modify the EMPVU10 view by using Modify the EMPVU10 view by using
CREATE OR REPLACE VIEW CREATE OR REPLACE VIEW clause. Add an alias for each column clause. Add an alias for each column name.name.
Column aliases in the CREATE Column aliases in the CREATE VIEW clause are listed in the same VIEW clause are listed in the same order as the columns in the order as the columns in the subquery.subquery.
Modify the EMPVU10 view by using Modify the EMPVU10 view by using CREATE OR REPLACE VIEW CREATE OR REPLACE VIEW clause. Add an alias for each column clause. Add an alias for each column name.name.
Column aliases in the CREATE Column aliases in the CREATE VIEW clause are listed in the same VIEW clause are listed in the same order as the columns in the order as the columns in the subquery.subquery.
SQL> CREATE OR REPLACE VIEW empvu10 2 (employee_number, employee_name, job_title) 3 AS SELECT empno, ename, job 4 FROM emp 5 WHERE deptno = 10;View created.View created.
Removing a ViewRemoving a ViewRemoving a ViewRemoving a View
Remove a view without losing data Remove a view without losing data because a view is based on because a view is based on underlying tables in the database.underlying tables in the database.
Remove a view without losing data Remove a view without losing data because a view is based on because a view is based on underlying tables in the database.underlying tables in the database.
SQL> DROP VIEW empvu10; View dropped.View dropped.
DROP VIEW view; DROP VIEW view;
Dynamic SQL QueriesDynamic SQL Queries
ObjectivesObjectivesObjectivesObjectives
After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Produce queries that require an Produce queries that require an
input variableinput variable Produce more readable outputProduce more readable output
After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Produce queries that require an Produce queries that require an
input variableinput variable Produce more readable outputProduce more readable output
Interactive ReportsInteractive ReportsInteractive ReportsInteractive Reports
I want to input query values at runtime....sal = ? …
… deptno = ? … .. ename = ? ...
UserUser
Substitution VariablesSubstitution VariablesSubstitution VariablesSubstitution Variables
Use SQL*Plus substitution Use SQL*Plus substitution variables to temporarily store variables to temporarily store values.values. Single ampersand (&)Single ampersand (&) Double ampersand (&&)Double ampersand (&&) DEFINE and ACCEPT commandsDEFINE and ACCEPT commands
Pass variable values between SQL Pass variable values between SQL statements.statements.
Use SQL*Plus substitution Use SQL*Plus substitution variables to temporarily store variables to temporarily store values.values. Single ampersand (&)Single ampersand (&) Double ampersand (&&)Double ampersand (&&) DEFINE and ACCEPT commandsDEFINE and ACCEPT commands
Pass variable values between SQL Pass variable values between SQL statements.statements.
Using the & Substitution Using the & Substitution VariableVariable
Using the & Substitution Using the & Substitution VariableVariable Use a variable prefixed with an Use a variable prefixed with an
ampersand (&) to prompt the ampersand (&) to prompt the user for a value.user for a value.
Use a variable prefixed with an Use a variable prefixed with an ampersand (&) to prompt the ampersand (&) to prompt the user for a value.user for a value.SQL> SELECT empno, ename, sal, deptno
2 FROM emp 3 WHERE empno = &employee_num;
Enter value for employee_num: 73697369
EMPNO ENAME SAL DEPTNO--------- ---------- --------- --------- 7369 SMITH 800 20
Using the SET VERIFY Using the SET VERIFY CommandCommand
Using the SET VERIFY Using the SET VERIFY CommandCommand Toggling the display of the text of Toggling the display of the text of
a command before and after a command before and after SQL*Plus replaces substitution SQL*Plus replaces substitution variables with values.variables with values.
Toggling the display of the text of Toggling the display of the text of a command before and after a command before and after SQL*Plus replaces substitution SQL*Plus replaces substitution variables with values.variables with values.SQL> SET VERIFY ON
SQL> SELECT empno, ename, sal, deptno 2 FROM emp 3 WHERE empno = &employee_num;
Enter value for employee_num: 7369old 3: WHERE empno = &employee_numnew 3: WHERE empno = 7369
...
Character and Date Character and Date Values Values
with Substitution with Substitution VariablesVariables
Character and Date Character and Date Values Values
with Substitution with Substitution VariablesVariables
Use single quotation marks for date Use single quotation marks for date and character values.and character values.
Use single quotation marks for date Use single quotation marks for date and character values.and character values.SQL> SELECT ename, deptno, sal*12 2 FROM emp 3 WHERE job='&job_title';
Enter value for job_title: ANALYSTANALYST
ENAME DEPTNO SAL*12---------- --------- ---------SCOTT 20 36000FORD 20 36000
Specifying Column Specifying Column Names, Expressions, and Names, Expressions, and
Text at RuntimeText at Runtime
Specifying Column Specifying Column Names, Expressions, and Names, Expressions, and
Text at RuntimeText at Runtime Use substitution variables to Use substitution variables to supplement the following:supplement the following: WHERE conditionWHERE condition ORDER BY clauseORDER BY clause Column expressionColumn expression Table nameTable name Entire SELECT statementEntire SELECT statement
Use substitution variables to Use substitution variables to supplement the following:supplement the following: WHERE conditionWHERE condition ORDER BY clauseORDER BY clause Column expressionColumn expression Table nameTable name Entire SELECT statementEntire SELECT statement
Specifying Column Specifying Column Names, Expressions, Names, Expressions, and Text at Runtimeand Text at Runtime
Specifying Column Specifying Column Names, Expressions, Names, Expressions, and Text at Runtimeand Text at RuntimeSQL> SELECT empno, ename, job, &column_name
2 FROM emp 3 WHERE &condition 4 ORDER BY &order_column;
Enter value for column_name: salsalEnter value for condition: sal>=3000sal>=3000Enter value for order_column: enameename
EMPNO ENAME JOB SAL--------- ---------- --------- --------- 7902 FORD ANALYST 3000 7839 KING PRESIDENT 5000 7788 SCOTT ANALYST 3000
Using the && Using the && Substitution VariableSubstitution Variable
Using the && Using the && Substitution VariableSubstitution Variable Use the double-ampersand (&&) Use the double-ampersand (&&) if you want to reuse the variable if you want to reuse the variable value without prompting the value without prompting the user each time.user each time.
Use the double-ampersand (&&) Use the double-ampersand (&&) if you want to reuse the variable if you want to reuse the variable value without prompting the value without prompting the user each time.user each time.SQL> SELECT empno, ename, job, &&column_name
2 FROM emp 3 ORDER BY &column_name;
Enter value for column_name: deptnodeptno EMPNO ENAME JOB DEPTNO--------- ---------- --------- --------- 7839 KING PRESIDENT 10 7782 CLARK MANAGER 10 7934 MILLER CLERK 10...14 rows selected.
Defining User VariablesDefining User VariablesDefining User VariablesDefining User Variables
You can predefine variables using You can predefine variables using one of two SQL*Plus commands:one of two SQL*Plus commands: DEFINE: Create a CHAR datatype DEFINE: Create a CHAR datatype
user variableuser variable ACCEPT: Read user input and store it ACCEPT: Read user input and store it
in a variablein a variable If you need to predefine a variable If you need to predefine a variable
that includes spaces, you must that includes spaces, you must enclose the value within single enclose the value within single quotation marks when using the quotation marks when using the DEFINE command.DEFINE command.
You can predefine variables using You can predefine variables using one of two SQL*Plus commands:one of two SQL*Plus commands: DEFINE: Create a CHAR datatype DEFINE: Create a CHAR datatype
user variableuser variable ACCEPT: Read user input and store it ACCEPT: Read user input and store it
in a variablein a variable If you need to predefine a variable If you need to predefine a variable
that includes spaces, you must that includes spaces, you must enclose the value within single enclose the value within single quotation marks when using the quotation marks when using the DEFINE command.DEFINE command.
The ACCEPT CommandThe ACCEPT CommandThe ACCEPT CommandThe ACCEPT Command
Creates a customized prompt when Creates a customized prompt when accepting user inputaccepting user input
Explicitly defines a NUMBER or Explicitly defines a NUMBER or DATE datatype variableDATE datatype variable
Hides user input for security Hides user input for security reasonsreasons
Creates a customized prompt when Creates a customized prompt when accepting user inputaccepting user input
Explicitly defines a NUMBER or Explicitly defines a NUMBER or DATE datatype variableDATE datatype variable
Hides user input for security Hides user input for security reasonsreasons
ACCEPT variable [datatype] [FORMAT format] [PROMPT text] [HIDE]
ACCEPT variable [datatype] [FORMAT format] [PROMPT text] [HIDE]
Using the ACCEPT Using the ACCEPT CommandCommand
Using the ACCEPT Using the ACCEPT CommandCommand
ACCEPT dept PROMPT 'Provide the department name: 'SELECT * FROM deptWHERE dname = UPPER('&dept')/
Provide the department name: SalesSales
DEPTNO DNAME LOC--------- -------------- ------------- 30 SALES CHICAGO
DEFINE and UNDEFINE DEFINE and UNDEFINE CommandsCommands
DEFINE and UNDEFINE DEFINE and UNDEFINE CommandsCommands A variable remains defined until you A variable remains defined until you
either:either: Use the UNDEFINE command to clear itUse the UNDEFINE command to clear it Exit SQL*PlusExit SQL*Plus
You can verify your changes with the You can verify your changes with the DEFINE command.DEFINE command.
To define variables for every session, To define variables for every session, modify your modify your login.sqllogin.sql file so that the file so that the variables are created at startup.variables are created at startup.
A variable remains defined until you A variable remains defined until you either:either: Use the UNDEFINE command to clear itUse the UNDEFINE command to clear it Exit SQL*PlusExit SQL*Plus
You can verify your changes with the You can verify your changes with the DEFINE command.DEFINE command.
To define variables for every session, To define variables for every session, modify your modify your login.sqllogin.sql file so that the file so that the variables are created at startup.variables are created at startup.
Using the DEFINE Using the DEFINE CommandCommand
Using the DEFINE Using the DEFINE CommandCommand
Create a variable to hold the Create a variable to hold the department name.department name.
Create a variable to hold the Create a variable to hold the department name.department name.
DEFINE DEPTNAME = "sales" (CHAR) DEFINE DEPTNAME = "sales" (CHAR)
• Use the variable as you would any other variable.• Use the variable as you would any other
variable.
SQL> DEFINE deptname = salesSQL> DEFINE deptname
SQL> SELECT * 2 FROM dept 3 WHERE dname = UPPER('&deptname');
Controlling User AccessControlling User Access
ObjectivesObjectivesObjectivesObjectives
After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Create usersCreate users Create roles to ease setup and Create roles to ease setup and
maintenance of the security modelmaintenance of the security model Use the GRANT and REVOKE Use the GRANT and REVOKE
statements to grant and revoke statements to grant and revoke object privilegesobject privileges
After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Create usersCreate users Create roles to ease setup and Create roles to ease setup and
maintenance of the security modelmaintenance of the security model Use the GRANT and REVOKE Use the GRANT and REVOKE
statements to grant and revoke statements to grant and revoke object privilegesobject privileges
Controlling User AccessControlling User AccessControlling User AccessControlling User Access
DatabaseDatabaseadministratoradministrator
UsersUsers
Username and passwordprivileges
PrivilegesPrivilegesPrivilegesPrivileges Database security:Database security:
System securitySystem security Data securityData security
System privileges: Gain access to System privileges: Gain access to the databasethe database
Object privileges: Manipulate the Object privileges: Manipulate the content of the database objectscontent of the database objects
Schema: Collection of objects, such Schema: Collection of objects, such as tables, views, and sequencesas tables, views, and sequences
Database security:Database security: System securitySystem security Data securityData security
System privileges: Gain access to System privileges: Gain access to the databasethe database
Object privileges: Manipulate the Object privileges: Manipulate the content of the database objectscontent of the database objects
Schema: Collection of objects, such Schema: Collection of objects, such as tables, views, and sequencesas tables, views, and sequences
System PrivilegesSystem PrivilegesSystem PrivilegesSystem Privileges
More than 80 privileges are More than 80 privileges are available.available.
The DBA has high-level system The DBA has high-level system privileges:privileges: Create new usersCreate new users Remove usersRemove users Remove tablesRemove tables Back up tablesBack up tables
More than 80 privileges are More than 80 privileges are available.available.
The DBA has high-level system The DBA has high-level system privileges:privileges: Create new usersCreate new users Remove usersRemove users Remove tablesRemove tables Back up tablesBack up tables
Creating UsersCreating UsersCreating UsersCreating Users
The DBA creates users by using the The DBA creates users by using the CREATE USER statement.CREATE USER statement.
The DBA creates users by using the The DBA creates users by using the CREATE USER statement.CREATE USER statement.
SQL> CREATE USER scott 2 IDENTIFIED BY tiger;User created.User created.
SQL> CREATE USER scott 2 IDENTIFIED BY tiger;User created.User created.
CREATE USER user IDENTIFIED BY password;
User System User System PrivilegesPrivileges
User System User System PrivilegesPrivileges
GRANT privilege [, privilege...]TO user [, user...];
GRANT privilege [, privilege...]TO user [, user...];
• An application developer may have the following system privileges:– CREATE SESSION– CREATE TABLE– CREATE SEQUENCE– CREATE VIEW– CREATE PROCEDURE
• An application developer may have the following system privileges:– CREATE SESSION– CREATE TABLE– CREATE SEQUENCE– CREATE VIEW– CREATE PROCEDURE
• Once a user is created, the DBA can grant specific system privileges to a user.• Once a user is created, the DBA can grant
specific system privileges to a user.
Granting System Granting System PrivilegesPrivileges
Granting System Granting System PrivilegesPrivileges
The DBA can grant a user specific system The DBA can grant a user specific system privileges.privileges.
The DBA can grant a user specific system The DBA can grant a user specific system privileges.privileges.
SQL> GRANT create table, create sequence, create view 2 TO scott;Grant succeeded.Grant succeeded.
SQL> GRANT create table, create sequence, create view 2 TO scott;Grant succeeded.Grant succeeded.
What Is a Role?What Is a Role?What Is a Role?What Is a Role?
Allocating privilegesAllocating privilegeswithout a rolewithout a role
Allocating privilegesAllocating privilegeswith a rolewith a role
PrivilegesPrivileges
UsersUsers
ManagerManager
Creating and Granting Creating and Granting Privileges to a RolePrivileges to a Role
Creating and Granting Creating and Granting Privileges to a RolePrivileges to a Role
SQL> CREATE ROLE manager;Role created.Role created.
SQL> CREATE ROLE manager;Role created.Role created.
SQL> GRANT create table, create view 2 to manager; Grant succeeded.Grant succeeded.
SQL> GRANT create table, create view 2 to manager; Grant succeeded.Grant succeeded.
SQL> GRANT manager to BLAKE, CLARK; Grant succeeded.Grant succeeded.
SQL> GRANT manager to BLAKE, CLARK; Grant succeeded.Grant succeeded.
Changing Your PasswordChanging Your PasswordChanging Your PasswordChanging Your Password
The DBA creates your user account and The DBA creates your user account and initializes your password.initializes your password.
You can change your password by using You can change your password by using the ALTER USER statement.the ALTER USER statement.
The DBA creates your user account and The DBA creates your user account and initializes your password.initializes your password.
You can change your password by using You can change your password by using the ALTER USER statement.the ALTER USER statement.
SQL> ALTER USER scott 2 IDENTIFIED BY lion;User altered.User altered.
Object Privilege Table View Sequence
Procedure
ALTER
DELETE *
EXECUTE
INDEX *
INSERT *
REFERENCES *
SELECT *
UPDATE *
Object PrivilegesObject PrivilegesObject PrivilegesObject Privileges
Object PrivilegesObject PrivilegesObject PrivilegesObject Privileges
Object privileges vary from object to Object privileges vary from object to object.object.
An owner has all the privileges on the An owner has all the privileges on the object.object.
An owner can give specific privileges on An owner can give specific privileges on that owner’s object.that owner’s object.
Object privileges vary from object to Object privileges vary from object to object.object.
An owner has all the privileges on the An owner has all the privileges on the object.object.
An owner can give specific privileges on An owner can give specific privileges on that owner’s object.that owner’s object.
GRANT object_priv [(columns)] ON object TO {user|role|PUBLIC} [WITH GRANT OPTION];
GRANT object_priv [(columns)] ON object TO {user|role|PUBLIC} [WITH GRANT OPTION];
Granting Object Granting Object PrivilegesPrivileges
Granting Object Granting Object PrivilegesPrivileges
SQL> GRANT select 2 ON emp 3 TO sue, rich;Grant succeeded.Grant succeeded.
SQL> GRANT select 2 ON emp 3 TO sue, rich;Grant succeeded.Grant succeeded.
SQL> GRANT update (dname, loc) 2 ON dept 3 TO scott, manager;Grant succeeded.Grant succeeded.
SQL> GRANT update (dname, loc) 2 ON dept 3 TO scott, manager;Grant succeeded.Grant succeeded.
Grant query privileges on the EMP table.Grant query privileges on the EMP table. Grant query privileges on the EMP table.Grant query privileges on the EMP table.
• Grant privileges to update specific columns to users and roles. • Grant privileges to update specific
columns to users and roles.
Using WITH GRANT Using WITH GRANT OPTION and PUBLIC OPTION and PUBLIC
KeywordsKeywords
Using WITH GRANT Using WITH GRANT OPTION and PUBLIC OPTION and PUBLIC
KeywordsKeywords
Allow all users on the system to Allow all users on the system to query data from Alice’s DEPT query data from Alice’s DEPT table.table.
Allow all users on the system to Allow all users on the system to query data from Alice’s DEPT query data from Alice’s DEPT table.table.
SQL> GRANT select, insert 2 ON dept 3 TO scott 4 WITH GRANT OPTION;Grant succeeded.Grant succeeded.
SQL> GRANT select, insert 2 ON dept 3 TO scott 4 WITH GRANT OPTION;Grant succeeded.Grant succeeded.
SQL> GRANT select 2 ON alice.dept 3 TO PUBLIC;Grant succeeded.Grant succeeded.
SQL> GRANT select 2 ON alice.dept 3 TO PUBLIC;Grant succeeded.Grant succeeded.
• Give a user authority to pass along the privileges.• Give a user authority to pass along the
privileges.
Confirming Privileges Confirming Privileges GrantedGranted
Confirming Privileges Confirming Privileges GrantedGrantedData Dictionary Table Description
ROLE_SYS_PRIVS System privileges granted to roles
ROLE_TAB_PRIVS Table privileges granted to roles
USER_ROLE_PRIVS Roles accessible by the user
USER_TAB_PRIVS_MADE Object privileges granted on the user’s objects
USER_TAB_PRIVS_RECD Object privileges granted to the user
USER_COL_PRIVS_MADE Object privileges granted on the columns of the user’s objects
USER_COL_PRIVS_RECD Object privileges granted to the user on specific columns
How to Revoke Object How to Revoke Object PrivilegesPrivileges
How to Revoke Object How to Revoke Object PrivilegesPrivileges
You use the REVOKE statement to You use the REVOKE statement to revoke privileges granted to other revoke privileges granted to other users.users.
Privileges granted to others Privileges granted to others through the WITH GRANT OPTION through the WITH GRANT OPTION will also be revoked.will also be revoked.
You use the REVOKE statement to You use the REVOKE statement to revoke privileges granted to other revoke privileges granted to other users.users.
Privileges granted to others Privileges granted to others through the WITH GRANT OPTION through the WITH GRANT OPTION will also be revoked.will also be revoked.
REVOKE {privilege [, privilege...]|ALL}ON objectFROM {user[, user...]|role|PUBLIC}[CASCADE CONSTRAINTS];
REVOKE {privilege [, privilege...]|ALL}ON objectFROM {user[, user...]|role|PUBLIC}[CASCADE CONSTRAINTS];
Revoking Object Revoking Object PrivilegesPrivileges
Revoking Object Revoking Object PrivilegesPrivileges
As user Alice, revoke the As user Alice, revoke the SELECT and INSERT privileges SELECT and INSERT privileges given to user Scott on the DEPT given to user Scott on the DEPT table.table.
As user Alice, revoke the As user Alice, revoke the SELECT and INSERT privileges SELECT and INSERT privileges given to user Scott on the DEPT given to user Scott on the DEPT table.table.SQL> REVOKE select, insert
2 ON dept 3 FROM scott;Revoke succeeded.Revoke succeeded.
SQL> REVOKE select, insert 2 ON dept 3 FROM scott;Revoke succeeded.Revoke succeeded.
SummarySummarySummarySummary Statement Action
CREATE USER Allows the DBA to create a user
GRANT Allows the user to give other users
privileges to access the user’sobjects
CREATE ROLE Allows the DBA to create a collection
of privileges
ALTER USER Allows users to change theirpassword
REVOKE Removes privileges on an object from
users
Practice OverviewPractice OverviewPractice OverviewPractice Overview
Granting other users privileges to your tableGranting other users privileges to your table Modifying another user’s table through the privileges granted to youModifying another user’s table through the privileges granted to you Creating a synonymCreating a synonym Querying the data dictionary views related to privilegesQuerying the data dictionary views related to privileges
Granting other users privileges to your tableGranting other users privileges to your table Modifying another user’s table through the privileges granted to youModifying another user’s table through the privileges granted to you Creating a synonymCreating a synonym Querying the data dictionary views related to privilegesQuerying the data dictionary views related to privileges