Summary
331
Now you’ll create the
CITY
table. Notice the foreign key constraint is created with the
ON
DELETE CASCADE
clause:
SQL> CREATE TABLE city (
2 city_code VARCHAR2 (6),
3 city_name VARCHAR2 (40) NOT NULL,
4 country_code NUMBER (4) NOT NULL,
5 state_code VARCHAR2 (3) NOT NULL,
6 population NUMBER (15),
7 created DATE DEFAULT SYSDATE,
8 constraint pk_city PRIMARY KEY (city_code),
9 constraint fk_cigy FOREIGN KEY
10 (country_code, state_code)
11 REFERENCES state ON DELETE CASCADE);
Table created.
SQL>
Summary
Tables are the basic structure of data storage. A table comprises columns and rows, as
in a spreadsheet. Each column has a characteristic that restricts and verifies the data it
stores. You can use several datatypes to define columns. CHAR, NCHAR, VARCHAR2,
CLOB, and NCLOB are the character datatypes. BLOB, BFILE, and RAW are the binary
datatypes. DATE, TIMESTAMP, and INTERVAL are the date datatypes. TIMESTAMP
datatypes can store the time-zone information also. NUMBER, BINARY_FLOAT, and
BINARY_DOUBLE are the numeric datatypes.
You use the
ENABLE VALIDATE
is the default state.
95127c06.indd 331 2/18/09 6:45:51 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
332
Chapter 6
N
Creating Tables and Constraints
Exam Essentials
Understand datatypes. Know each datatype’s limitations and accepted values. Concen-
trate on the new TIMESTAMP and INTERVAL datatypes.
Know how date arithmetic works. Know the resulting datatype of date arithmetic, espe-
cially between INTERVAL and DATE datatypes.
Know how to modify column characteristics. Understand how to change datatypes, add
and modify constraints, and make other modifications.
Understand the rules associated with changing datatype definitions of columns with rows
in a table. When the table is not empty, you can change a datatype only from CHAR to
VARCHAR2, and vice versa. Reducing the length is allowed only if the existing data fits in
the new length specified.
Understand the
DEFAULT
clause on the column definition. T h e
DEFAULT
clause provides a
value for the column if the
INSERT
statement omits a value for the column. When modify-
ing a column to have default values, the existing rows with
NULL
Check constraint
ck_cnt_code
(disabled)
Check constraint
ck_st_code
(enabled)
NOT NULL
constraint
nn_st_name
(enabled)
You execute the following SQL:
CREATE TABLE STATE_NEW AS SELECT * FROM STATE;
How many constraints will there be in the new table?
A. 0
B. 1
C. 3
D. 5
E. 2
2. Which line of code has an error?
1 CREATE TABLE FRUITS_VEGETABLES
2 (FRUIT_TYPE VARCHAR2,
3 FRUIT_NAME CHAR (20),
4 QUANTITY NUMBER);
A. 1
B. 2
C. 3
D. 4
3. Which statement successfully adds a new column, ORDER_DATE, to the table ORDERS?
A. ALTER TABLE ORDERS ADD COLUMN ORDER_DATE DATE;
B. ALTER TABLE ORDERS ADD ORDER_DATE (DATE);
D. USR_TABLES
7. The STATE table has six rows. You issue the following command:
ALTER TABLE STATE ADD UPDATE_DT DATE DEFAULT SYSDATE;
Which of the following is correct?
A. A new column, UPDATE_DT, is added to the STATE table, and its contents for the exist-
ing rows are NULL.
B. Since the table is not empty, you cannot add a new column.
C. The DEFAULT value cannot be provided if the table has rows.
D. A new column, UPDATE_DT, is added to STATE and is populated with the current system
date and time.
95127c06.indd 334 2/18/09 6:45:52 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Review Questions
335
8. The HIRING table has the following data:
EMPNO HIREDATE
--------- ----------
1021 12-DEC-00
3400 24-JAN-01
2398 30-JUN-01
What will be result of the following query?
SELECT hiredate+1 FROM hiring WHERE empno = 3400;
A. 4-FEB-01
B. 25-JAN-01
C. N-02
D. None of the above
9. What is the default length of a CHAR datatype column if no length is specified in the table
definition?
A. 256
ALTER TABLE CITY ADD PRIMARY KEY CONSTRAINT PK_CITY ON (STATE_CD, CITY_CD);
13. Which of the following check constraints will raise an error? (Choose all that apply.)
A. CONSTRAINT ck_gender CHECK (gender IN (‘M’, ‘F’))
B. CONSTRAINT ck_old_order CHECK (order_date > (SYSDATE - 30))
C. CONSTRAINT ck_vendor CHECK (vendor_id IN (SELECT vendor_id FROM vendors))
D. CONSTRAINT ck_profit CHECK (gross_amt > net_amt)
14. Consider the datatypes DATE, TIMESTAMP (TS), TIMESTAMP WITH LOCAL TIME
ZONE (TSLTZ), INTERVAL YEAR TO MONTH (IY2M), and INTERVAL DAY TO
SECOND (ID2S). Which operations are not allowed by Oracle Database 11g? (Choose all
that apply.)
A. DATE+DATE
B. TSLTZ–DAT E
C. TSLTZ+IY2M
D. TS*5
E. ID2S/2
F. IY2M+IY2M
G. ID2S+IY2M
H. DATE–IY2M
15. A constraint is created with the DEFERRABLE INITIALLY IMMEDIATE clause. What does this
mean?
A. Constraint checking is done only at commit time.
B. Constraint checking is done after each SQL statement is executed, but you can change
this behavior by specifying SET CONSTRAINTS ALL DEFERRED.
C. Existing rows in the table are immediately checked for constraint violation.
D. The constraint is immediately checked in a DML operation, but subsequent constraint
verification is done at commit time.
16. What is the default precision for fractional seconds in a TIMESTAMP datatype column?
A. 0
B. 2
C. 6
20. Tom executed the following SQL statement.
create table xx (n number, x long, y clob);
Choose the best option.
A. A table named xx will be created.
B. Single-character column names are not allowed in table definitions.
C. When using the LONG datatype, other LOB datatypes cannot be used in table
definitions.
D. One of the datatypes used in the column definition needs the size specified.
95127c06.indd 337 2/18/09 6:45:52 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
338
Chapter 6
N
Creating Tables and Constraints
Answers to Review Questions
1. B. When you create a table using CTAS (CREATE TABLE AS SELECT), only the NOT NULL
constraints are copied.
2. B. A VARCHAR2 datatype should always specify the maximum length of the column.
3. C. The correct statement is C. When adding only one column, the column definition doesn’t
need to be enclosed in parentheses.
4. B, D. Only three special characters ($, _, and #) are allowed in table names along with let-
ters and numbers.
5. C. All identifiers (column names, table names, and so on) must begin with an alphabetic
character. An identifier can contain alphabetic characters, numbers, and the special charac-
ters $, #, and _.
6. C. The USER_TABLES view provides information on the tables owned by the user who
has logged on that session. DBA_TABLES will have all the tables in the database, and ALL_
TABLES will have the tables owned by you as well as the tables to which you have access.
USR_TABLES is not a valid dictionary view.
date the constraint for each SQL statement executed.
16. C. The default precision is 6 digits. The precision can range from 0 to 9.
17. C. Only TIMESTAMP WITH TIME ZONE stores the time-zone information as a dis-
placement from UTC. TIMESTAMP WITH LOCAL TIME ZONE adjusts the time to the
database’s time zone before storing it.
18. C. You can disable a constraint by specifying its constraint name. You may enable the
constraint after the load and avoid the constraint checking while enabling using the ALTER
TABLE ORDERS MODIFY CONSTRAINT FK_ORDERS ENABLE NOVALIDATE; command.
19. C. RENAME can be used to rename objects owned by the user. ALTER TABLE should be used
to rename tables owned by another user. To do so, you must have the ALTER privilege on the
table or the ALTER ANY TABLE privilege.
20. A. The table will be created without error. A table cannot have more than one LONG column,
but LONG and multiple LOB columns can exist together. If a LONG or LONG RAW
column is defined, another LONG or LONG RAW column cannot be used.
95127c06.indd 339 2/18/09 6:45:52 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
95127c06.indd 340 2/18/09 6:45:52 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter
7
Creating Schema
Objects
ORACLE DATABASE 11g: SQL
FUNDAMENTALS I EXAM OBJECTIVES
COVERED IN THIS CHAPTER:
Creating Other Schema Objects
Create simple and complex views
Retrieve data from views
actual data is not copied anywhere. This means that creating views does not take any stor-
age space other than the space in the dictionary.
Use the
CREATE VIEW
statement to create a view. The query that defines the view can
refer to one or more tables, to materialized views, or to other views. Let’s begin by creating
a simple view. This example will use the
EMPLOYEES
table of the
HR
schema as the base table:
SQL> DESCRIBE employees
Name Null? Type
-------------------------- -------- -------------
EMPLOYEE_ID NOT NULL NUMBER(6)
FIRST_NAME VARCHAR2(20)
95127c07.indd 342 2/17/09 12:33:19 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Creating and Modifying Views
343
LAST_NAME NOT NULL VARCHAR2(25)
EMAIL NOT NULL VARCHAR2(25)
PHONE_NUMBER VARCHAR2(20)
HIRE_DATE NOT NULL DATE
JOB_ID NOT NULL VARCHAR2(10)
SALARY NUMBER(8,2)
COMMISSION_PCT NUMBER(2,2)
MANAGER_ID NUMBER(6)
DEPARTMENT_ID NUMBER(4)
schema.
The views that actually copy data from base tables and take up storage are
called materialized views. Materialized views are commonly used in data-
warehouse environments. In earlier versions of Oracle, materialized views
were called snapshots, and they are sometimes still called snapshots.
95127c07.indd 343 2/17/09 12:33:19 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
344
Chapter 7
Creating Schema Objects
When numeric operations are performed using numeric datatypes in the view definition,
the resulting column will be a floating datatype, which is NUMBER without any precision
or scale. The following example uses
SALARY
(defined
NUMBER (8,2)
) and
COMMISSION_PCT
(defined
NUMBER (2,2)
) in an arithmetic operation. The resulting column value is the
NUMBER datatype.
CREATE VIEW emp_sal_comm AS
SELECT employee_id, salary,
salary * NVL(commission_pct,0) commission
FROM employees;
View created.
hire_date, commission_amt)
AS SELECT employee_id, first_name || ‘ ‘ || last_name,
department_name, TO_CHAR(hire_date,’DD-MM-YYYY’),
salary * NVL(commission_pct, .5)
95127c07.indd 344 2/17/09 12:33:19 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Creating and Modifying Views
345
FROM employees JOIN departments USING (department_id)
ORDER BY first_name || ‘ ‘ || last_name;
View created.
SQL> DESC emp_hire
Name Null? Type
-------------------------- -------- ------------
EMPLOYEE_ID NOT NULL NUMBER(6)
EMPLOYEE_NAME VARCHAR2(46)
DEPARTMENT_NAME NOT NULL VARCHAR2(30)
HIRE_DATE VARCHAR2(10)
COMMISSION_AMT NUMBER
SQL>
If you use an asterisk (
*
) to select all columns from a table in the query to
create a view and you later modify the table to add columns, you should
re-create the view to reflect the new columns. When
*
is used, Oracle
expands it to the column list and stores the definition in the database.
Creating Views with Errors
Chapter 7
Creating Schema Objects
Since you did not use the
FORCE
option, the view was not created. When you use the
FORCE
option, Oracle creates the view. However, trying to access the view gives an error, because
the table
TEST_TABLE
does not exist yet:
CREATE FORCE VIEW test_view AS
SELECT c1, c2 FROM test_table;
Warning: View created with compilation errors.
SELECT * FROM test_view;
SELECT * FROM test_view
*
ERROR at line 1:
ORA-04063: view “HR.TEST_VIEW” has errors
Now, let’s create the
TEST_TABLE
and access the view:
CREATE TABLE test_table (
c1 NUMBER (10),
c2 VARCHAR2 (20));
Table created.
SQL> SELECT * FROM test_view;
no rows selected
SQL>
the base tables. When creating constraints on views, you must always include the
DISABLE
NOVALIDATE
clause. You can define primary key, unique key, and foreign key constraints on
views. The syntax for creating constraints on views is the same as for creating constraints
on a table (see Chapter 6).
The following example creates a view with constraints. Line 2 defines a column-level
foreign key constraint, line 5 defines a column-level unique constraint, and line 7 defines a
view-level foreign key constraint. The column-level constraint is called an inline constraint,
and the view-level constraint is called an out-of-line constraint.
SQL> CREATE VIEW emp_details
2 (employee_no CONSTRAINT fk_employee_no
3 REFERENCES employees DISABLE NOVALIDATE,
4 manager_no,
5 phone_number CONSTRAINT uq_email unique
6 DISABLE NOVALIDATE,
7 CONSTRAINT fk_manager_no FOREIGN KEY (manager_no)
8 REFERENCES employees DISABLE NOVALIDATE)
9 AS SELECT employee_id, manager_id, phone_number
10 FROM employees
11 WHERE department_id = 40
SQL> /
View created.
SQL>
Modifying Views
To change the definition of the view, use the
CREATE VIEW
statement with the
OR REPLACE
email, job_id
FROM employees
WHERE department_id = 10;
View created.
Recompiling a View
Views become invalid when the base tables are altered. Oracle automatically recompiles the
view when it is accessed, but you can explicitly recompile the view using the
ALTER VIEW
statement. When the view is recompiled, the objects dependent on the view become invalid.
Let’s change the length of a column in the
TEST_TABLE
table created earlier. The
TEST_
VIEW
view is dependent on this table. You can see the status of the database objects in the
USER_OBJECTS
view. The following example queries the status of the view, modifies the table,
queries the status of the view, compiles the view, and again queries the status of the view:
SQL> SELECT last_ddl_time, status FROM user_objects
2 WHERE object_name = ‘TEST_VIEW’;
LAST_DDL_TIME STATUS
----------------------- -------
25-OCT-2001 11:17:24 AM VALID
SQL> ALTER TABLE test_table MODIFY c2 VARCHAR2 (8);
Table altered.
SQL> SELECT last_ddl_time, status FROM user_objects
2 WHERE object_name = ‘TEST_VIEW’;
95127c07.indd 348 2/17/09 12:33:19 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Dropping a View
To drop a view, use the
DROP VIEW
statement. The view definition is dropped from the dic-
tionary, and the privileges and grants on the view are also dropped. Other views and stored
programs that refer to the dropped view become invalid.
SQL> DROP VIEW test_view;
View dropped.
SQL>
95127c07.indd 349 2/17/09 12:33:19 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
350
Chapter 7
Creating Schema Objects
Once a view is dropped, there is no rollback, and the view is not available in the Recycle
Bin. So, be sure before dropping the view.
Using Views
You can use a view in most places where a table is used, such as in queries and in DML
operations. If certain conditions are met, most single-table views and many join views
can be used to insert, update, and delete data from the base table. All operations on views
affect the data in the base tables; therefore, they should satisfy any integrity constraints
defined on the base tables.
The following are some common uses of views:
To represent a subset of data For security reasons, you may not want certain users to see
all the rows of your table. You may create a view on the columns that the users need to
access with a
WHERE
clause to limit the rows and then grant privileges on the view.