Using DDL Statements to Create and Manage Tables: license to use this Student Guideฺ

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

SQL Star International Limited

Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Using DDL Statements


to Create and Manage Tables

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

After completing this lesson, you should be able to do the


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

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.

Oracle Database 10g: SQL Fundamentals I 9 - 2


SQL Star International Limited

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.

Oracle Database 10g: SQL Fundamentals I 9 - 3


SQL Star International Limited

Naming Rules

Table names and column names:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

• Must begin with a letter


• Must be 1–30 characters long
• Must contain only A–Z, a–z, 0–9, _, $, and #
• Must not duplicate the name of another object owned by
the same user
• Must not be an Oracle server–reserved word e
r a bl
s fe
- t r an
n no
s a
h a
) deฺ
c o m ui
i l ฺ G
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
( m t o
Naming Rules
N S nse
D A tables
You name database l i c eand columns according to the standard rules for naming any Oracle
N
Aobject:
I K
Database
• NTable names and column names must begin with a letter and be 1–30 characters long.
MA • Names must contain only the characters A–Z, a–z, 0–9, _ (underscore), $, and # (legal
characters, but their use is discouraged).
• Names must not duplicate the name of another object owned by the same Oracle server
user.
• Names must not be an Oracle server–reserved word.
Naming Guidelines
Use descriptive names for tables and other database objects.
Note: Names are case-insensitive. For example, EMPLOYEES is treated as the same name as
eMPloyees or eMpLOYEES.
For more information, see “Object Names and Qualifiers” in the Oracle Database SQL
Reference.

Oracle Database 10g: SQL Fundamentals I 9 - 4


SQL Star International Limited

CREATE TABLE Statement

• You must have:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

– The CREATE TABLE privilege


– A storage area
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr][, ...]);

• You specify the:


– Table name
ble
– Column name, column data type, and column size
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
CREATE TABLE Statement
N S nse
D Ato store
You create tables l i c e by executing the SQL CREATE TABLE statement. This
data
K
statement
I AisNone of the DDL statements, which are a subset of SQL statements used to create,
N or remove Oracle Database structures. These statements have an immediate effect on
MA
modify,
the database, and they also record information in the data dictionary.
To create a table, a user must have the CREATE TABLE privilege and a storage area in which to
create objects. The database administrator uses data control language statements to grant
privileges to users (DCL statements are covered in a later lesson).
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 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

Oracle Database 10g: SQL Fundamentals I 9 - 5


SQL Star International Limited

Referencing Another User’s Tables

• Tables belonging to other users are not in the user’s


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

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;

Oracle Database 10g: SQL Fundamentals I 9 - 6


SQL Star International Limited

DEFAULT Option

• Specify a default value for a column during an insert.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

... hire_date DATE DEFAULT SYSDATE, ...

• Literal values, expressions, or SQL functions are legal


values.
• Another column’s name or a pseudocolumn are illegal
values.
ble
• The default data type must match the column data type.
fe r a
ans
CREATE TABLE hire_dates
n - t r
o
an
(id NUMBER(8),
hire_date DATE DEFAULT SYSDATE);
h a s
) ฺ
ide
CREATE TABLE succeeded.
c o m u

ail ent G
m
g tud
t @
ei isAllSrights reserved.
o v
pr se th
Copyright © 2009, Oracle.
n i
( ma to u
DEFAULT Option
N S nse
D
When you define Aa table,
l i c e can specify that a column be given a default value by using the
you
DEFAULT
I K ANoption. This option prevents null values from entering the columns if a row is
AN without a value for the column. The default value can be a literal, an expression, or a
inserted
MSQL function (such as SYSDATE or USER), but the value cannot be the name of another column
or a pseudocolumn (such as NEXTVAL or CURRVAL). The default expression must match the
data type of the column.
Note: CURRVAL and NEXTVAL are explained later in this lesson.

Oracle Database 10g: SQL Fundamentals I 9 - 7


SQL Star International Limited

Creating Tables

• Create the table.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

CREATE TABLE dept


(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13),
create_date DATE DEFAULT SYSDATE);
CREATE TABLE succeeded.

• Confirm table creation.


ble
DESCRIBE dept
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
Creating Tables
N S nse
The example D in A
the slide
l i c e the DEPT table, with four columns: DEPTNO, DNAME, LOC,
creates
I K AN
and CREATE_DATE. The CREATE_DATE column has a default value. If a value is not provided
forN
MItAfurther confirms the creation of the table by issuing the DESCRIBE command.
an INSERT statement, the system date is automatically inserted.

Because creating a table is a DDL statement, an automatic commit takes place when this
statement is executed.

Oracle Database 10g: SQL Fundamentals I 9 - 8


SQL Star International Limited

Data Types

Data Type Description


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

VARCHAR2(size) Variable-length character data


CHAR(size) Fixed-length character data
NUMBER(p,s) Variable-length numeric data
DATE Date and time values
LONG Variable-length character data (up to 2 GB)
CLOB Character data (up to 4 GB)
ble
RAW and LONG Raw binary data
fe r a
RAW
an s
n - t r
BLOB Binary data (up to 4 GB)
n o
BFILE Binary data stored in an external file (up to a
s 4 GB)
h a ฺ
) thedeunique
ROWID A base-64 number system representing
o m i
address of a row in its table
a ilฺc nt Gu
@ gm tude
v e it s S
i p ro e Oracle.
Copyright © 2009,
t hi All rights reserved.
a n us
( m t o
Data Types
N S nse
D
When you identifyA a column
l i c e for a table, you need to provide a data type for the column. There
K AN
are several
I data types available:
N
MAData Type Description
VARCHAR2(size) Variable-length character data (A maximum size must be
specified: minimum size is 1; maximum size is 4,000.)
CHAR [(size)] Fixed-length character data of length size bytes (Default and
minimum size is 1; maximum size is 2,000.)
NUMBER [(p,s)] Number having precision p and scale s (The precision is the
total number of decimal digits, and the scale is the number of
digits to the right of the decimal point; the precision can range
from 1 to 38, and the scale can range from –84 to 127.)
DATE Date and time values to the nearest second between January 1,
4712 B.C., and December 31, 9999 A.D.
LONG Variable-length character data (up to 2 GB)

CLOB Character data (up to 4 GB)

Oracle Database 10g: SQL Fundamentals I 9 - 9


SQL Star International Limited

Data Types (continued)


D ata T ype D escription
RAW(size) R aw binary data of length size (A m axim um size m ust be specified:
m axim um size is 2,000.)
LONG RAW R aw binary data of variable length (up to 2 G B )
BLOB B inary data (up to 4 G B )
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

BFILE B inary data stored in an external file (up to 4 G B )

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

Oracle Database 10g: SQL Fundamentals I 9 - 10


SQL Star International Limited

Datetime Data Types

You can use several datetime data types:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Data Type Description


TIMESTAMP Date with fractional seconds
INTERVAL YEAR TO Stored as an interval of years
MONTH and months
INTERVAL DAY TO Stored as an interval of days, hours, minutes,
SECOND and seconds
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
Other Datetime DataS ( m
Types e t o
A N e n s
ND
Data Type lic Description
IK A
A N
TIMESTAMP Enables the time to be stored as a date with fractional seconds. There
M are several variations of this data type.
INTERVAL YEAR TO Enables time to be stored as an interval of years and months. Used to
MONTH represent the difference between two datetime values in which the only
significant portions are the year and month.
INTERVAL DAY TO Enables time to be stored as an interval of days, hours, minutes, and
SECOND seconds. Used to represent the precise difference between two datetime
values.

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.

Oracle Database 10g: SQL Fundamentals I 9 - 11


SQL Star International Limited

Datetime Data Types

• The TIMESTAMP data type is an extension of the DATE


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

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.):

Oracle Database 10g: SQL Fundamentals I 9 - 12


SQL Star International Limited

TIMESTAMP Data Type (continued)


SELECT start_date
FROM new_employees;

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ฺ

TIMESTAMP WITH TIME ZONE Data Type


TIMESTAMP WITH TIME ZONE is a variant of TIMESTAMP that includes a time-zone
displacement in its value. The time-zone displacement is the difference (in hours and
minutes) between local time and UTC (Universal Time Coordinate, formerly known as
Greenwich Mean Time). This data type is used for collecting and evaluating date
information across geographic regions.
For example,
TIMESTAMP '2003-04-15 8:00:00 -8:00'
is the same as ble
TIMESTAMP '2003-04-15 11:00:00 -5:00' fe r a
ns
tra Time.
That is, 8:00 a.m. Pacific Standard Time is the same as 11:00 a.m. Eastern Standard
n -
This can also be specified as follows: no a
TIMESTAMP '2003-04-15 8:00:00 US/Pacific'
a s
TIMESTAMP WITH LOCAL TIME ZONE Data Type om
) h deฺ
i l ฺ c G ui
TIMESTAMP WITH LOCAL TIME ZONE is another
m a variant e n t of TIMESTAMP that
includes a time-zone displacement in its value. @ g udfrom TIMESTAMP WITH TIME
It differs
t
i t S
ZONE in that data stored in the database
r ove is normalized
t h is to the database time zone, and the
ip asspart
time-zone displacement is notnstored
a e of the column data. When users retrieve the
(m
data, it is returned in the u
to session time zone. The time-zone displacement is the
users' local
S e
ns between local time and UTC.
N andceminutes)
difference (in hours
A liWITH TIME ZONE, you can specify columns of type TIMESTAMP
ND
Unlike TIMESTAMP
A
WITH
N IKLOCAL TIME ZONE as part of a primary or unique key, as in the following example:
MA
CREATE TABLE time_example
(order_date TIMESTAMP WITH LOCAL TIME ZONE);

INSERT INTO time_example VALUES('15-JAN-04 09:34:28 AM');

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.

Oracle Database 10g: SQL Fundamentals I 9 - 13


SQL Star International Limited

Datetime Data Types

• The INTERVAL YEAR TO MONTH data type stores a


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

period of time using the YEAR and MONTH datetime fields:

INTERVAL YEAR [(year_precision)] TO MONTH

• The INTERVAL DAY TO SECOND data type stores a


period of time in terms of days, hours, minutes, and
seconds:
ble
INTERVAL DAY [(day_precision)]
fe r a
TO SECOND [(fractional_seconds_precision)]
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
(
INTERVAL YEAR TOSMONTH Data
m t o
N n s e Type
INTERVAL D A TOlicMONTH
YEAR e stores a period of time using the YEAR and MONTH datetime
fields. KAN
I
NINTERVAL
A
Use YEAR TO MONTH to represent the difference between two datetime values,
Mwhere the only significant portions are the year and month. For example, you might use this
value to set a reminder for a date that is 120 months in the future, or check whether 6 months
have elapsed since a particular date.
In the syntax:
year_precision is the number of digits in the YEAR datetime field.
The default value of year_precision is 2.
Examples
• INTERVAL '123-2' YEAR(3) TO MONTH
Indicates an interval of 123 years, 2 months
• INTERVAL '123' YEAR(3)
Indicates an interval of 123 years 0 months
• INTERVAL '300' MONTH(3)
Indicates an interval of 300 months
• INTERVAL '123' YEAR
Returns an error because the default precision is 2, and 123 has 3 digits

Oracle Database 10g: SQL Fundamentals I 9 - 14


SQL Star International Limited

INTERVAL YEAR TO MONTH Data Type (continued)


CREATE TABLE time_example2
(loan_duration INTERVAL YEAR (3) TO MONTH);

INSERT INTO time_example2 (loan_duration)


VALUES (INTERVAL '120' MONTH(3));
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

SELECT TO_CHAR(sysdate+loan_duration, 'dd-mon-yyyy')


FROM time_example2; --today’s date is 11-11-2008

INTERVAL DAY TO SECOND Data Type


INTERVAL DAY TO SECOND stores a period of time in terms of days, hours, minutes, and
seconds. a b le
Use INTERVAL DAY TO SECOND to represent the precise difference between two n s fer
datetime
values. For example, you might use this value to set a reminder for a time that is -
36 a in the
trhours
future, or to record the time between the start and end of a race. To represent
n
nolong spans of time,
a
s for the days portion.
including multiple years, with high precision, you can use a large value
h
) deฺa
In the syntax:
c o m i
udigits
day_precision Is a ilฺnumber
the
n t G
of in the DAY datetime
m de values are 0 to 9. The default
g field.tuAccepted
t @
ei isisS2.
ov
fractional_seconds_precision
n i pr se th Is the number of digits in the fractional part of
( ma to u the SECOND datetime field. Accepted values

N S nse are 0 to 9. The default is 6.


Examples DA lic e

K AN
INTERVAL '4 5:12:10.222' DAY TO SECOND(3)
I
NIndicates 4 days, 5 hours, 12 minutes, 10 seconds, and 222 thousandths of a second.
MA• INTERVAL '180' DAY(3)
Indicates 180 days.
• INTERVAL '4 5:12:10.222' DAY TO SECOND(3)
Indicates 4 days, 5 hours, 12 minutes, 10 seconds, and 222 thousandths of a second
• INTERVAL '4 5:12' DAY TO MINUTE
Indicates 4 days, 5 hours, and 12 minutes
• INTERVAL '400 5' DAY(3) TO HOUR
Indicates 400 days and 5 hours.
• INTERVAL '11:12:10.2222222' HOUR TO SECOND(7)
Indicates 11 hours, 12 minutes, and 10.2222222 seconds.

Oracle Database 10g: SQL Fundamentals I 9 - 15


SQL Star International Limited

INTERVAL DAY TO SECOND Data Type (continued)


Example
CREATE TABLE time_example3
(day_duration INTERVAL DAY (3) TO SECOND);

INSERT INTO time_example3 (day_duration)


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

VALUES (INTERVAL '180' DAY(3));

SELECT sysdate + day_duration "Half Year"


FROM time_example3; --today’s date is 11-11-2008

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

Oracle Database 10g: SQL Fundamentals I 9 - 16


SQL Star International Limited

Including Constraints

• Constraints enforce rules at the table level.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

• Constraints prevent the deletion of a table if there are


dependencies.
• The following constraint types are valid:
– NOT NULL
– UNIQUE
– PRIMARY KEY
– ble
FOREIGN KEY
fe r a
– CHECK
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
Constraints
N S nse
D
The Oracle server i e
A uses lconstraints
c to prevent invalid data entry into tables.
N
Ause constraints to do the following:
I K
You can
N
MA• Enforce rules on the data in a table whenever a row is inserted, updated, or deleted from that
table. The constraint must be satisfied for the operation to succeed.
• Prevent the deletion of a table if there are dependencies from other tables
• Provide rules for Oracle tools, such as Oracle Developer
Data Integrity Constraints
Constraint Description
NOT NULL Specifies that the column cannot contain a null value

UNIQUE Specifies a column or combination of columns whose values


must be unique for all rows in the table
PRIMARY KEY Uniquely identifies each row of the table
FOREIGN KEY Establishes and enforces a foreign key relationship between the
column and a column of the referenced table
CHECK Specifies a condition that must be true

Oracle Database 10g: SQL Fundamentals I 9 - 17


SQL Star International Limited

Constraint Guidelines

• You can name a constraint, or the Oracle server generates


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

a name with the SYS_Cn format.


• Create a constraint at either of the following times:
– At the same time as the table is created
– After the table has been created
• Define a constraint at the column or table level.
• View a constraint in the data dictionary.
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
Constraint Guidelines
N S nse
A stored
All constraintsDare l i cinethe data dictionary. Constraints are easy to reference if you give
I AN
them aKmeaningful name. Constraint names must follow the standard object-naming rules. If you
AN
do not name your constraint, the Oracle server generates a name with the format SYS_Cn,
Mwhere n is an integer so that the constraint name is unique.
Constraints can be defined at the time of table creation or after the table has been created.
For more information, see “Constraints” in Oracle Database SQL Reference.

Oracle Database 10g: SQL Fundamentals I 9 - 18


SQL Star International Limited

Defining Constraints

• Syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

CREATE TABLE [schema.]table


(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);

• 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

Oracle Database 10g: SQL Fundamentals I 9 - 19


SQL Star International Limited

Defining Constraints

• Column-level constraint:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

CREATE TABLE employees(


employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY, 1
first_name VARCHAR2(20),
...);

• 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.

Oracle Database 10g: SQL Fundamentals I 9 - 20


SQL Star International Limited

NOT NULL Constraint

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

Oracle Database 10g: SQL Fundamentals I 9 - 21


SQL Star International Limited

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.

Oracle Database 10g: SQL Fundamentals I 9 - 22


SQL Star International Limited

UNIQUE Constraint

Defined at either the table level or the column level:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

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),
ble
hire_date DATE NOT NULL,
fe r a
...
ans
CONSTRAINT emp_email_uk UNIQUE(email));
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
S nse
UNIQUE Constraint (continued)
N
D A canlicbeedefined at the column level or table level. A composite unique key is
UNIQUE constraints
I AN
createdKby using the table-level definition.
ANexample in the slide applies the UNIQUE constraint to the EMAIL column of the
MThe
EMPLOYEES table. The name of the constraint is EMP_EMAIL_UK.
Note: The Oracle server enforces the UNIQUE constraint by implicitly creating a unique index
on the unique key column or columns.

Oracle Database 10g: SQL Fundamentals I 9 - 23


SQL Star International Limited

PRIMARY KEY Constraint


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

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.

Oracle Database 10g: SQL Fundamentals I 9 - 24


SQL Star International Limited

FOREIGN KEY Constraint


DEPARTMENTS
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

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.

EMPLOYEES table (dependent or child table); it references the DEPARTMENT_ID column of


the DEPARTMENTS table (the referenced or parent table).
Guidelines
• 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.

Oracle Database 10g: SQL Fundamentals I 9 - 25


SQL Star International Limited

FOREIGN KEY Constraint

Defined at either the table level or the column level:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

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, ble
... fe r a
ans
department_id NUMBER(4),
CONSTRAINT emp_dept_fk FOREIGN KEY (department_id) n - t r
REFERENCES departments(department_id), a no
CONSTRAINT emp_email_uk UNIQUE(email));
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
N S (continued)
FOREIGN KEY Constraint
n s e
FOREIGN KEY DA e
lic can be defined at the column or table constraint level. A composite
constraints
N
A must be created by using the table-level definition.
foreignKkey
I
ANexample in the slide defines a FOREIGN KEY constraint on the DEPARTMENT_ID column
MThe
of the EMPLOYEES table, using table-level syntax. The name of the constraint is
EMP_DEPTID_FK.
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. For
example:
CREATE TABLE employees
(...
department_id NUMBER(4) CONSTRAINT emp_deptid_fk
REFERENCES departments(department_id),
...
)

Oracle Database 10g: SQL Fundamentals I 9 - 26


SQL Star International Limited

FOREIGN KEY Constraint:


Keywords
• FOREIGN KEY: Defines the column in the child table at the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

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.

Oracle Database 10g: SQL Fundamentals I 9 - 27


SQL Star International Limited

CHECK Constraint

• Defines a condition that each row must satisfy


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

• The following expressions are not allowed:


– References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM
pseudocolumns
– Calls to SYSDATE, UID, USER, and USERENV functions
– Queries that refer to other values in other rows
..., salary NUMBER(2)
ble
CONSTRAINT emp_salary_min
fe r a
CHECK (salary > 0),...
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
CHECK Constraint S ( m t o
N n s e
DA ldefines
The CHECK constraint e
ic a condition that each row must satisfy. The condition can use the
N
A as query conditions, with the following exceptions:
I K
same constructs
• NReferences to the CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns
MA • Calls to SYSDATE, UID, USER, and USERENV functions
• Queries that refer to other values in other rows
A single column can have multiple CHECK constraints that refer to the column in its definition.
There is no limit to the number of CHECK constraints that you can define on a column.
CHECK constraints can be defined at the column level or table level.
CREATE TABLE employees
(...
salary NUMBER(8,2) CONSTRAINT emp_salary_min
CHECK (salary > 0),
...

Oracle Database 10g: SQL Fundamentals I 9 - 28


SQL Star International Limited

CREATE TABLE: Example


CREATE TABLE employees
( employee_id NUMBER(6)
CONSTRAINT emp_employee_id PRIMARY KEY
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

, 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

Oracle Database 10g: SQL Fundamentals I 9 - 29


SQL Star International Limited

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.

Oracle Database 10g: SQL Fundamentals I 9 - 30


SQL Star International Limited

Violating Constraints

You cannot delete a row that contains a primary key that is


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

used as a foreign key in another table.

DELETE FROM departments


WHERE department_id = 60;

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.

Oracle Database 10g: SQL Fundamentals I 9 - 31


SQL Star International Limited

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ฺ

TABLE statement and the AS subquery option.


CREATE TABLE table
[(column, column...)]
AS subquery;

• Match the number of specified columns to the number of


subquery columns.
a b le
• Define columns with column names and
s f er
default values. ran n -t
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
Creating a Table from
N S Rows n s e Another Table
in
A second method D l i e a table is to apply the AS subquery clause, which both creates
Afor creating
c
K
the table
I AandNinserts rows returned from the subquery.
N syntax:
Athe
MIn
table is the name of the table
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
Guidelines
• 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.
• 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. The other constraint rules are not passed to the new table. However, you can add
constraints in the column definition.
Oracle Database 10g: SQL Fundamentals I 9 - 32
SQL Star International Limited

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.

DESCRIBE dept80 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
Creating a Table from
N S Rows n s e Another Table (continued)
in
D A creates
The slide example l i c ea table named DEPT80, which contains details of all the employees
workingK inN
A department 80. Notice that the data for the DEPT80 table comes from the
I
AN
EMPLOYEES
MYou
table.
can verify the existence of a database table and check column definitions by using the
DESCRIBE command.
Be sure to provide a column alias when selecting an expression. The expression SALARY*12 is
given the alias ANNSAL. Without the alias, the following error is generated:

Oracle Database 10g: SQL Fundamentals I 9 - 33


SQL Star International Limited

ALTER TABLE Statement

Use the ALTER TABLE statement to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

• Add a new column


• Modify an existing column
• Define a default value for the new column
• Drop a column

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.

Oracle Database 10g: SQL Fundamentals I 9 - 34


SQL Star International Limited

Dropping a Table

• All data and structure in the table are deleted.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

• Any pending transactions are committed.


• All indexes are dropped.
• All constraints are dropped.
• You cannot roll back the DROP TABLE statement.

DROP TABLE dept80;


DROP 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
Dropping a Table S ( m t o
N n s e
DA statement
The DROP TABLE e
lic removes the definition of an Oracle table. When you drop a table,
N
A loses all the data in the table and all the indexes associated with it.
K
the database
I
AN
MSyntax
DROP TABLE table
In the syntax, table is the name of the table.
Guidelines
• All data is deleted from the table.
• Any views and synonyms remain but are invalid.
• Any pending transactions are committed.
• Only the creator of the table or a user with the DROP ANY TABLE privilege can remove a
table.
Note: The DROP TABLE statement, once executed, is irreversible. The Oracle server does not
question the action when you issue the DROP TABLE statement. If you own that table or have a
high-level privilege, then the table is immediately removed. As with all DDL statements, DROP
TABLE is committed automatically.

Oracle Database 10g: SQL Fundamentals I 9 - 35


SQL Star International Limited

Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

• Use the CREATE TABLE statement to create a table and


include constraints
• Categorize the main database objects
• Review the table structure
• List the data types that are available for columns
• Create a simple table
a b le
• Explain how constraints are created at the time of table
s f er
creation
- t r an
• Describe how schema objects work n on
a s
h a
) deฺ
c o m ui
i l ฺ G
g ma dent
e i t@ Stu
ro©v2009,e Oracle.
Copyright
i p t hisAll rights reserved.
a n us
( m t o
Summary
N S nse
In this lesson,D A should
you l i c e learned how to do the following:
have
N
ATABLE
CREATEI K
NUse the CREATE TABLE statement to create a table and include constraints.
MA•• Create a table based on another table by using a subquery.
DROP TABLE
• Remove rows and a table structure.
• Once executed, this statement cannot be rolled back.

Oracle Database 10g: SQL Fundamentals I 9 - 36


SQL Star International Limited

Practice 9: Overview

This practice covers the following topics:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

• Creating new tables


• Creating a new table by using the CREATE TABLE AS
syntax
• Verifying that tables exist
• Dropping tables

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

Oracle Database 10g: SQL Fundamentals I 9 - 37


SQL Star International Limited

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

Oracle Database 10g: SQL Fundamentals I 9 - 38


SQL Star International Limited

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

Oracle Database 10g: SQL Fundamentals I 9 - 39


SQL Star International Limited
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

You might also like