lesson10
TRANSCRIPT
10-1 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Oracle OCPOracle OCPOracle OCPOracle OCP 考试系列培训之
1Z0-007 Lesson101Z0-007 Lesson101Z0-007 Lesson101Z0-007 Lesson10wwwwwwwwwwww....OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux....cncncncn
10101010Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating Other Schema ObjectsCreating Other Schema ObjectsCreating Other Schema ObjectsCreating Other Schema Objects
10-3 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
ObjectivesObjectivesObjectivesObjectives
After completing this lesson, you should be able to do After completing this lesson, you should be able to do After completing this lesson, you should be able to do After completing this lesson, you should be able to do the following:the following:the following:the following:• Create simple and complex viewsCreate simple and complex viewsCreate simple and complex viewsCreate simple and complex views• Retrieve data from viewsRetrieve data from viewsRetrieve data from viewsRetrieve data from views• Create, maintain, and use sequencesCreate, maintain, and use sequencesCreate, maintain, and use sequencesCreate, maintain, and use sequences• Create and maintain indexesCreate and maintain indexesCreate and maintain indexesCreate and maintain indexes• Create private and public synonymsCreate private and public synonymsCreate private and public synonymsCreate private and public synonyms
10-4 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Database ObjectsDatabase ObjectsDatabase ObjectsDatabase Objects
Logically represents subsets of data from Logically represents subsets of data from Logically represents subsets of data from Logically represents subsets of data from one or more tablesone or more tablesone or more tablesone or more tables
View View View View
Generates numeric valuesGenerates numeric valuesGenerates numeric valuesGenerates numeric valuesSequence Sequence Sequence Sequence
Basic unit of storage; composed of rows Basic unit of storage; composed of rows Basic unit of storage; composed of rows Basic unit of storage; composed of rows TableTableTableTable
Gives alternative names to objectsGives alternative names to objectsGives alternative names to objectsGives alternative names to objectsSynonym Synonym Synonym Synonym
Improves the performance of some Improves the performance of some Improves the performance of some Improves the performance of some queriesqueriesqueriesqueries
IndexIndexIndexIndex
DescriptionDescriptionDescriptionDescriptionObjectObjectObjectObject
10-5 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
What Is a View?What Is a View?What Is a View?What Is a View?
EMPLOYEESEMPLOYEESEMPLOYEESEMPLOYEES table table table table
10-6 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Advantages of ViewsAdvantages of ViewsAdvantages of ViewsAdvantages of Views
To restrict To restrict To restrict To restrict data accessdata accessdata accessdata access
To make complex To make complex To make complex To make complex queries easyqueries easyqueries easyqueries easy
To provide To provide To provide To provide data data data data
independenceindependenceindependenceindependence
To present To present To present To present different views of different views of different views of different views of
the same datathe same datathe same datathe same data
10-7 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Simple Views and Complex ViewsSimple Views and Complex ViewsSimple Views and Complex ViewsSimple Views and Complex Views
YesYesYesYesNoNoNoNo
NoNoNoNo
OneOneOneOne
Simple ViewsSimple ViewsSimple ViewsSimple Views
YesYesYesYesContain functionsContain functionsContain functionsContain functions
YesYesYesYesContain groups of dataContain groups of dataContain groups of dataContain groups of data
One or moreOne or moreOne or moreOne or moreNumber of tablesNumber of tablesNumber of tablesNumber of tables
Not alwaysNot alwaysNot alwaysNot alwaysDML operations DML operations DML operations DML operations through a viewthrough a viewthrough a viewthrough a view
Complex ViewsComplex ViewsComplex ViewsComplex ViewsFeatureFeatureFeatureFeature
10-8 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating a ViewCreating a ViewCreating a ViewCreating a View
• You embed a subquery in the You embed a subquery in the You embed a subquery in the You embed a subquery in the CREATE VIEWCREATE VIEWCREATE VIEWCREATE VIEW statement:statement:statement:statement:
• The subquery can contain complex The subquery can contain complex The subquery can contain complex The subquery can contain complex SELECTSELECTSELECTSELECT syntax. syntax. syntax. syntax.
CREATE [OR REPLACE] [FORCE|CREATE [OR REPLACE] [FORCE|CREATE [OR REPLACE] [FORCE|CREATE [OR REPLACE] [FORCE|NOFORCENOFORCENOFORCENOFORCE] VIEW ] VIEW ] VIEW ] VIEW viewviewviewview [( [( [( [(aliasaliasaliasalias[, [, [, [, aliasaliasaliasalias]...)]]...)]]...)]]...)] AS AS AS AS subquerysubquerysubquerysubquery[WITH CHECK OPTION [CONSTRAINT [WITH CHECK OPTION [CONSTRAINT [WITH CHECK OPTION [CONSTRAINT [WITH CHECK OPTION [CONSTRAINT constraintconstraintconstraintconstraint]]]]]]]][WITH READ ONLY [CONSTRAINT [WITH READ ONLY [CONSTRAINT [WITH READ ONLY [CONSTRAINT [WITH READ ONLY [CONSTRAINT constraintconstraintconstraintconstraint]];]];]];]];
10-9 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating a ViewCreating a ViewCreating a ViewCreating a View
• Create the Create the Create the Create the EMPVU80EMPVU80EMPVU80EMPVU80 view, which contains details view, which contains details view, which contains details view, which contains details of employees in department 80:of employees in department 80:of employees in department 80:of employees in department 80:
• Describe the structure of the view by using the Describe the structure of the view by using the Describe the structure of the view by using the Describe the structure of the view by using the iiiiSQLSQLSQLSQL****Plus Plus Plus Plus DESCRIBEDESCRIBEDESCRIBEDESCRIBE command: command: command: command:
DESCRIBE empvu80DESCRIBE empvu80DESCRIBE empvu80DESCRIBE empvu80
CREATE VIEW CREATE VIEW CREATE VIEW CREATE VIEW empvu80empvu80empvu80empvu80 AS SELECT employee_id, last_name, salary AS SELECT employee_id, last_name, salary AS SELECT employee_id, last_name, salary AS SELECT employee_id, last_name, salary FROM employees FROM employees FROM employees FROM employees WHERE department_id = 80; WHERE department_id = 80; WHERE department_id = 80; WHERE department_id = 80;View created.View created.View created.View created.
10-10 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating a ViewCreating a ViewCreating a ViewCreating a View
• Create a view by using Create a view by using Create a view by using Create a view by using column aliasescolumn aliasescolumn aliasescolumn aliases in the in the in the in the subquery:subquery:subquery:subquery:
• Select the columns from this view by the given Select the columns from this view by the given Select the columns from this view by the given Select the columns from this view by the given alias names:alias names:alias names:alias names:
CREATE VIEW CREATE VIEW CREATE VIEW CREATE VIEW salvu50salvu50salvu50salvu50 AS SELECT employee_id ID_NUMBER, last_name NAME, AS SELECT employee_id ID_NUMBER, last_name NAME, AS SELECT employee_id ID_NUMBER, last_name NAME, AS SELECT employee_id ID_NUMBER, last_name NAME, salary salary salary salary****12 ANN_SALARY12 ANN_SALARY12 ANN_SALARY12 ANN_SALARY FROM employees FROM employees FROM employees FROM employees WHERE department_id = 50; WHERE department_id = 50; WHERE department_id = 50; WHERE department_id = 50;View created.View created.View created.View created.
10-11 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
SELECT SELECT SELECT SELECT ****FROM salvu50;FROM salvu50;FROM salvu50;FROM salvu50;
Retrieving Data from a ViewRetrieving Data from a ViewRetrieving Data from a ViewRetrieving Data from a View
P85 Q138P85 Q138P85 Q138P85 Q138
10-12 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Modifying a ViewModifying a ViewModifying a ViewModifying a View
• Modify the Modify the Modify the Modify the EMPVU80EMPVU80EMPVU80EMPVU80 view by using a view by using a view by using a view by using a CREATE OR CREATE OR CREATE OR CREATE OR REPLACE VIEWREPLACE VIEWREPLACE VIEWREPLACE VIEW clause. Add an alias for each clause. Add an alias for each clause. Add an alias for each clause. Add an alias for each column name:column name:column name:column name:
• Column aliases in the Column aliases in the Column aliases in the Column aliases in the CREATE OR REPLACE VIEWCREATE OR REPLACE VIEWCREATE OR REPLACE VIEWCREATE OR REPLACE VIEW clause are listed in the same order as the columns clause are listed in the same order as the columns clause are listed in the same order as the columns clause are listed in the same order as the columns in the subquery.in the subquery.in the subquery.in the subquery.
CREATE OR REPLACE VIEW empvu80CREATE OR REPLACE VIEW empvu80CREATE OR REPLACE VIEW empvu80CREATE OR REPLACE VIEW empvu80 (id_number, name, sal, department_id) (id_number, name, sal, department_id) (id_number, name, sal, department_id) (id_number, name, sal, department_id)AS SELECT employee_id, first_name || ' ' AS SELECT employee_id, first_name || ' ' AS SELECT employee_id, first_name || ' ' AS SELECT employee_id, first_name || ' ' || last_name, salary, department_id || last_name, salary, department_id || last_name, salary, department_id || last_name, salary, department_id FROM employees FROM employees FROM employees FROM employees WHERE department_id = 80; WHERE department_id = 80; WHERE department_id = 80; WHERE department_id = 80;View created.View created.View created.View created.
10-13 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating a Complex ViewCreating a Complex ViewCreating a Complex ViewCreating a Complex View
Create a complex view that contains group functions Create a complex view that contains group functions Create a complex view that contains group functions Create a complex view that contains group functions to display values from two tables:to display values from two tables:to display values from two tables:to display values from two tables:
CREATE OR REPLACE VIEW dept_sum_vuCREATE OR REPLACE VIEW dept_sum_vuCREATE OR REPLACE VIEW dept_sum_vuCREATE OR REPLACE VIEW dept_sum_vu (name, minsal, maxsal, avgsal) (name, minsal, maxsal, avgsal) (name, minsal, maxsal, avgsal) (name, minsal, maxsal, avgsal)AS SELECT d.department_name, MIN(e.salary), AS SELECT d.department_name, MIN(e.salary), AS SELECT d.department_name, MIN(e.salary), AS SELECT d.department_name, MIN(e.salary), MAX(e.salary),AVG(e.salary) MAX(e.salary),AVG(e.salary) MAX(e.salary),AVG(e.salary) MAX(e.salary),AVG(e.salary) FROM employees e JOIN departments d FROM employees e JOIN departments d FROM employees e JOIN departments d FROM employees e JOIN departments d ON (e.department_id = d.department_id) ON (e.department_id = d.department_id) ON (e.department_id = d.department_id) ON (e.department_id = d.department_id) GROUP BY d.department_name; GROUP BY d.department_name; GROUP BY d.department_name; GROUP BY d.department_name;View created.View created.View created.View created.
10-14 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Rules for Performing Rules for Performing Rules for Performing Rules for Performing DML Operations on a ViewDML Operations on a ViewDML Operations on a ViewDML Operations on a View
• You can usually perform DML operationsYou can usually perform DML operationsYou can usually perform DML operationsYou can usually perform DML operationson simple views. on simple views. on simple views. on simple views.
• You cannot You cannot You cannot You cannot removeremoveremoveremove a row if the view contains the a row if the view contains the a row if the view contains the a row if the view contains the following:following:following:following:– Group functionsGroup functionsGroup functionsGroup functions– A A A A GROUP BYGROUP BYGROUP BYGROUP BY clause clause clause clause– The The The The DISTINCTDISTINCTDISTINCTDISTINCT keyword keyword keyword keyword– The pseudocolumn The pseudocolumn The pseudocolumn The pseudocolumn ROWNUMROWNUMROWNUMROWNUM keyword keyword keyword keyword
10-15 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Rules for Performing Rules for Performing Rules for Performing Rules for Performing DML Operations on a ViewDML Operations on a ViewDML Operations on a ViewDML Operations on a View
You cannot You cannot You cannot You cannot modify modify modify modify data in a view if it contains:data in a view if it contains:data in a view if it contains:data in a view if it contains:• Group functionsGroup functionsGroup functionsGroup functions• A A A A GROUP BYGROUP BYGROUP BYGROUP BY clause clause clause clause• The The The The DISTINCTDISTINCTDISTINCTDISTINCT keyword keyword keyword keyword• The pseudocolumn The pseudocolumn The pseudocolumn The pseudocolumn ROWNUMROWNUMROWNUMROWNUM keyword keyword keyword keyword• Columns defined by expressionsColumns defined by expressionsColumns defined by expressionsColumns defined by expressions
10-16 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Rules for Performing Rules for Performing Rules for Performing Rules for Performing DML Operations on a ViewDML Operations on a ViewDML Operations on a ViewDML Operations on a View
You cannot You cannot You cannot You cannot addaddaddadd data through a view if the view data through a view if the view data through a view if the view data through a view if the view includes:includes:includes:includes:• Group functionsGroup functionsGroup functionsGroup functions• A A A A GROUP BYGROUP BYGROUP BYGROUP BY clause clause clause clause• The The The The DISTINCTDISTINCTDISTINCTDISTINCT keyword keyword keyword keyword• The pseudocolumn The pseudocolumn The pseudocolumn The pseudocolumn ROWNUMROWNUMROWNUMROWNUM keyword keyword keyword keyword• Columns defined by expressionsColumns defined by expressionsColumns defined by expressionsColumns defined by expressions• NOT NULLNOT NULLNOT NULLNOT NULL columns in the base tables that are not columns in the base tables that are not columns in the base tables that are not columns in the base tables that are not
selected by the viewselected by the viewselected by the viewselected by the view
10-17 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Using the Using the Using the Using the WITH CHECK OPTIONWITH CHECK OPTIONWITH CHECK OPTIONWITH CHECK OPTION Clause Clause Clause Clause
• You can ensure that DML operations performed on You can ensure that DML operations performed on You can ensure that DML operations performed on You can ensure that DML operations performed on the view stay in the domain of the view by using the view stay in the domain of the view by using the view stay in the domain of the view by using the view stay in the domain of the view by using the the the the WITH CHECK OPTIONWITH CHECK OPTIONWITH CHECK OPTIONWITH CHECK OPTION clause: clause: clause: clause:
• Any attempt to change the department number for Any attempt to change the department number for Any attempt to change the department number for Any attempt to change the department number for any row in the view fails because it violates the any row in the view fails because it violates the any row in the view fails because it violates the any row in the view fails because it violates the WITH CHECK OPTIONWITH CHECK OPTIONWITH CHECK OPTIONWITH CHECK OPTION constraint. constraint. constraint. constraint.
CREATE OR REPLACE VIEW empvu20CREATE OR REPLACE VIEW empvu20CREATE OR REPLACE VIEW empvu20CREATE OR REPLACE VIEW empvu20AS SELECTAS SELECTAS SELECTAS SELECT **** FROM employees FROM employees FROM employees FROM employees WHERE department_id = 20 WHERE department_id = 20 WHERE department_id = 20 WHERE department_id = 20 WITH CHECK OPTION CONSTRAINT empvu20_ck ; WITH CHECK OPTION CONSTRAINT empvu20_ck ; WITH CHECK OPTION CONSTRAINT empvu20_ck ; WITH CHECK OPTION CONSTRAINT empvu20_ck ;View created.View created.View created.View created.
P84 Q137P84 Q137P84 Q137P84 Q137
10-18 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Denying DML OperationsDenying DML OperationsDenying DML OperationsDenying DML Operations
• You can ensure that no DML operations occur by You can ensure that no DML operations occur by You can ensure that no DML operations occur by You can ensure that no DML operations occur by adding the adding the adding the adding the WITH READ ONLYWITH READ ONLYWITH READ ONLYWITH READ ONLY option to your view option to your view option to your view option to your view definition.definition.definition.definition.
• Any attempt to perform a DML operation on any Any attempt to perform a DML operation on any Any attempt to perform a DML operation on any Any attempt to perform a DML operation on any row in the view results in an Oracle server error.row in the view results in an Oracle server error.row in the view results in an Oracle server error.row in the view results in an Oracle server error.
10-19 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
CREATE OR REPLACE VIEW empvu10CREATE OR REPLACE VIEW empvu10CREATE OR REPLACE VIEW empvu10CREATE OR REPLACE VIEW empvu10 (employee_number, employee_name, job_title) (employee_number, employee_name, job_title) (employee_number, employee_name, job_title) (employee_number, employee_name, job_title)AS SELECTAS SELECTAS SELECTAS SELECT employee_id, last_name, job_idemployee_id, last_name, job_idemployee_id, last_name, job_idemployee_id, last_name, job_id FROM employees FROM employees FROM employees FROM employees WHERE department_id = 10 WHERE department_id = 10 WHERE department_id = 10 WHERE department_id = 10 WITH READ ONLY ; WITH READ ONLY ; WITH READ ONLY ; WITH READ ONLY ;View created.View created.View created.View created.
Denying DML OperationsDenying DML OperationsDenying DML OperationsDenying DML Operations
10-20 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Removing a ViewRemoving a ViewRemoving a ViewRemoving a View
You can remove a view without losing data because a You can remove a view without losing data because a You can remove a view without losing data because a You can remove a view without losing data because a view is based on underlying tables in the database.view is based on underlying tables in the database.view is based on underlying tables in the database.view is based on underlying tables in the database.
DROP VIEW DROP VIEW DROP VIEW DROP VIEW viewviewviewview;;;;
DROP VIEW empvu80;DROP VIEW empvu80;DROP VIEW empvu80;DROP VIEW empvu80;View dropped.View dropped.View dropped.View dropped.
10-21 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 10: Overview of Part 1Practice 10: Overview of Part 1Practice 10: Overview of Part 1Practice 10: Overview of Part 1
This practice covers the following topics:This practice covers the following topics:This practice covers the following topics:This practice covers the following topics:• Creating a simple viewCreating a simple viewCreating a simple viewCreating a simple view• Creating a complex viewCreating a complex viewCreating a complex viewCreating a complex view• Creating a view with a check constraintCreating a view with a check constraintCreating a view with a check constraintCreating a view with a check constraint• Attempting to modify data in the viewAttempting to modify data in the viewAttempting to modify data in the viewAttempting to modify data in the view• Removing viewsRemoving viewsRemoving viewsRemoving views
P69 Q109P69 Q109P69 Q109P69 Q109
10-22 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
SequencesSequencesSequencesSequences
Logically represents subsets of data from Logically represents subsets of data from Logically represents subsets of data from Logically represents subsets of data from one or more tablesone or more tablesone or more tablesone or more tables
View View View View
Generates numeric valuesGenerates numeric valuesGenerates numeric valuesGenerates numeric valuesSequence Sequence Sequence Sequence
Basic unit of storage; composed of rows Basic unit of storage; composed of rows Basic unit of storage; composed of rows Basic unit of storage; composed of rows TableTableTableTable
Gives alternative names to objectsGives alternative names to objectsGives alternative names to objectsGives alternative names to objectsSynonym Synonym Synonym Synonym
Improves the performance of some Improves the performance of some Improves the performance of some Improves the performance of some queriesqueriesqueriesqueries
IndexIndexIndexIndex
DescriptionDescriptionDescriptionDescriptionObjectObjectObjectObject
10-23 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
SequencesSequencesSequencesSequences
A sequence:A sequence:A sequence:A sequence:• Can automatically generate unique numbersCan automatically generate unique numbersCan automatically generate unique numbersCan automatically generate unique numbers• Is a sharable objectIs a sharable objectIs a sharable objectIs a sharable object• Can be used to create a primary key valueCan be used to create a primary key valueCan be used to create a primary key valueCan be used to create a primary key value• Replaces application codeReplaces application codeReplaces application codeReplaces application code• Speeds up the efficiency of accessing sequence Speeds up the efficiency of accessing sequence Speeds up the efficiency of accessing sequence Speeds up the efficiency of accessing sequence
values when cached in memoryvalues when cached in memoryvalues when cached in memoryvalues when cached in memory
1111
2222 4444
3333 5555
6666 8888
7777
10101010
9999
10-24 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
CREATECREATECREATECREATE SEQUENCESEQUENCESEQUENCESEQUENCE Statement: Statement: Statement: Statement:SyntaxSyntaxSyntaxSyntax
Define a sequence to generate sequential numbers Define a sequence to generate sequential numbers Define a sequence to generate sequential numbers Define a sequence to generate sequential numbers automatically:automatically:automatically:automatically:
CREATE SEQUENCE CREATE SEQUENCE CREATE SEQUENCE CREATE SEQUENCE sequencesequencesequencesequence [INCREMENT BY [INCREMENT BY [INCREMENT BY [INCREMENT BY nnnn]]]] [START WITH [START WITH [START WITH [START WITH nnnn]]]] [{MAXVALUE [{MAXVALUE [{MAXVALUE [{MAXVALUE nnnn | | | | NOMAXVALUENOMAXVALUENOMAXVALUENOMAXVALUE}]}]}]}] [{MINVALUE [{MINVALUE [{MINVALUE [{MINVALUE nnnn | | | | NOMINVALUENOMINVALUENOMINVALUENOMINVALUE}]}]}]}] [{CYCLE | [{CYCLE | [{CYCLE | [{CYCLE | NOCYCLENOCYCLENOCYCLENOCYCLE}]}]}]}] [{CACHE [{CACHE [{CACHE [{CACHE nnnn | NOCACHE}]; | NOCACHE}]; | NOCACHE}]; | NOCACHE}];
P87 Q145P87 Q145P87 Q145P87 Q145
10-25 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating a SequenceCreating a SequenceCreating a SequenceCreating a Sequence
• Create a sequence named Create a sequence named Create a sequence named Create a sequence named DEPT_DEPTID_SEQDEPT_DEPTID_SEQDEPT_DEPTID_SEQDEPT_DEPTID_SEQ to to to to be used for the primary key of the be used for the primary key of the be used for the primary key of the be used for the primary key of the DEPARTMENTSDEPARTMENTSDEPARTMENTSDEPARTMENTS table.table.table.table.
• Do not use the Do not use the Do not use the Do not use the CYCLECYCLECYCLECYCLE option. option. option. option.
CREATE SEQUENCE dept_deptid_seqCREATE SEQUENCE dept_deptid_seqCREATE SEQUENCE dept_deptid_seqCREATE SEQUENCE dept_deptid_seq INCREMENT BY 10 INCREMENT BY 10 INCREMENT BY 10 INCREMENT BY 10 START WITH 120 START WITH 120 START WITH 120 START WITH 120 MAXVALUE 9999 MAXVALUE 9999 MAXVALUE 9999 MAXVALUE 9999 NOCACHE NOCACHE NOCACHE NOCACHE NOCYCLE; NOCYCLE; NOCYCLE; NOCYCLE;Sequence created.Sequence created.Sequence created.Sequence created.
10-26 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
NEXTVALNEXTVALNEXTVALNEXTVAL and and and and CURRVALCURRVALCURRVALCURRVAL Pseudocolumns Pseudocolumns Pseudocolumns Pseudocolumns
• NEXTVALNEXTVALNEXTVALNEXTVAL returns the next available sequence returns the next available sequence returns the next available sequence returns the next available sequence value. It returns a unique value every time it is value. It returns a unique value every time it is value. It returns a unique value every time it is value. It returns a unique value every time it is referenced, even for different users. referenced, even for different users. referenced, even for different users. referenced, even for different users.
• CURRVALCURRVALCURRVALCURRVAL obtains the current sequence value. obtains the current sequence value. obtains the current sequence value. obtains the current sequence value. • NEXTVALNEXTVALNEXTVALNEXTVAL must be issued for that sequence before must be issued for that sequence before must be issued for that sequence before must be issued for that sequence before
CURRVALCURRVALCURRVALCURRVAL contains a value. contains a value. contains a value. contains a value.
10-27 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
10-28 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Using a SequenceUsing a SequenceUsing a SequenceUsing a Sequence
• Insert a new department named Insert a new department named Insert a new department named Insert a new department named ““““SupportSupportSupportSupport”””” in in in in location ID 2500:location ID 2500:location ID 2500:location ID 2500:
• View the current value for the View the current value for the View the current value for the View the current value for the DEPT_DEPTID_SEQDEPT_DEPTID_SEQDEPT_DEPTID_SEQDEPT_DEPTID_SEQ sequence:sequence:sequence:sequence:
INSERT INTO departments(department_id, INSERT INTO departments(department_id, INSERT INTO departments(department_id, INSERT INTO departments(department_id, department_name, location_id) department_name, location_id) department_name, location_id) department_name, location_id)VALUES (dept_deptid_seq.NEXTVAL, VALUES (dept_deptid_seq.NEXTVAL, VALUES (dept_deptid_seq.NEXTVAL, VALUES (dept_deptid_seq.NEXTVAL, 'Support', 2500); 'Support', 2500); 'Support', 2500); 'Support', 2500);1 row created.1 row created.1 row created.1 row created.
SELECTSELECTSELECTSELECT dept_deptid_seq.CURRVALdept_deptid_seq.CURRVALdept_deptid_seq.CURRVALdept_deptid_seq.CURRVALFROMFROMFROMFROM dual;dual;dual;dual;
10-29 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Caching Sequence ValuesCaching Sequence ValuesCaching Sequence ValuesCaching Sequence Values
• Caching sequence values in memory gives faster Caching sequence values in memory gives faster Caching sequence values in memory gives faster Caching sequence values in memory gives faster access to those values.access to those values.access to those values.access to those values.
• Gaps in sequence values can occur when:Gaps in sequence values can occur when:Gaps in sequence values can occur when:Gaps in sequence values can occur when:– A rollback occursA rollback occursA rollback occursA rollback occurs– The system crashesThe system crashesThe system crashesThe system crashes– A sequence is used in another tableA sequence is used in another tableA sequence is used in another tableA sequence is used in another table
10-30 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Modifying a SequenceModifying a SequenceModifying a SequenceModifying a Sequence
Change the increment value, maximum value, Change the increment value, maximum value, Change the increment value, maximum value, Change the increment value, maximum value, minimum value, cycle option, or cache option:minimum value, cycle option, or cache option:minimum value, cycle option, or cache option:minimum value, cycle option, or cache option:
ALTER SEQUENCE dept_deptid_seqALTER SEQUENCE dept_deptid_seqALTER SEQUENCE dept_deptid_seqALTER SEQUENCE dept_deptid_seq INCREMENT BY 20 INCREMENT BY 20 INCREMENT BY 20 INCREMENT BY 20 MAXVALUE 999999 MAXVALUE 999999 MAXVALUE 999999 MAXVALUE 999999 NOCACHE NOCACHE NOCACHE NOCACHE NOCYCLE; NOCYCLE; NOCYCLE; NOCYCLE;Sequence altered.Sequence altered.Sequence altered.Sequence altered.
10-31 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Guidelines for Modifying Guidelines for Modifying Guidelines for Modifying Guidelines for Modifying a Sequencea Sequencea Sequencea Sequence
• You must be the owner or have the You must be the owner or have the You must be the owner or have the You must be the owner or have the ALTERALTERALTERALTER privilege for the sequence.privilege for the sequence.privilege for the sequence.privilege for the sequence.
• Only future sequence numbers are affected.Only future sequence numbers are affected.Only future sequence numbers are affected.Only future sequence numbers are affected.• The sequence must be dropped and The sequence must be dropped and The sequence must be dropped and The sequence must be dropped and
re-created to restart the sequence at a different re-created to restart the sequence at a different re-created to restart the sequence at a different re-created to restart the sequence at a different number.number.number.number.
• Some validation is performed.Some validation is performed.Some validation is performed.Some validation is performed.• To remove a sequence, use the To remove a sequence, use the To remove a sequence, use the To remove a sequence, use the DROPDROPDROPDROP statement: statement: statement: statement:
DROP SEQUENCE dept_deptid_seq;DROP SEQUENCE dept_deptid_seq;DROP SEQUENCE dept_deptid_seq;DROP SEQUENCE dept_deptid_seq;Sequence dropped.Sequence dropped.Sequence dropped.Sequence dropped.
10-32 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
IndexesIndexesIndexesIndexes
Logically represents subsets of data from Logically represents subsets of data from Logically represents subsets of data from Logically represents subsets of data from one or more tablesone or more tablesone or more tablesone or more tables
View View View View
Generates numeric valuesGenerates numeric valuesGenerates numeric valuesGenerates numeric valuesSequence Sequence Sequence Sequence
Basic unit of storage; composed of rows Basic unit of storage; composed of rows Basic unit of storage; composed of rows Basic unit of storage; composed of rows TableTableTableTable
Gives alternative names to objectsGives alternative names to objectsGives alternative names to objectsGives alternative names to objectsSynonym Synonym Synonym Synonym
Improves the performance of some Improves the performance of some Improves the performance of some Improves the performance of some queriesqueriesqueriesqueries
IndexIndexIndexIndex
DescriptionDescriptionDescriptionDescriptionObjectObjectObjectObject
10-33 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
IndexesIndexesIndexesIndexes
An index:An index:An index:An index:• Is a schema objectIs a schema objectIs a schema objectIs a schema object• Can be used by the Oracle server to speed up the Can be used by the Oracle server to speed up the Can be used by the Oracle server to speed up the Can be used by the Oracle server to speed up the
retrieval of rows by using a pointerretrieval of rows by using a pointerretrieval of rows by using a pointerretrieval of rows by using a pointer• Can reduce disk I/O by using a rapid path access Can reduce disk I/O by using a rapid path access Can reduce disk I/O by using a rapid path access Can reduce disk I/O by using a rapid path access
method to locate data quicklymethod to locate data quicklymethod to locate data quicklymethod to locate data quickly• Is independent of the table that it indexesIs independent of the table that it indexesIs independent of the table that it indexesIs independent of the table that it indexes• Is used and maintained automatically by the Is used and maintained automatically by the Is used and maintained automatically by the Is used and maintained automatically by the
Oracle serverOracle serverOracle serverOracle server
10-34 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
How Are Indexes Created?How Are Indexes Created?How Are Indexes Created?How Are Indexes Created?
• Automatically: A unique index is created Automatically: A unique index is created Automatically: A unique index is created Automatically: A unique index is created automatically when you define a automatically when you define a automatically when you define a automatically when you define a PRIMARY KEYPRIMARY KEYPRIMARY KEYPRIMARY KEY or or or or UNIQUEUNIQUEUNIQUEUNIQUE constraint in a table definition. constraint in a table definition. constraint in a table definition. constraint in a table definition.
• Manually: Users can create nonunique indexes on Manually: Users can create nonunique indexes on Manually: Users can create nonunique indexes on Manually: Users can create nonunique indexes on columns to speed up access to the rows.columns to speed up access to the rows.columns to speed up access to the rows.columns to speed up access to the rows.
10-35 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating an IndexCreating an IndexCreating an IndexCreating an Index
• Create an index on one or more columns:Create an index on one or more columns:Create an index on one or more columns:Create an index on one or more columns:
• Improve the speed of query access to the Improve the speed of query access to the Improve the speed of query access to the Improve the speed of query access to the LAST_NAMELAST_NAMELAST_NAMELAST_NAME column in the column in the column in the column in the EMPLOYEESEMPLOYEESEMPLOYEESEMPLOYEES table: table: table: table:
CREATE INDEX CREATE INDEX CREATE INDEX CREATE INDEX emp_last_name_idxemp_last_name_idxemp_last_name_idxemp_last_name_idxON ON ON ON employees(last_name);employees(last_name);employees(last_name);employees(last_name);Index created.Index created.Index created.Index created.
CREATE INDEX CREATE INDEX CREATE INDEX CREATE INDEX indexindexindexindexON ON ON ON tabletabletabletable ( ( ( (columncolumncolumncolumn[, [, [, [, columncolumncolumncolumn]...);]...);]...);]...);
10-36 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Index Creation GuidelinesIndex Creation GuidelinesIndex Creation GuidelinesIndex Creation Guidelines
Do not create an index when:Do not create an index when:Do not create an index when:Do not create an index when:The columns are not often used as a condition in the queryThe columns are not often used as a condition in the queryThe columns are not often used as a condition in the queryThe columns are not often used as a condition in the query
The table is small or most queries are expected to retrieve more The table is small or most queries are expected to retrieve more The table is small or most queries are expected to retrieve more The table is small or most queries are expected to retrieve more than 2% to 4% of the rows in the tablethan 2% to 4% of the rows in the tablethan 2% to 4% of the rows in the tablethan 2% to 4% of the rows in the tableThe table is updated frequentlyThe table is updated frequentlyThe table is updated frequentlyThe table is updated frequently
A column contains a large number of null valuesA column contains a large number of null valuesA column contains a large number of null valuesA column contains a large number of null valuesOne or more columns are frequently used together in a One or more columns are frequently used together in a One or more columns are frequently used together in a One or more columns are frequently used together in a WHERE WHERE WHERE WHERE clause or a join conditionclause or a join conditionclause or a join conditionclause or a join condition
A column contains a wide range of valuesA column contains a wide range of valuesA column contains a wide range of valuesA column contains a wide range of values
The indexed columns are referenced as part of an expressionThe indexed columns are referenced as part of an expressionThe indexed columns are referenced as part of an expressionThe indexed columns are referenced as part of an expression
The table is large and most queries are expected to retrieve less The table is large and most queries are expected to retrieve less The table is large and most queries are expected to retrieve less The table is large and most queries are expected to retrieve less than 2%than 2%than 2%than 2% to to to to 4% of the rows in the table4% of the rows in the table4% of the rows in the table4% of the rows in the table
Create an index when:Create an index when:Create an index when:Create an index when:
10-37 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
什么时候创建索引
如果出现下列情况,,,,考虑创建索引::::• 包含了大量不同值的列
• 包含了大量空值的列
• 一个或者多个列经常被一起出现在 WHEREWHEREWHEREWHERE条件中或者
作为连接的条件出现
• 表的数据量很大,,,,而且对表的查询经常是得到表中数据的2%2%2%2%到4%4%4%4%。
P92 Q154P92 Q154P92 Q154P92 Q154
10-38 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
什么时候不要创建索引
如果出现下列情况,,,,不需要创建索引::::• 一个很小的表• 列很少被用于查询的条件中出现• 表上的大多数查询是得到表中大于4%4%4%4%的数据• 表中的数据经常发生变动• 要被索引的列被作为条件表达式的一部分或出现在函
数中((((索引无效))))
10-39 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
SELECTSELECTSELECTSELECT ic.index_name, ic.column_name,ic.index_name, ic.column_name,ic.index_name, ic.column_name,ic.index_name, ic.column_name,ic.column_position col_pos,ix.uniquenessic.column_position col_pos,ix.uniquenessic.column_position col_pos,ix.uniquenessic.column_position col_pos,ix.uniqueness
FROMFROMFROMFROM user_indexes ix, user_ind_columns icuser_indexes ix, user_ind_columns icuser_indexes ix, user_ind_columns icuser_indexes ix, user_ind_columns icWHEREWHEREWHEREWHERE ic.index_name = ix.index_nameic.index_name = ix.index_nameic.index_name = ix.index_nameic.index_name = ix.index_nameANDANDANDAND ic.table_name = 'EMPLOYEES';ic.table_name = 'EMPLOYEES';ic.table_name = 'EMPLOYEES';ic.table_name = 'EMPLOYEES';
查询索引信息
• 通过USER_INDEXESUSER_INDEXESUSER_INDEXESUSER_INDEXES 数据字典可以得到索引的定义和
唯一性....• 通过USER_IND_COLUMNSUSER_IND_COLUMNSUSER_IND_COLUMNSUSER_IND_COLUMNS 数据字典可以得到索引的
名称,,,,表名和列名....
10-40 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Removing an IndexRemoving an IndexRemoving an IndexRemoving an Index
• Remove an index from the data dictionary by Remove an index from the data dictionary by Remove an index from the data dictionary by Remove an index from the data dictionary by using the using the using the using the DROP INDEXDROP INDEXDROP INDEXDROP INDEX command: command: command: command:
• Remove the Remove the Remove the Remove the UPPER_LAST_NAME_IDXUPPER_LAST_NAME_IDXUPPER_LAST_NAME_IDXUPPER_LAST_NAME_IDX index from index from index from index from the data dictionary:the data dictionary:the data dictionary:the data dictionary:
• To drop an index, you must be the owner of the To drop an index, you must be the owner of the To drop an index, you must be the owner of the To drop an index, you must be the owner of the index or have the index or have the index or have the index or have the DROP ANY INDEXDROP ANY INDEXDROP ANY INDEXDROP ANY INDEX privilege. privilege. privilege. privilege.
DROP INDEX emp_last_name_idx;DROP INDEX emp_last_name_idx;DROP INDEX emp_last_name_idx;DROP INDEX emp_last_name_idx;Index dropped.Index dropped.Index dropped.Index dropped.
DROP INDEX DROP INDEX DROP INDEX DROP INDEX indexindexindexindex;;;;
10-41 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
SynonymsSynonymsSynonymsSynonyms
Logically represents subsets of data from Logically represents subsets of data from Logically represents subsets of data from Logically represents subsets of data from one or more tablesone or more tablesone or more tablesone or more tables
View View View View
Generates numeric valuesGenerates numeric valuesGenerates numeric valuesGenerates numeric valuesSequence Sequence Sequence Sequence
Basic unit of storage; composed of rows Basic unit of storage; composed of rows Basic unit of storage; composed of rows Basic unit of storage; composed of rows TableTableTableTable
Gives alternative names to objectsGives alternative names to objectsGives alternative names to objectsGives alternative names to objectsSynonym Synonym Synonym Synonym
Improves the performance of some Improves the performance of some Improves the performance of some Improves the performance of some queriesqueriesqueriesqueries
IndexIndexIndexIndex
DescriptionDescriptionDescriptionDescriptionObjectObjectObjectObject
10-42 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
SynonymsSynonymsSynonymsSynonyms
Simplify access to objects by creating a synonym Simplify access to objects by creating a synonym Simplify access to objects by creating a synonym Simplify access to objects by creating a synonym (another name for an object). With synonyms, you can:(another name for an object). With synonyms, you can:(another name for an object). With synonyms, you can:(another name for an object). With synonyms, you can:• Create an easier reference to a table that is owned Create an easier reference to a table that is owned Create an easier reference to a table that is owned Create an easier reference to a table that is owned
by another userby another userby another userby another user• Shorten lengthy object namesShorten lengthy object namesShorten lengthy object namesShorten lengthy object names
CREATE [PUBLIC] SYNONYM CREATE [PUBLIC] SYNONYM CREATE [PUBLIC] SYNONYM CREATE [PUBLIC] SYNONYM synonymsynonymsynonymsynonymFOR FOR FOR FOR objectobjectobjectobject;;;;
10-43 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating and Removing SynonymsCreating and Removing SynonymsCreating and Removing SynonymsCreating and Removing Synonyms
• Create a shortened name for the Create a shortened name for the Create a shortened name for the Create a shortened name for the DEPT_SUM_VU DEPT_SUM_VU DEPT_SUM_VU DEPT_SUM_VU view:view:view:view:
• Drop a synonym:Drop a synonym:Drop a synonym:Drop a synonym:
CREATE SYNONYM d_sumCREATE SYNONYM d_sumCREATE SYNONYM d_sumCREATE SYNONYM d_sumFOR dept_sum_vu;FOR dept_sum_vu;FOR dept_sum_vu;FOR dept_sum_vu;Synonym Created.Synonym Created.Synonym Created.Synonym Created.
DROP SYNONYM d_sum;DROP SYNONYM d_sum;DROP SYNONYM d_sum;DROP SYNONYM d_sum;Synonym dropped.Synonym dropped.Synonym dropped.Synonym dropped.
10-44 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating and Removing SynonymsCreating and Removing SynonymsCreating and Removing SynonymsCreating and Removing Synonyms
• 创建一个同义词时,基表可以不存在;
• 创建公共同义词时,需要相关权限;
• 公共同义词所有用户都能看到,但不一定能看到基表,取决于权限;
• 私有、公共同义词同名时,用户看到的同义词默认为私有同义词;
P63 Q100 P63 Q100 P63 Q100 P63 Q100 同义词概念,P85 Q139P85 Q139P85 Q139P85 Q139
10-45 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
SummarySummarySummarySummary
In this lesson, you should have learned how to:In this lesson, you should have learned how to:In this lesson, you should have learned how to:In this lesson, you should have learned how to:• Create, use, and remove viewsCreate, use, and remove viewsCreate, use, and remove viewsCreate, use, and remove views• Automatically generate sequence numbers by Automatically generate sequence numbers by Automatically generate sequence numbers by Automatically generate sequence numbers by
using a sequence generatorusing a sequence generatorusing a sequence generatorusing a sequence generator• Create indexes to improve query retrieval speedCreate indexes to improve query retrieval speedCreate indexes to improve query retrieval speedCreate indexes to improve query retrieval speed• Use synonyms to provide alternative names for Use synonyms to provide alternative names for Use synonyms to provide alternative names for Use synonyms to provide alternative names for
objectsobjectsobjectsobjects
10-46 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 10: Overview of Part 2Practice 10: Overview of Part 2Practice 10: Overview of Part 2Practice 10: Overview of Part 2
This practice covers the following topics:This practice covers the following topics:This practice covers the following topics:This practice covers the following topics:• Creating sequencesCreating sequencesCreating sequencesCreating sequences• Using sequencesUsing sequencesUsing sequencesUsing sequences• Creating nonunique indexesCreating nonunique indexesCreating nonunique indexesCreating nonunique indexes• Creating synonymsCreating synonymsCreating synonymsCreating synonyms
• P59 Q93P59 Q93P59 Q93P59 Q93
10-47 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
10-48 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
10-49 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.