Oracle Database 11g Using DDL Views Sequences Indexes and Synonyms
Oracle Database 11g Using DDL Views Sequences Indexes and Synonyms
After completing this topic, you should be able to recognize the steps for creating,
defining, and naming a table, and for specifying data types for its columns.
table
view
sequence
index
synonym
table
A table is the basic unit of data storage. It is composed of rows.
view
A view logically represents subsets of data from one or more tables.
sequence
A sequence generates numeric values.
index
An index improves the performance of some queries.
synonym
A synonym gives an alternative name to an object.
Oracle table structures have some characteristic features. These include
You can create tables at any time, even when users are using the database.
You do not need to specify the size of a table. The size is ultimately defined by the amount of
space allocated to the database as a whole. It is important, however, to estimate how much space
a table will use over time.
You can modify the table structure online.
You can name Oracle database tables and columns according to these standard rules for
naming an Oracle database object:
table names and column names must begin with a letter and be 130 characters long
names must contain only the characters AZ, az, 09, _ (underscore), $, and #. The $ and #
characters are legal characters, but their use is discouraged
names must not duplicate the name of another object owned by the same Oracle server user
Note
Names are not case-sensitive. For example, EMPLOYEES is treated to be the
same as eMPloyees or eMpLOYEES. However, quoted identifiers are casesensitive.
You can create tables to store data using
schema
table
DEFAULT expr
column
datatype
schema
The schema element in the syntax is the same as the owner's name.
table
The table element in the syntax is the name of the table.
DEFAULT expr
The DEFAULT expr element specifies a default value if a value is omitted in the INSERT
statement.
column
The column element is the name of the column.
datatype
The datatype element is the column's data type and length.
Using the AS subquery clause with the CREATE TABLE statement creates the table
and inserts rows returned from the subquery.
In the syntax for the AS subquery clause
column is the name of the column, default value, and integrity constraint
subquery is the SELECT statement that defines the set of rows to be inserted into the new table
CREATE TABLE table
[(column, column...)]
AS subquery;
Here are some guidelines for creating tables using the AS subquery clause:
the table is created with the specified column names, and the rows retrieved by the SELECT
statement are inserted into the table
the column definition can contain only the column name and default value
if column specifications are given, the number of columns must equal the number of columns in
the subquery SELECT list
Here are some more guidelines for creating tables using the AS subquery clause:
If no column specifications are given, the column names of the table are the same as the column
names in the subquery.
The column data type definitions and the NOT NULL constraint are passed to the new table. Note
that only the explicit NOT NULL constraint will be inherited. The PRIMARY KEY column will not
pass the NOT NULL feature to the new column. Any other constraint rules are not passed to the
new table. However, you can add constraints in the column definition.
This sample code creates a table named DEPT80, which contains details of all the
employees working in department 80.
Notice that the data for the DEPT80 table comes from the EMPLOYEES table.
CREATE TABLE dept80
AS
SELECT employee_id, last_name,
salary*12 ANNSAL,
hire_date
FROM
employees
WHERE
department_id = 80;
-------------------------------CREATE TABLE succeeded
You can verify the existence of a database table and check the column definitions by
using the DESCRIBE command.
DESCRIBE dept80
It is important to provide a column alias when selecting an expression in a subquery.
The expression SALARY*12 is given the alias ANNSAL. Without the alias, the error in this
sample code is generated.
CREATE TABLE
dept 80
AS SELECT
employee_id, last_name,
salary*12
hire_date FROM employees WHERE department_id
= 80
Note
In SQL Developer, you click the Run Script icon or press F5 to run the DDL
statements. The feedback messages will be shown on the Script Output tabbed
page.
This sample code creates the DEPT table with four columns: DEPTNO, DNAME, LOC, and
CREATE_DATE.
The CREATE_DATE column has a default value. If a value is not provided for an INSERT
statement, the system date is automatically inserted.
CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13),
create_date DATE DEFAULT SYSDATE);
---------------------------CREATE TABLE succeeded.
To confirm that the table was created, you run the DESCRIBE command.
Because creating a table is a DDL statement, an automatic commit takes place when the
CREATE TABLE statement is executed.
DESCRIBE dept
Question
Which Oracle Database 11g structure generates numeric values?
Options:
1.
Sequence
2.
Synonym
3.
Table
4.
View
Answer
A sequence generates numeric values.
Option 1 is correct. Sequences are database structures used to generate numeric
values for numeric columns of a database's tables.
Option 2 is incorrect. Synonyms give an alternative name to an object. Synonyms
do not generate numeric values.
Option 3 is incorrect. Tables are a basic unit of storage, composed of rows. Tables
do not generate numeric values.
Option 4 is incorrect. A view logically represents subsets of data from one or more
tables. Views do not generate numeric values.
Question
Which table names would be acceptable according to the standard rules for
naming any Oracle Database 11g object?
Options:
1.
902101_custdata
2.
custdata
3.
grant
4.
this_table_is_very_important_so_please_do_not_delete_it
Answer
The name custdata is acceptable as a table name.
Option 1 is incorrect. Table names and column names must begin with a letter.
Option 2 is correct. The example custdata meets all the requirements for
standard naming rules for any Oracle database object.
Option 3 is incorrect. Names must not be an Oracle server-reserved keyword.
Option 4 is incorrect. Table names must be 130 characters long.
VARCHAR2(size)
CHAR [(size)]
NUMBER [(p,s)]
DATE
LONG
CLOB
VARCHAR2(size)
The VARCHAR2(size) data type is used for variable-length character data. A maximum
size must be specified. The minimum size is 1, and the maximum size is 4,000.
CHAR [(size)]
The CHAR [(size)]data type is used for fixed-length character data of length-size bytes.
The default and minimum size is 1, and the maximum size is 2,000.
NUMBER [(p,s)]
The NUMBER [(p,s)] data type is used for numbers having precision p and scale s.
Precision is the total number of decimal digits and scale is the number of digits to the right
of the decimal point. Precision can range from 1 to 38, and scale can range from 84 to
127.
DATE
The DATE data type is used for date and time values to the nearest second between
January 1, 4712 B.C., and December 31, 9999 A.D.
LONG
The LONG data type is used for variable-length character data of up to 2 GB.
CLOB
The CLOB data type is used for character data of up to 4 GB.
RAW(size)
LONG RAW
BLOB
BFILE
ROWID
RAW(size)
The RAW(size)data type is used for raw binary data of length size. A maximum size must
be specified. The maximum size is 2,000.
LONG RAW
The LONG RAW data type is used for raw binary data of variable length of up to 2 GB.
BLOB
The BLOB data type is used for binary data of up to 4 GB.
BFILE
The BFILE data type is used for binary data stored in an external file of up to 4 GB.
ROWID
The ROWID data type is used for a base-64 number system representing the unique
address of a row in its table.
Here are some guidelines for providing a data type for a column:
TIMESTAMP
Question
Which data type allows you to enter variable-length character data, which must be
defined with a size?
Options:
1.
BLOB
2.
CHAR
3.
DATE
4.
VARCHAR2
Answer
The VARCHAR2 data type allows you to enter variable-length character data,
which must be defined with a size.
Option 1 is incorrect. The BLOB data type is a binary large object, not a variablelength character data type.
Option 2 is incorrect. The CHAR data type is a fixed-length character data type that
must be defined with a size. It is not a variable-length character type.
Option 3 is incorrect. The DATE data type stores date and time values to the
nearest second between January 1, 4712 B.C., and December 31, 9999 A. D.
Option 4 is correct. The VARCHAR2 data type allows for variable-length character
data. A maximum size must be specified. The minimum size is 1 and the
maximum size is 4,000.
Question
Which data type makes use of precision and scale?
Options:
1.
DATE
2.
LONG
3.
NUMBER
4.
VARCHAR2
Answer
The NUMBER data type makes use of precision and scale.
Option 1 is incorrect. The DATE data type allows for date and time values to the
nearest second between January 1, 4712 B.C., and December 31, 9999 A.D. You
would not specify precision and scale with this data type.
Option 2 is incorrect. The LONG data type allows for variable-length character
data. You would not specify precision and scale with this data type.
Option 3 is correct. The NUMBER data type allows for a number having precision,
p, and scale, s. Precision is the total number of decimal digits and scale is the
number of digits to the right of the decimal point.
Option 4 is incorrect. The VARCHAR2 data type allows for variable-length character
data. You would not specify precision and scale with this data type.
Summary
Some of the more popular database objects in an Oracle database are tables, views,
sequences, indexes, and synonyms. You name database tables and columns according
to the standard rules for naming Oracle database objects. You may use quoted identifiers
to represent the name of an object. You use the CREATE TABLE statement to create a
table and include constraints. You can also create a table based on another table by
using a subquery. When you define a table, you can specify that a column should be
given a default value by using the DEFAULT option.
When you identify a column for a table, you need to provide a data type for the column.
There are several data types available VARCHAR2(size), CHAR [(size)], NUMBER
[(p,s)], DATE, LONG, CLOB, RAW(size), LONG RAW, BLOB, BFILE, and ROWID. The
datetime data types are TIMESTAMP, INTERVAL YEAR TO MONTH, and INTERVAL DAY
TO SECOND.
Table of Contents
| Top of page |
| Learning objective |
Constraints
Learning objective
After completing this topic, you should be able to recognize the steps for using
constraints to prevent invalid data entry into tables.
1. Overview of constraints
The Oracle server uses constraints to prevent invalid data entry into tables. You can use
constraints to
enforce rules on the table data whenever a row is inserted, updated, or deleted from that table;
the constraint must be satisfied for the operation to succeed
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
NOT NULL
The NOT NULL constraint specifies that the column cannot contain a null value.
UNIQUE
The UNIQUE constraint specifies a column or combination of columns whose values must
be unique for all rows in the table.
PRIMARY KEY
The PRIMARY KEY constraint uniquely identifies each row of the table.
FOREIGN KEY
The FOREIGN KEY constraint establishes and enforces a referential integrity between the
column and a column of the referenced table such that values in one table match values in
another table.
CHECK
The CHECK constraint specifies a condition that must be true.
All constraints are stored in the data dictionary and are easy to refer if you give them a
meaningful name. The constraint names must follow the standard object-naming rules,
except that the name cannot be the same as another object owned by the same user. If
you do not name your constraint, the Oracle server generates a name with the format
SYS_Cn, where n is an integer so that the constraint name is unique.
Constraints can be defined at the time of table creation or after the creation of the table.
You can define a constraint at the column or table level. Functionally, a table-level
constraint is the same as a column-level constraint.
Here is the syntax to define constraints when creating a table.
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);
In this syntax
DEFAULT expr specifies a default value to be used if a value is omitted in the INSERT statement
column-level
table-level
column-level
You include column-level constraints when the column is defined. The NOT NULL
constraints must be defined at the column-level.
Syntax
column [CONSTRAINT constraint_name] constraint_type,
table-level
Table-level constraints are defined at the end of the table definition and must refer to the
column or columns on which the constraint pertains in a set of parentheses. Constraints
that apply to more than one column must be defined at the table-level.
Syntax
column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),"
Functionally, a table-level constraint is the same as a column-level constraint. It is mainly
the syntax that differentiates the two.
Constraints are usually created at the same time as the table. You can add constraints to
a table after its creation and contraints can also be temporarily disabled. Consider this
sample code of a column-level constraint. This code creates a primary key constraint on
the EMPLOYEE_ID column of the EMPLOYEES table.
CREATE TABLE employees(
employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY,
first_name VARCHAR2(20),
...);
Here is a sample code that uses the table-level syntax to define the constraint.
CREATE TABLE employees(
employee_id NUMBER(6),
first_name VARCHAR2(20),
...
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID));
Question
CHECK
2.
FOREIGN KEY
3.
PRIMARY KEY
4.
UNIQUE
Answer
A FOREIGN KEY constraint is used to establish and enforce referential integrity.
Option 1 is incorrect. A CHECK constraint is not used to establish and enforce
referential integrity. It specifies a condition that must be true.
Option 2 is correct. A FOREIGN KEY constraint is used to establish and enforce
referential integrity between the column and a column of the referenced table such
that values in one table match values in another table.
Option 3 is incorrect. A PRIMARY KEY constraint is not used to establish and
enforce referential integrity. It is used to uniquely identify each row of the table.
Option 4 is incorrect. A UNIQUE constraint is used to specify a column or
combination of columns whose values must be unique for all rows in the table. It is
not used to establish and enforce referential integrity.
2. Types of constraints
The various data integrity constraints include
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
The NOT NULL constraint ensures that the column contains no null values. By default,
columns without the NOT NULL constraint can contain null values. In the EMPLOYEES
table, the EMPLOYEE_ID column inherits the NOT NULL constraint as it is defined as a
primary key. Otherwise, the FIRST_NAME, LAST_NAME, EMAIL, HIRE_DATE, and
JOB_ID columns have the NOT NULL constraint enforced on them.
The UNIQUE key integrity constraint ensures that every value in a column or a set of
columns should be unique that is, no two rows of a table can have duplicate values in a
specified column or a set of columns. The column or set of columns included in the
definition of the UNIQUE key constraint is called the unique key. If the UNIQUE constraint
comprises more than one column, that group of columns is called a composite unique
key.
The UNIQUE constraints enable the input of nulls unless you define NOT NULL
constraints for the same columns. In fact, any number of rows can include nulls for
columns without the NOT NULL constraints because nulls are not considered equal to
anything. A null in a column or in all columns of a composite unique key always satisfies
the UNIQUE constraint.
Note
Because of the search mechanism for the UNIQUE constraints on more than one
column, you cannot have identical values in the non-null columns of a partially null
composite UNIQUE key constraint.
The UNIQUE constraint is defined at the column-level or table-level. You can define the
constraint at the table-level when you want to create a composite unique key. A
composite key is defined when there is not a single attribute that can uniquely identify a
row. In that case, you can have a unique key that is composed of two or more columns,
the combined value of which is always unique and can identify rows.
Note
The Oracle server enforces the UNIQUE constraint by implicitly creating a unique
index on the unique key column or columns.
Here is sample code to apply the UNIQUE constraint on the EMAIL column of the
EMPLOYEES table. The name of the constraint is EMP_EMAIL_UK.
CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
...
CONSTRAINT emp_email_uk UNIQUE(email));
The PRIMARY KEY constraint creates a primary key for the table. Only one primary key
can be created for each table. This constraint enforces the uniqueness of the column or
columns and ensures that no column that is part of the primary key can contain a null
value.
Note
Because uniqueness is part of the primary key constraint definition, the Oracle
server enforces the uniqueness by implicitly creating a unique index on the
primary key column or columns.
The FOREIGN KEY or referential integrity constraint designates a column or a
combination of columns as a foreign key and establishes a relationship with a primary key
or a unique key in the same table or a different table.
In this example, DEPARTMENT_ID is defined as the foreign key in the EMPLOYEES table
(dependent or child table). It references the DEPARTMENT_ID column of the
DEPARTMENTS table (the referenced or parent table).
You need to consider these guidelines when using the FOREIGN KEY constraint:
a foreign key value must match an existing value in the parent table or be NULL
foreign keys are based on data values and are purely logical, rather than physical, pointers
The FOREIGN KEY constraints can be defined at the column-level or table-level. A
composite foreign key must be created by using the table-level definition. This sample
code defines the FOREIGN KEY constraint on the DEPARTMENT_ID column of the
EMPLOYEES table, using table-level syntax. The name of the constraint is EMP_DEPT_FK.
CREATE TABLE employees(
employee_id
NUMBER(6),
last_name
VARCHAR2(25) NOT NULL,
email
VARCHAR2(25),
salary
NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
...
department_id NUMBER(4),
CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
REFERENCES departments(department_id),
CONSTRAINT emp_email_uk UNIQUE(email));
The foreign key can also be defined at the column-level, provided the constraint is based
on a single column. The syntax differs in that the keywords FOREIGN KEY do not appear.
This is the sample code for defining foreign key constraints at the column-level.
FOREIGN KEY
REFERENCES
ON DELETE CASCADE
a column. The CHECK constraints can be defined at the column-level or table-level. This is
sample code to define the CHECK constraints.
Example 1
..., salary NUMBER(2)
CONSTRAINT emp_salary_min
CHECK (salary > 0),...
Example 2
CREATE TABLE employees
(...
salary NUMBER(8,2) CONSTRAINT emp_salary_min
CHECK (salary > 0),
...
Here is a sample code that creates the EMPLOYEES table in the human resource (HR)
schema.
CREATE TABLE employees
( employee_id NUMBER(6)
CONSTRAINT emp_employee_id PRIMARY KEY, first_name VARCHAR2(20),
last_name VARCHAR2(25)
CONSTRAINT emp_last_name_nn NOT NULL, email VARCHAR2(25)
CONSTRAINT emp_email_nn NOT NULL
CONSTRAINT emp_email_uk UNIQUE, phone_number VARCHAR2(20),
hire_date DATE
CONSTRAINT emp_hire_date_nn NOT NULL, job_id VARCHAR2(10)
CONSTRAINT emp_job_nn NOT NULL, salary NUMBER(8,2)
CONSTRAINT emp_salary_ck CHECK (salary>0), commission_pct
NUMBER(2,2), manager_id NUMBER(6)
CONSTRAINT emp_manager_fk REFERENCES
employees (employee_id), department_id NUMBER(4)
CONSTRAINT emp_dept_fk REFERENCES
departments (department_id));
Question
What statement is true about FOREIGN KEY constraints?
Options:
1.
2.
3.
Foreign keys can be defined at the column or table constraint level in all cases
4.
Answer
Foreign keys are purely logical rather than physical pointers to the data.
Option 1 is incorrect. Composite foreign keys must be created using the tablelevel definition.
Option 2 is correct. Foreign keys are based on data values and are purely logical
rather than physical pointers to the data.
Option 3 is incorrect. The foreign key can be defined at the column level provided
that the constraint is based on a single column.
Option 4 is incorrect. The foreign key is defined in the child table and the table
containing the referenced column is the parent table.
Question
What keywords are used within a FOREIGN KEY constraint definition to delete
dependent rows in child tables when the related row in the parent table is deleted?
Options:
1.
FOREIGN KEY
2.
ON DELETE CASCADE
3.
4.
REFERENCES
Answer
You can use the ON DELETE CASCADE keywords to delete dependent rows in
child tables when the related row in the parent table is deleted.
Option 1 is incorrect. The FOREIGN KEY keywords are used to define the column
in the child table at the table-constraint level, not delete dependent rows.
Option 2 is correct. The ON DELETE CASCADE keywords indicates that when a
row in the parent table is deleted, the dependent rows in the child table are also
deleted.
Option 3 is incorrect. The ON DELETE SET NULL keywords indicate that when a
row in the parent table is deleted, the foreign key values are set to null.
Option 4 is incorrect. The REFERENCES keyword identifies the table and the
column in the parent table.
Question
How is the UNIQUE constraint enforced?
Options:
1.
2.
3.
4.
Answer
The UNIQUE constraint is enforced by creating an index on the unique key column
or columns.
Option 1 is correct. The Oracle server enforces the UNIQUE constraint by implicitly
creating a unique index on the unique key column or columns.
Option 2 is incorrect. A UNIQUE key integrity constraint requires that every value in
a column or a set of columns be unique so that no two rows of a table can have
duplicate values in a specified column or a set of columns. It is not enforced by
matching an existing value in a parent table.
Option 3 is incorrect. The UNIQUE constraints enable the input of nulls unless you
also define NOT NULL constraints for the same column.
Option 4 is incorrect. The UNIQUE constraint is not enforced by placing a
PRIMARY KEY constraint on the unique key column or columns. It is the PRIMARY
KEY constraint that is enforced via an implicit creation of a unique index on the
primary key column or columns by the Oracle server.
3. Constraints violation
When you have constraints in place on columns, an error is returned if you try to violate
the constraint rule. For example, if you try to update a record with a value that is tied to an
integrity constraint, an error is returned.
In this sample code, you will receive the "parent key not found" violation ORA-02291
because department 55 does not exist in the parent table, DEPARTMENTS.
UPDATE employees
SET department_id = 55
WHERE department_id = 110;
If you attempt to delete a record with a value that is tied to an integrity constraint, an error
is returned. You cannot delete a row that contains a primary key that is used as a foreign
key in another table.
This sample code tries to delete department 60 from the DEPARTMENTS table, but it
results in an error because that department number is used as a foreign key in the
EMPLOYEES table. If the parent record that you attempt to delete has child records, then
you receive the "child record found" violation ORA-02292.
DELETE FROM departments
WHERE department_id = 60;
Here is a sample code that works because there are no employees in department 70.
DELETE FROM departments
WHERE department_id = 70;
result:
1 row deleted
Summary
You can define constraints on a table to prevent invalid data entry. By defining constraints
you can enforce rules on the table data whenever a row is inserted, updated, or deleted
from that table and prevent deletion of a table if there are dependencies from other
tables.
You can define NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK
constraints on a table. You can define constraints at column-level and table-level at the
time of table creation or after the table creation. The column-level constraints are included
when the column is defined. The table-level constraints are defined at the end of the table
definition and must refer to the column or columns on which the constraint pertains in a
set of parentheses.
If you try to violate the constraint rule, you will receive an error.
Table of Contents
| Top of page |
| Learning objective |
| 1. Overview of constraints |
| 2. Types of constraints |
| 3. Constraints violation |
| Summary |
Copyright 2008 SkillSoft. All rights reserved.
SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.
| Print | Contents |
This article explains the steps for altering or dropping a table, using the ALTER TABLE
statement and the DROP TABLE statement.
only the creator of the table or a user with the DROP ANY TABLE privilege can remove a table
Note : Use the FLASHBACK TABLE statement to restore a dropped table from the recycle
bin.
Summary
After you create a table, you can change the table structure by using the ALTER TABLE
statement. You can move a table to the recycle bin using the DROP TABLE statement or
remove the table and all its data from the database entirely by using the DROP TABLE
[PURGE] statement.
Table of Contents
| Top of page |
| Abstract |
| ALTER TABLE Statement |
| DROP TABLE Statement |
| Summary |
Copyright 2008 SkillSoft. All rights reserved.
SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.
Views
Learning objective
After completing this topic, you should be able to identify the steps for creating and
manipulating views to view or hide a table's data.
1. Creating views
In addition to tables, there are several other objects in a database. These include views,
sequences, indexes, and synonyms.
Each database object performs a specific function.
Table
View
Sequence
Index
Synonym
Table
There are two classifications for views and the basic difference is related to the DML
(INSERT, UPDATE, and DELETE) operations:
simple
complex
simple
A simple view:
complex
A complex view:
You can create a view by embedding a subquery in the CREATE VIEW statement. This is
the syntax for this statement.
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];
Note
In SQL Developer, click the Run Script icon or press the F5 key to run the data
definition language (DDL) statements. The feedback messages are displayed on
the Script Output tabbed page.
In the syntax for the CREATE VIEW statement, various keywords and parameters are
specified:
OR REPLACE
FORCE
NOFORCE
view
alias
subquery
constraint
the subquery that defines a view can contain complex SELECT syntax, including joins, groups,
and subqueries
if you do not specify a constraint name for the view created with the WITH CHECK OPTION, the
system assigns a default name in the SYS_Cn format
you can use the OR REPLACE option to change the definition of the view without dropping and
recreating it, or re-granting the object privileges previously granted on it
You can control the column names by including column aliases in the subquery.
This sample code creates a view containing the employee number (EMPLOYEE_ID) with
the alias ID_NUMBER, name (LAST_NAME) with the alias NAME, and annual salary
(SALARY) with the alias ANN_SALARY for every employee in department 50.
CREATE VIEW salvu50
AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM employees
WHERE department_id = 50;
Alternatively, you can use an alias after the CREATE statement and before the SELECT
subquery. The number of aliases listed must match the number of expressions selected in
the subquery.
CREATE OR REPLACE VIEW salvu50 (ID_NUMBER, NAME, ANN_SALARY)
AS SELECT employee_id, last_name, salary*12
FROM employees
WHERE department_id = 50;
Question
Which Oracle Database 11g object is a logical table based on a table or view?
Options:
1.
An index
2.
A sequence
3.
A synonym
4.
A view
Answer
A view is a logical table based on a table or view.
Question
You need to create a view containing the employee number (EMPLOYEE_ID) with
the alias ID_NUMBER, name (LAST_NAME) with the alias NAME, and the annual
salary (SALARY) with the alias ANN_SALARY for every employee in department 50.
Which queries would successfully create this view?
Options:
1.
2.
3.
4.
Answer
These are the queries that can create a view with the required columns.
Option 1 is correct. You can control the column names by including column aliases
in the subquery.
Option 2 is incorrect. The column names cannot be listed after the CREATE
statement and before the SELECT subquery. It is the aliases that can be listed in
this section.
Option 3 is incorrect. The number of aliases listed must match the number of
expressions selected in the subquery. There are four aliases and only three
expressions in the subquery.
Option 4 is correct. You can use an alias after the CREATE statement and before
the SELECT subquery.
Note
When assigning column aliases in the CREATE OR REPLACE VIEW clause,
remember that the aliases are listed in the same order as the columns in the
subquery.
Here is a sample code that creates a complex view of department names, minimum
salaries, maximum salaries, and the average salaries by department. Note that
alternative names have been specified for the view. This is a requirement if any column of
the view is derived from a function or an expression.
CREATE OR REPLACE VIEW dept_sum_vu
(name, minsal, maxsal, avgsal)
AS SELECT d.department_name, MIN(e.salary),
MAX(e.salary),AVG(e.salary)
FROM employees e JOIN departments d
ON (e.department_id = d.department_id)
GROUP BY d.department_name;
You can view the structure of the view by using the DESCRIBE command and display the
contents of the view by issuing a SELECT statement.
SELECT *
FROM dept_sum_vu;
You can perform DML operations on data through a view if those operations follow certain
rules. You can remove a row from a view unless it contains any of these:
group functions
a GROUP BY clause
WITH CHECK OPTION clause, the view can see only the employees in department 20
and does not allow the department number for those employees to be changed through
the view.
UPDATE empvu20
SET department_id = 10
WHERE employee_id = 201;
You can ensure that no DML operations occur on your view by creating it with the WITH
READ ONLY option.
This sample code modifies the EMPVU10 view to prevent any DML operations on the
view.
CREATE OR REPLACE VIEW empvu10
(employee_number, employee_name, job_title)
AS SELECT employee_id, last_name, job_id
FROM employees
WHERE department_id = 10
WITH READ ONLY;
Any attempt to remove a row from a view with a read-only constraint results in an error.
Similarly, any attempt to insert a row or modify a row using the view with a read-only
constraint results in the same error.
DELETE FROM empvu10
WHERE employee_number = 200;
You use the DROP VIEW statement to remove a view. The statement removes the view
definition from the database. However, dropping views has no effect on the tables on
which the view was based.
On the other hand, views or other applications based on the deleted views become
invalid. Only the creator or a user with the DROP ANY VIEW privilege can remove a view.
This is the syntax for the DROP VIEW statement, in which view is the name of the view.
DROP VIEW view;
This sample code removes the view definition from the database.
DROP VIEW empvu80;
Question
Which clause in a CREATE VIEW statement prevents INSERT, UPDATE, and
DELETE statements from being performed on the view?
Options:
1.
FORCE
2.
OR REPLACE
3.
4.
Answer
The WITH READ ONLY clause in a CREATE VIEW statement prevents INSERT,
UPDATE, and DELETE statements from being performed on the view.
Option 1 is incorrect. The FORCE clause is used to create the view regardless of
whether or not the base tables exist.
Option 2 is incorrect. The OR REPLACE clause is used to recreate the view if it
already exists.
Option 3 is incorrect. The WITH CHECK OPTION clause specifies that only those
rows that are accessible to the view can be inserted or updated.
Option 4 is correct. The WITH READ ONLY clause when used within the CREATE
VIEW statement ensures that no DML operation can be performed on the view.
Summary
Various database objects include views, sequences, indexes, and synonyms. A view is a
logical table based on a table or another view. It enables you to restrict data access,
make complex queries easy, provide data independence, and present different views of
the same data. You can create a view by embedding a subquery in the CREATE VIEW
statement and display the structure of the view by using the DESCRIBE command. You
can control the column names by including column aliases in the subquery.
You can retrieve data from a view as you would from any table and display either the
contents of the entire view or just specific rows and columns. You can also perform
referential integrity checks and enforce constraints at the database level. You use the
DROP VIEW statement to remove a view.
Table of Contents
| Top of page |
| Learning objective |
| 1. Creating views |
| 2. Modifying and removing views |
| Summary |
Copyright 2008 SkillSoft. All rights reserved.
SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.
After completing this topic, you should be able to recognize the steps for using sequences
to create integers, using indexes to improve the performance of queries, and using
synonyms to give a table an alternative name.
1. Understanding sequences
A sequence is a user-created database object that generates integer values. You can
create sequences and then use them to generate numbers. A sequence can be shared by
multiple users to generate integers.
You can also define a sequence to generate unique values or to recycle and use the
same numbers again.
A typical use for sequences is to create a primary key value, which must be unique for
each row. A sequence is generated and incremented or decremented by an internal
Oracle routine. This can be a time-saving object because it can reduce the amount of
application code needed to write a sequence generating routine.
Sequence numbers are stored and generated independent of tables. Therefore, the same
sequence can be used for multiple tables.
You can automatically generate sequential numbers using the CREATE SEQUENCE
statement.
CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NONMAXVALUE}]
[{MINVALUE n | NONMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];
The various components of the syntax for the CREATE SEQUENCE statement are
sequence
INCREMENT BY n
START WITH n
MAXVALUE n
NONMAXVALUE
MINVALUE n
NONMINVALUE
CYCLE | NOCYCLE
CACHE n | NOCACHE
sequence
The component sequence is the name of the sequence generator.
INCREMENT BY n
INCREMENT BY n specifies the interval between sequence numbers, where n is an
integer. If this clause is omitted, the sequence increments by 1.
START WITH n
START WITH n specifies the first sequence number to be generated. If this clause is
omitted, the sequence starts with 1.
MAXVALUE n
MAXVALUE n specifies the maximum value the sequence can generate.
NONMAXVALUE
NONMAXVALUE specifies a maximum value of 10^27 for an ascending sequence and 1 for
a descending sequence. This is the default option.
MINVALUE n
MINVALUE n specifies the minimum sequence value.
NONMINVALUE
NONMINVALUE specifies a minimum value of 1 for an ascending sequence and (10^26)
for a descending sequence. This is the default option.
CYCLE | NOCYCLE
CYCLE | NOCYCLE specifies whether the sequence continues to generate values after
reaching its maximum or minimum value. NOCYCLE is the default option.
CACHE n | NOCACHE
CACHE n | NOCACHE specifies how many values the Oracle server preallocates and
keeps in memory. By default, the Oracle server caches 20 values.
This sample code creates a sequence named DEPT_DEPTID_SEQ to be used for the
DEPARTMENT_ID column of the DEPARTMENTS table. The sequence starts at 120, does
not allow caching, and does not cycle.
CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;
CREATE SEQUENCE succeeded
You should not use the CYCLE option if the sequence is used to generate primary key
values, unless you have a reliable mechanism that purges old rows faster than the
sequence cycles.
Note
The sequence is not tied to a table. Generally, you should name the sequence
after its intended use. However, the sequence can be used anywhere regardless
of its name.
After you create your sequence, it generates sequential numbers for use in your tables.
You reference the sequence values using these pseudocolumns:
NEXTVAL
CURRVAL
NEXTVAL
The NEXTVAL pseudocolumn is used to extract successive sequence numbers from a
specified sequence. You must qualify NEXTVAL with the sequence name. When you
reference sequence.NEXTVAL, a new sequence number is generated and the current
sequence number is placed in CURRVAL.
CURRVAL
The CURRVAL pseudocolumn is used to refer to a sequence number that the current user
has just generated. However, NEXTVAL must be used to generate a sequence number in
the current user's session before CURRVAL can be referenced. You must qualify CURRVAL
with the sequence name. When you reference sequence.CURRVAL, the last value
returned to that user's process is displayed.
You can use NEXTVAL and CURRVAL in these contexts:
system crash
NOCACHE
NOCYCLE;
To remove a sequence you can use a DROP SEQUENCE statement.
DROP SEQUENCE dept_deptid_seq;
Question
Which statement is true for sequences?
Options:
1.
2.
Modified sequences will allow a new MAXVALUE less than the current sequence
number
3.
4.
Answer
In sequences, the START WITH option cannot be changed using ALTER
SEQUENCE.
Option 1 is incorrect. Only future sequence numbers are affected by the ALTER
SEQUENCE statement.
Option 2 is incorrect. Some validation is performed when modifying sequences. A
new MAXVALUE less than the current sequence number cannot be imposed.
Option 3 is incorrect. Anyone with the ALTER privilege for a sequence can modify
it, as can the owner.
Option 4 is correct. The START WITH option cannot be changed using ALTER
SEQUENCE. The sequence must be dropped and recreated to restart the sequence
at a different number.
Question
Which statements are true for a sequence created with this code?
Options:
1.
2.
3.
4.
Answer
For the given code, the sequence will not generate values after reaching 9999
and the sequence will increment by 1.
Option 1 is incorrect. The CACHE clause specifies how many values the Oracle
server preallocates and keeps in memory. By default, the Oracle server caches 20
values.
Option 2 is correct. The INCREMENT BY clause specifies the interval between
sequence numbers. If omitted, the sequence increments by 1.
Option 3 is correct. The MAXVALUE clause specifies the maximum value the
sequence can generate is 9999 in this case.
Option 4 is incorrect. The statement will not fail because of a missing INCREMENT
clause. The sequence would use the default value of 1 if the INCREMENT clause is
missing.
2. Understanding indexes
Indexes are database objects that you can create to improve the performance of some
queries. Indexes can also be created automatically by the server when you create a
primary key or a unique constraint.
An Oracle server index is a schema object that can speed up the retrieval of rows by
using a pointer. Indexes can be created explicitly or automatically. If you do not have an
index on the column, then a full table scan occurs.
An index provides direct and fast access to rows in a table. Its purpose is to reduce the
disk I/O by using an indexed path to locate data quickly. An index is used and maintained
automatically by the Oracle server. After an index is created, no direct activity is required
by the user.
Indexes are logically and physically independent on the table that they index. This means
that they can be created or dropped at any time, and have no effect on the base tables or
other indexes.
Note
When you drop a table, the corresponding indexes are also dropped.
You can create two types of indexes:
unique index
nonunique index
unique index
The Oracle server automatically creates this index when you define a column in a table to
have a PRIMARY KEY or a UNIQUE constraint. The name of the index is the name that is
given to the constraint.
You can manually create a unique index, but it is recommended that you create a unique
constraint, which implicitly creates a unique index.
nonunique index
This is an index that a user can create. For example, you can create the FOREIGN KEY
column index for a join in a query to improve the speed of retrieval.
You create an index on one or more columns by issuing the CREATE INDEX statement.
In this syntax index is the name of the index, table is the name of the table, and
column is the name of the column in the table to be indexed.
You specify
UNIQUE to indicate that the value of the column (or columns) upon which the index is based must
be unique.
BITMAP to indicate that the index is to be created with a bitmap for each distinct key, rather than
indexing each row separately. Bitmap indexes store the row ids associated with a key value as a
bitmap.
CREATE [UNIQUE][BITMAP]INDEX index
ON table (column[, column]...);
Having more indexes on a table does not produce faster queries. Each data manipulation
language (DML) operation that is committed on a table with indexes means that the
indexes must be updated. The more indexes that you have associated with a table, the
more effort the Oracle server must make to update all the indexes after a DML operation.
You create an index when
one or more columns are frequently used together in a WHERE clause or a join condition
the table is large and most queries are expected to retrieve less than 2% to 4% of the rows in the
table
You do not create an index when:
Note
If you want to enforce uniqueness, you should define a unique constraint in the
table definition. A unique index is then created automatically.
You cannot modify indexes. To change an index, you must drop it and then re-create it.
Remove an index definition from the data dictionary by issuing the DROP INDEX
statement.
To drop an index, you must be the owner of the index or have the DROP ANY INDEX
privilege. In the syntax, index is the name of the index. For example, to remove the
emp_last_name_idx index from the data dictionary you use this code.
DROP INDEX index;
If you drop a table, indexes and constraints are automatically dropped but views and
sequences remain.
Question
In which situations would it be advisable to create an index?
Options:
1.
When the columns are not often used as a condition in the query
2.
3.
4.
Answer
It is advisable to create an index when the column contains a wide range of values
and when the table is large and queries will be very selective.
Option 1 is incorrect. It is advisable to create an index if one or more columns are
frequently used together in a WHERE clause or a join operation. If the columns are
not often used as a condition in the query, an index should not be created on it.
Option 2 is correct. If the column contains a small number of values it is not a
good candidate as an index column. Columns with a wide range of values are
good candidates.
Option 3 is correct. Large tables, in which the majority of queries are expected to
retrieve less than 2% to 4% of the rows of the table, are good candidates for
indexing.
Option 4 is incorrect. Each DML operation that is committed on a table with
indexes means the indexes must be updated. So columns that are updated
frequently are poor index column candidates.
3. Understanding synonyms
Synonyms are database objects that enable you to call a table by another name. You can
create synonyms to give an alternative name to a table.
To refer to a table that is owned by another user, you need to prefix the table name with
the name of the user who created it, followed by a period.
Creating a synonym eliminates the need to qualify the object name with the schema and
provides you with an alternative name for a table, view, sequence, procedure, or other
objects. This method can be especially useful with lengthy object names, such as views.
CREATE [PUBLIC] SYNONYM synonym
FOR object;
The various components of the syntax for creating a synomym are
PUBLIC
synonym
object
PUBLIC
PUBLIC creates a synonym that is accessible to all users.
synonym
The synonym component is the name of the synonym to be created.
object
The object component identifies the object for which the synonym is created.
The guidelines for creating synonyms include
a private synonym name must be distinct from all other objects that are owned by the same user
This sample code creates a synonym for the DEPT_SUM_VU view for quicker reference.
The database administrator can create a public synonym that is accessible to all users.
CREATE SYNONYM d_sum
FOR dept_sum_vu;
This sample code creates a public synonym named DEPT for Alice's DEPARTMENTS table.
CREATE PUBLIC SYNONYM dept
FOR alice.departments;
To remove a synonym, you use the DROP SYNONYM statement. Only the database
administrator can drop a public synonym.
DROP PUBLIC SYNONYM dept;
Summary
Sequences are user-defined database objects that generate numeric values. You can
automatically generate sequential numbers using the CREATE SEQUENCE statement.
Sequences can be used to generate primary key values that are unique.
Indexes are database objects used to improve the performance of some queries. An
index can also be created automatically by the server when you create a primary key or a
unique constraint. It provides direct and fast access to rows in a table and is used to
reduce the disk I/O.
Synonyms are database objects that enable you to call a table by another name. You can
create synonyms to give an alternative name to database objects.
Table of Contents
| Top of page |
| Learning objective |
| 1. Understanding sequences |
| 2. Understanding indexes |
| 3. Understanding synonyms |
| Summary |
Copyright 2009 SkillSoft. All rights reserved.
SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.
After completing this topic, you should be able to create a new table and create and use a
sequence, index, and synonym.
Exercise overview
In this exercise, you are required to complete and identify DDL statements.
This involves the following tasks:
creating tables
creating views
Step 1 of 6
You want to create a new DEPT table with two columns called ID and NAME. There
must be a primary key constraint on the ID column. The ID column must accept a
maximum of 7 decimal digits. The NAME column must accept entries with a
maximum of 25 variable-length characters.
Type the <missing code> to perform this task.
<missing code>
(id NUMBER(7)CONSTRAINT department_id_pk PRIMARY KEY, name
VARCHAR2(25));
Result
You type this code:
CREATE TABLE dept
The PRIMARY KEY constraint is a column or columns to uniquely identify each
row in a table. This constraint enforces the uniqueness of the column or columns
and ensures that no column that is part of the primary key can contain a null value.
Now you want to populate the DEPT table with information from another table.
Step 2 of 6
You want to populate the DEPT table with data from the DEPARTMENTS table and
include only those columns that you need.
Identify the code that you would use to complete this task.
Options:
1.
2.
3.
4.
Result
Step 3 of 6
You need to create a table called EMP with four columns. The ID and the DEPT_ID
column should accept a maximum of 7 decimal digits. The LAST_NAME and
FIRST_NAME columns must accept entries with a maximum of 25 characters.
There is also a FOREIGN KEY constraint on the DEPT_ID column that references
the ID column of the DEPT table.
Complete the code to perform this task.
Result
You type this code:
(id NUMBER(7),
The FOREIGN KEY establishes and enforces a referential integrity between the
column and a column of the referenced table so that the values in one table match
the values in another table.
Now you want to change the status of the table to read-only.
Step 4 of 6
You want to change the status of the EMP table to read-only.
Type the code that will alter the status of the EMP table.
Result
You type this code:
ALTER TABLE emp READ ONLY;
Because the EMP table is set to READ ONLY, you get the "Update operation not
allowed on table" error message when you try to insert a row. Hence, you are not
allowed to insert any row into the table because it is assigned a read-only status.
You want to insert some rows in a table. As a result, you now want to change the status of
the table to read/write.
Step 5 of 6
You want to revert the status of the EMP table to read/write.
Type the code that enables you to do this.
Result
You type this code:
ALTER TABLE emp READ WRITE;
Because the table is assigned a READ WRITE status, you will be allowed to insert
a row into the table.
You realize that the table is not required in the database and you want to remove it.
Step 6 of 6
You want to remove the EMP table from the database.
Type the code that enables you to do this.
Result
You type this code:
DROP TABLE emp;
You can even drop a table that is in the READ ONLY mode.
Step 1 of 2
The HR department wants to hide some of the data in the EMPLOYEES table. It
wants you to create a view called EMPLOYEES_VU based on the employee
numbers, employee last names, and department numbers from the EMPLOYEES
table. The department also wants the heading for the employee name column to
be EMPLOYEE.
Which statement will do this?
Options:
1.
2.
3.
4.
Result
Step 2 of 2
You are creating a view named DEPT50 that contains the ids, last names, and
department numbers for all employees in department 50. For security purposes,
you can not allow an employee to be reassigned to another department. You need
to define a CHECK CONSTRAINT called emp_dept_50 to implement this security.
Complete the code to perform this task.
Result
You type this code:
WITH CHECK OPTION CONSTRAINT emp_dept_50;
An error will now occur if someone attempts to reassign an employee to a different
department number. The DEPT50 view has been created with the CHECK
CONSTRAINT to ensure that the DEPTNO column is protected from being changed.
Step 1 of 3
You need a sequence that can be used with the primary key column of the DEPT
table. The sequence should start at 200 and have a maximum value of 1,000. Your
sequence must increment by 10, and you want to name the sequence
DEPT_ID_SEQ.
Which statement will do this?
Options:
1.
2.
3.
4.
Result
This statement will perform this task:
CREATE SEQUENCE dept_id_seq
START WITH 200
INCREMENT BY 10
MAXVALUE 1000;
Option 1 is incorrect. The sequence should start with 200 and increment by 10,
and not start with 10 and increment by 200.
Option 2 is correct. This sequence statement will start at 200, have an increment
of 10, and have a maximum value of 1,000.
Option 3 is incorrect. The sequence should have a MAXVALUE of 1,000 and not a
MINVALUE of 1,000.
Option 4 is incorrect. The sequence name should be called DEPT_ID_SEQ and
not DEPT_ID. The sequence should have a MAXVALUE of 1,000 and not a
MINVALUE of 1,000.
The HR department has now asked you to create a nonunique index on the column of a
table.
Step 2 of 3
Create a nonunique index on the NAME column in the DEPT table called
dept_name_idx.
Type the code that will run this task.
Result
To create a nonunique index on the NAME column in the DEPT table, you type this
code:
CREATE INDEX dept_name_idx ON dept (name);
You can create an index on one or more columns by issuing the CREATE INDEX
statement.
You also want to create a synonym for a table in the database.
Step 3 of 3
You want to create a synonym for the EMPLOYEES table and name it as EMP.
Type the code that will complete this task.
Result
To create a synonym for the EMPLOYEES table, you type this code:
CREATE SYNONYM emp FOR EMPLOYEES;
You can create synonyms to give an alternative name to a table by issuing the
CREATE SYNONYM statement.
Table of Contents
| Top of page |
| Learning objective |
| Exercise overview |
| Task 1: Creating tables |
| Task 2: Creating views |
| Task 3: Creating other schema objects |
Copyright 2008 SkillSoft. All rights reserved.
SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.