Using DDL Statements to Create and Manage Tables: license to use this Student Guideฺ
Using DDL Statements to Create and Manage Tables: license to use this Student Guideฺ
Using DDL Statements to Create and Manage Tables: license to use this Student Guideฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
ble
fe r a
ans
n - t r
o
s an
) ha eฺ
c o m uid
ฺ
ail ent G
m
g tud
t @
ei isAllSrights reserved.
o v
pr se th
Copyright © 2009, Oracle.
n i
( ma to u
N S nse
D A lice
AN
N I K
MA
SQL Star International Limited
Objectives
following:
• Categorize the main database objects
• Review the table structure
• List the data types that are available for columns
• Create a simple table
• Explain how constraints are created at the time of table
a b le
creation
s f er
• Describe how schema objects work tran n -
n o
s a
a
) h deฺ
m
co Gui
i l ฺ
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
( m t o
Objectives
N S nse
In this lesson,D
you l i e to the data definition language (DDL) statements. You are
A are introduced
c
taughtK the N of how to create simple tables, alter them, and remove them. The data types
Abasics
I
AN in DDL are shown, and schema concepts are introduced. Constraints are tied into this
available
Mlesson. Exception messages that are generated from violating constraints during DML are shown
and explained.
Database Objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Object Description
Table Basic unit of storage; composed of rows
View Logically represents subsets of data from one or
more tables
Sequence Generates numeric values
Index Improves the performance of some queries
ble
Synonym Gives alternative names to objects
fe r a
ans
n - t r
a no
h a s
m ) deฺ
i l ฺ c o
G ui
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
Database Objects S ( m t o
N n s e
e
DA canliccontain multiple data structures. Each structure should be outlined in
An Oracle Database
N
A design so that it can be created during the build stage of database development.
I K
the database
• NTable: Stores data
MA • View: Subset of data from one or more tables
• Sequence: Generates numeric values
• Index: Improves the performance of some queries
• Synonym: Gives alternative names to objects
Oracle Table Structures
• Tables can be created at any time, even while 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.
• Table structure can be modified online.
Note: More database objects are available but are not covered in this course.
Naming Rules
schema.
• You should use the owner’s name as a prefix to those
tables.
ble
fe r a
ans
n - t r
USERA USERB
a no
SELECT * SELECT *
h a s
FROM userB.employees; m ) deฺ
FROM userA.employees;
i l ฺ c o
G ui
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
( m
Referencing AnotherSUser’s Tables t o
N n s e
A schema is aD collection e
A licof objects. Schema objects are the logical structures that directly refer
N
A in a database. Schema objects include tables, views, synonyms, sequences, stored
N I K
to the data
MIfAa table does not belong to the user, the owner’s name must be prefixed to the table. For
procedures, indexes, clusters, and database links.
example, if there are schemas named USERA and USERB, and both have an EMPLOYEES table,
then if USERA wants to access the EMPLOYEES table that belongs to USERB, he or she must
prefix the table name with the schema name:
SELECT *
FROM userb.employees;
If USERB wants to access the EMPLOYEES table that is owned by USERA, he must prefix the
table name with the schema name:
SELECT *
FROM usera.employees;
DEFAULT Option
Creating Tables
Because creating a table is a DDL statement, an automatic commit takes place when this
statement is executed.
Data Types
ROWID A base-64 num ber system representing the unique address of a row
in its table
Guidelines
• A LONG column is not copied when a table is created using a subquery.
• A LONG column cannot be included in a GROUP BY or an ORDER BY clause.
• Only one LONG column can be used per table.
• No constraints can be defined on a LONG column. ble
• You might want to use a CLOB column rather than a LONG column. fe r a
ans
n - t r
o
s an
) ha eฺ
c o m uid
ฺ
ail ent G
m
g tud
t @
ei is S
ov
n i pr se th
( ma to u
N S nse
D A lice
A N
N I K
MA
Note: These datetime data types are available with Oracle9i and later releases. For detailed
information about the datetime data types, see the topics “TIMESTAMP Datatype,” “INTERVAL
YEAR TO MONTH Datatype,” and “INTERVAL DAY TO SECOND Datatype” in the Oracle
SQL Reference.
data type.
• It stores the year, month, and day of the DATE data type
plus hour, minute, and second values as well as the
fractional second value.
• You can optionally specify the time zone.
TIMESTAMP[(fractional_seconds_precision)]
ble
fe r a
ans
TIMESTAMP[(fractional_seconds_precision)]
n - t r
WITH TIME ZONE
a no
h a s
TIMESTAMP[(fractional_seconds_precision)]
m ) deฺ
WITH LOCAL TIME ZONE
i l ฺ c o
G ui
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
( m t o
TIMESTAMP Data Type
N S nse
The TIMESTAMPD A data ltype
i c eis an extension of the DATE data type. It stores the year, month, and
day of the N data type plus hour, minute, and second values. This data type is used for
ADATE
I K
N precise time values.
storing
A
MThe fractional_seconds_precision optionally specifies the number of digits in the
fractional part of the SECOND datetime field and can be a number in the range 0 to 9. The
default is 6.
Example
In this example, a table is created named NEW_EMPLOYEES, with a column START_DATE that
has a data type of TIMESTAMP:
CREATE TABLE new_employees
(employee_id NUMBER,
first_name VARCHAR2(15),
last_name VARCHAR2(15),
...
start_date TIMESTAMP(7),
...);
Suppose that two rows are inserted in the NEW_EMPLOYEES table. The displayed output shows
the differences. (A DATE data type defaults to display the DD-MON-RR format.):
17-JUN-03 12.00.00.000000 AM
21-SEP-03 12.00.00.000000 AM
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
SELECT *
FROM time_example;
ORDER_DATE
----------------------------
15-JAN-04 09.34.28.000000 AM
The TIMESTAMP WITH LOCAL TIME ZONE type is appropriate for two-tier
applications in which you want to display dates and times using the time zone of the client
system.
ble
fe r a
ans
n - t r
o
s an
) ha eฺ
c o m uid
ฺ
ail ent G
m
g tud
t @
ei is S
ov
n i pr se th
( ma to u
N S nse
D A lice
A N
N I K
MA
Including Constraints
Constraint Guidelines
Defining Constraints
• Syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
• Column-level constraint:
column [CONSTRAINT constraint_name] constraint_type,
ble
• Table-level constraint: fe r a
ans
n - t r
column,...
a no
h a s
[CONSTRAINT constraint_name] constraint_type
(column, ...), ) ฺ m uide
ฺ c o
m ail ent G
@ g tud
t
ei isAllSrights reserved.
o v
pr se th
Copyright © 2009, Oracle.
n i
Defining ConstraintsS (
ma to u
N n s e
A syntax
Dthe
The slide gives e
lic for defining constraints when creating a table. You can create the
N
A at either the column level or table level. Constraints defined at the column level are
K
constraints
I
AN when the column is defined. Table-level constraints are defined at the end of the table
included
Mdefinition and must refer to the column or columns on which the constraint pertains in a set of
parentheses.
NOT NULL constraints must be defined at the column level.
Constraints that apply to more than one column must be defined at the table level.
In the syntax:
schema Is the same as the owner’s name
table Is the name of the table
DEFAULT expr Specifies a default value to use if a value is omitted in the
INSERT statement
column Is the name of the column
datatype Is the column’s data type and length
column_constraint Is an integrity constraint as part of the column definition
table_constraint Is an integrity constraint as part of the table definition
Defining Constraints
• Column-level constraint:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
• Table-level constraint:
CREATE TABLE employees(
ble
employee_id NUMBER(6),
fe r a
first_name VARCHAR2(20),
ans
...
n2- t r
job_id VARCHAR2(10) NOT NULL,
a no
has eฺ
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID)); ) m uid
ฺ c o
m ail ent G
@ g tud
t
ei isAllSrights reserved.
o v
pr se th
Copyright © 2009, Oracle.
n i
(ma e to u
Defining ConstraintsS(continued)
A N createde n s
Constraints are
N D usually lic at the same time as the table. Constraints can be added to a table
I K
after its A
creation and also temporarily disabled.
AN slide examples create a primary key constraint on the EMPLOYEE_ID column of the
Both
MEMPLOYEES table.
1. The first example uses the column-level syntax to define the constraint.
2. The second example uses the table-level syntax to define the constraint.
More details about the primary key constraint are provided later in this lesson.
Ensures that null values are not permitted for the column:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
…
NOT NULL constraint Absence of NOT NULL ble
(No row can contain
NOT NULL
constraint constraint fe r a
a null value for (Any row can containans
this column.) n - t r
a null value for this
column.)
a no
h a s
m ) deฺ
i l ฺ c o
G ui
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
( m t o
NOT NULL Constraint
N S nse
The NOT NULLD Aconstraint
l i c eensures that the column contains no null values. Columns without
the NOT N constraint can contain null values by default. NOT NULL constraints must be
ANULL
I K
N at the column level.
MA
defined
UNIQUE Constraint
UNIQUE constraint
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
EMPLOYEES
…
INSERT INTO
ble
Allowed
fe r a
ans
Not allowed:
already exists n - t r
a no
h a s
m ) deฺ
i l ฺ c o
G ui
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
UNIQUE Constraint S ( m t o
N n s e
A UNIQUE key DA e
licconstraint requires that every value in a column or set of columns (key)
integrity
N
A is, no two rows of a table can have duplicate values in a specified column or set
N I K
be unique—that
Acolumns.
of
Mconstraint
The column (or set of columns) included in the definition of the UNIQUE key
is called the unique key. If the UNIQUE constraint comprises more than one column,
that group of columns is called a composite unique key.
UNIQUE constraints enable the input of nulls unless you also define NOT NULL constraints for
the same columns. In fact, any number of rows can include nulls for columns without 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 a UNIQUE constraint.
Note: Because of the search mechanism for 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.
UNIQUE Constraint
DEPARTMENTS
PRIMARY KEY
… e
Not allowed r a bl
INSERT INTO
s fe
(null value)
- t r an
n no
s a
h a
) deฺ
c o m ui
Not allowed
i l ฺ G
(50 already exists)
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
( m t o
PRIMARY KEY Constraint
N S nse
A PRIMARY D A constraint
KEY l i c e creates a primary key for the table. Only one primary key can be
I AN
createdKfor each table. The PRIMARY KEY constraint is a column or set of columns that
AN identifies each row in a table. This constraint enforces uniqueness of the column or
uniquely
Mcolumn combination 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.
PRIMARY
KEY
…
EMPLOYEES
FOREIGN
KEY
ble
fe r a
ans
n - t r
… n o
INSERT INTO
s a
Not allowed
a not
(9 does
) hexist)
o m uideฺ
ฺ c
m ail ent GAllowed
@ g tud
t
ei isAllSrights reserved.
o v
pr se th
Copyright © 2009, Oracle.
n i
( ma to u
FOREIGN KEY Constraint
N S nse
The FOREIGN D KEY e
A (orlireferential
c integrity) constraint designates a column or combination of
N
Aas a foreign key and establishes a relationship between a primary key or a unique key in
columns
theN
I K
MInAthe example in the slide, DEPARTMENT_ID has been defined as the foreign key in the
same table or a different table.
table-constraint level
• REFERENCES: Identifies the table and column in the parent
table
• ON DELETE CASCADE: Deletes the dependent rows in the
child table when a row in the parent table is deleted
• ON DELETE SET NULL: Converts dependent foreign key
values to null ble
fe r a
ans
n - t r
a no
h a s
m ) deฺ
i l ฺ c o
G ui
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
( m t o
FOREIGN KEY Constraint:
N S nKeywords
s e
DAis defined
The foreign key e
lic in the child table, and the table containing the referenced column is
N
Atable. The foreign key is defined using a combination of the following keywords:
I K
the parent
• NFOREIGN KEY is used to define the column in the child table at the table-constraint level.
MA• REFERENCES identifies the table and column in the parent table.
• ON DELETE CASCADE indicates that when the row in the parent table is deleted, the
dependent rows in the child table are also deleted.
• ON DELETE SET NULL converts foreign key values to null when the parent value is
removed.
The default behavior is called the restrict rule, which disallows the update or deletion of
referenced data.
Without the ON DELETE CASCADE or the ON DELETE SET NULL options, the row in the
parent table cannot be deleted if it is referenced in the child table.
CHECK Constraint
, 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) ble
CONSTRAINT emp_job_nn NOT NULL
fe r a
, salary NUMBER(8,2)
t r a ns
CONSTRAINT emp_salary_ck n -
CHECK (salary>0)
o
, commission_pct NUMBER(2,2)
s an
, manager_id NUMBER(6)
, department_id NUMBER(4) ) ha eฺ
c o m REFERENCES
uid
CONSTRAINT emp_dept_fk
i l ฺ G
departments (department_id));
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
( m t o
S nse
CREATE TABLE: Example
N
The example Dshows e
A thelistatement
c used to create the EMPLOYEES table in the HR schema.
A N
N I K
MA
Violating Constraints
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
UPDATE employees
SET department_id = 55
WHERE department_id = 110;
ble
fe r a
ans
n - t r
a no
h a s
m ) deฺ
Department 55 does not exist.
i l ฺ c o
G ui
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
Integrity Constraint S ( m t o
N
Error
n s e
When you have DA e
lic in place on columns, an error is returned to you if you try to violate
constraints
N
A rule.
K
the constraint
I
ANexample, if you attempt to update a record with a value that is tied to an integrity constraint,
MFor
an error is returned.
In the example in the slide, department 55 does not exist in the parent table, DEPARTMENTS,
and so you receive the parent key violation ORA-02291.
Violating Constraints
ble
fe r a
ans
n - t r
a no
h a s
m ) deฺ
i l ฺ c o
G ui
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
Integrity Constraint S ( m t o
N n s e
Error (continued)
e
If you attemptDtoAdeleteliacrecord with a value that is tied to an integrity constraint, an error is
K
returned.
I AN
ANexample in the slide tries to delete department 60 from the DEPARTMENTS table, but it
The
Mresults 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.
The following statement works because there are no employees in department 70:
DELETE FROM departments
WHERE department_id = 70;
1 row deleted.
Creating a Table
by Using a Subquery
• Create a table and insert rows by combining the CREATE
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Creating a Table
by Using a Subquery
CREATE TABLE dept80
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
AS
SELECT employee_id, last_name,
salary*12 ANNSAL,
hire_date
FROM employees
WHERE department_id = 80;
CREATE TABLE Succeeded.
ble
fe r a
ans
n - t r
a no
h a s
m ) deฺ
i l ฺ c o
G ui
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
( m t o
ALTER TABLE Statement
N S nse
D
After you create e may need to change the table structure for any of the following
Aa table,licyou
K
reasons:
I AN
• NYou omitted a column.
MA• Your column definition needs to be changed.
• You need to remove columns.
You can do this by using the ALTER TABLE statement. For information about the
ALTER TABLE statement, see the Oracle Database 10g SQL Fundamentals II course.
Dropping a Table
Summary
Practice 9: Overview
ble
fe r a
ans
n - t r
a no
h a s
m ) deฺ
i l ฺ c o
G ui
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
Practice 9: OverviewS ( m t o
N n s e
DA by using
Create new tables e
lic the CREATE TABLE statement. Confirm that the new table is added
N
A Create the syntax in the command file, and then execute the command file to
I K
to the database.
N the table.
MA
create
Practice 9
1. Create the DEPT table based on the following table instance chart. Place the
syntax in a script called lab_09_01.sql, and then execute the statement in the script to
create the table. Confirm that the table is created.
Column Name ID NAME
Primary key
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Key Type
Nulls/Unique
FK Table
FK Column
Data type NUMBER VARCHAR2
Length 7 25
ble
fe r a
ans
n - t r
a no
h a s
m ) deฺ
2. Populate the DEPT table with data from the DEPARTMENTS
i l ฺ c o
G ui Include only columns
table.
that you need.
g ma dent
i t@ table
3. Create the EMP table based on the following
e S tuinstance chart. Place the syntax in
a script called lab_09_03.sql,
i p rovandethen
t hisexecute the statement in the script to create the
a n is created.
table. Confirm that the table us
Column Name SID ( m t o
N n s e LAST_NAME FIRST_NAME DEPT_ID
D
Key Type A lice
I K AN
Nulls/Unique
N
MA FK Table DEPT
FK Column ID
Data type NUMBER VARCHAR2 VARCHAR2 NUMBER
Length 7 25 25 7
Practice 9 (continued)
4. Create the EMPLOYEES2 table based on the structure of the EMPLOYEES table. Include
only the EMPLOYEE_ID, FIRST_NAME, LAST_NAME, SALARY, and DEPARTMENT_ID
columns. Name the columns in your new table ID, FIRST_NAME, LAST_NAME, SALARY,
and DEPT_ID, respectively.
5. Drop the EMP table.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
ble
fe r a
ans
n - t r
o
s an
) ha eฺ
c o m uid
ฺ
ail ent G
m
g tud
t @
ei is S
ov
n i pr se th
( ma to u
N S nse
D A lice
AN
N I K
MA
ble
fe r a
ans
n - t r
o
s an
) ha eฺ
c o m uid
ฺ
ail ent G
m
g tud
t @
ei is S
ov
n i pr se th
( ma to u
N S nse
D A lice
AN
N I K
MA