Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 44

Chapter 3:

Table Creation and Management:


Creating and Modifying
Database Tables
Jason C. H. Chen, Ph.D.
Professor of MIS
School of Business Administration
Gonzaga University
Spokane, WA 99258
chen@jepson.gonzaga.edu
Dr. Chen, Oracle Database System (Oracle)

Objectives
Become acquainted with Structured Query Language
(SQL)
Identify the table name and structure
Create a new table using the CREATE TABLE command
Use a subquery to create a new table
Add a column to an existing table
Modify the definition of a column in an existing table
Delete a column from an existing table
Mark a column as unused and then delete it at a later time
Rename a table
Truncate a table
Drop a table
Dr. Chen, Oracle Database System (Oracle)

Database Objects and Queries


An Oracle database consists of multiple user accounts
Each user account owns database objects

Tables
Views
Stored programs, etc.

Query: command to perform operation on database


object
Structured Query Language (SQL)
Industry standard query language for most of relational
databases
Consists of about 30 commands

Dr. Chen, Oracle Database System (Oracle)

Basic SQL Concepts and Commands


SQL (Structured Query Language) is used to
manipulate the database.

There are two basic types of SQL commands:


Data Definition Language (DDL)

Data Manipulation Language (DML)

DDL commands work with the structure of the objects


(tables, indexes, views) in the database.

DML commands work with the data in the database


(i.e.,manipulate the data).
Reserved words - SQL command words
Dr. Chen, Oracle Database System (Oracle)

Security Granting Table Privileges


Security is the prevention of unauthorized access
to the database. Within an organization, the
database administrator determines the types of
access various users need for the database.
Some users might be able to retrieve and update
data in the database. Other users might be able to
retrieve any data from the database but not make
any changes to it. Still other users might be able
to access only a portion of the database.

Dr. Chen, Oracle Database System (Oracle)

Oracle11g User Accounts


User account - identified by a unique username
and password
User schema - all of the objects that the user
creates and stores in the database
Database objects
Also called schema objects
Objects in user schema

Object owner has privileges to perform all


possible actions on an object

Dr. Chen, Oracle Database System (Oracle)

A. Names and Properties


Why need a name?

Dr. Chen, Oracle Database System (Oracle)

Creating a Table

CREATE TABLE tablename


(fieldname1 data_type (size),
fieldname2 data_type (size),
);

Dr. Chen, Oracle Database System (Oracle)

Defining Oracle10g Database Tables

To create a table, you must specify:

Table name
Field names
Field data types
Field sizes

Constraints
restrictions on the data values that a field can store

Dr. Chen, Oracle Database System (Oracle)

I. Names and Properties: Conventions


Series of rules Oracle Corporation established for
naming all database objects

1. From 1 to 30 characters
2. Only alphanumeric characters, and special
characters ($ , _, #)
3. Must begin with a letter and can not contain blank
spaces or hyphens
4. Must be unique and No reserved words are allowed

Dr. Chen, Oracle Database System (Oracle)

Are the following names valid? Why?


customer order
customer-order
#order
Customer_#
Customer#

10

Oracle 11g Data Types


Data type
Specifies kind of data that column stores
Provides means for error checking
Enable DBMS to use storage space more
efficiently by internally storing different types of
data in different ways
Basic types
Character
Number
Date/time
Dr. Chen, Oracle Database System (Oracle)

11

II. Data Types

Built-in
provided by the system

Library

built by the software


vendor or a third party

User-defined

built by users
Dr. Chen, Oracle Database System (Oracle)

12

Basic Built-In Data Types

Character
VARCHAR2
CHAR

Numeric

NUMBER

DATE
OTHERS:
LOB, BLOB, LONG, RAW, LONG RAW

Dr. Chen, Oracle Database System (Oracle)

13

Character Data Types

1. VARCHAR2
Stores variable-length character data up
to a maximum of 4,000 characters
Values in different records can have a
different number of characters
fieldname VARCHAR2(maximum_size)
(e.g.) emp_name VARCHAR2(20);
an instance: Jason Chen

Dr. Chen, Oracle Database System (Oracle)

14

Character Data Types (cont.)


2. CHAR
Fixed-length character data (<= 2000 characters)

default is 1 if no field size is specified


Data values for different records all have the same number
of characters
DBMS adds trailing blank spaces to the end of the entry to
make the entry fill the maximum_size value
Data longer than maximum_size causes an error
[optional]
fieldname CHAR[(maximum_size)]
pros: use data storage space more efficiently and processed
faster
cons: causes inconsistent query results in other Oracle
applications
e.g. s_class CHAR(2);
SR JR SO FR GR
State CHAR(2) DEFAULT WA;
student_gender CHAR;
Dr. Chen, Oracle Database System (Oracle)

15

Character Subtypes
Examples:

VARCHAR2(5)

Smith or Smi

CHAR(5)

Smith or Smi

LONG

Smith...

Note that you do not specify a size for


LONG.
To include a single quote in a literal
character string, use two in a row:
This is Heralds string.
Dr. Chen, Oracle Database System (Oracle)

16

Question: Which query will possibly generate


student information?
s_Last VARCHAR2(15);

s_Last CHAR(15);

SELECT s_Last, s_First,


s_Address
FROM student
WHERE s_Last = Smith;

SELECT s_Last, s_First,


s_Address
FROM student
WHERE s_Last = Smith;

What data type should be used if there is any


chance that all column spaces will NOT be filled?
Answer: VARCHAR2
L
Dr. Chen, Oracle Database System (Oracle)

17

When use Query:


SELECT s_last, s_first, ssn, telephone
FROM student
WHERE s_last = Smith;
Case is sensitive within the single
quotation.
SQL Plus commands are NOT case
sensitive, but Query within the single
quotation are case sensitive.
Dr. Chen, Oracle Database System (Oracle)

18

3. Number Data Types


Stores negative, positive, fixed, and floating point
numbers between
10 -130 <=
<=10 +126
precision up to 38 decimal places
General Syntax:
fieldname NUMBER [([precision,] [scale])]
Integer: fieldname NUMBER(precision)
Fixed point: fieldname
NUMBER[([precision],[scale])]
Floating point: fieldname NUMBER
Dr. Chen, Oracle Database System (Oracle)

19

Number Data Types (examples)


a) Integer: Number (n)
e.g. s_id NUMBER(5)
12345
b) Fixed-point numbers
e.g. current_price NUMBER (5, 2);
259.99
33.89
c) Fixed-point numbers (cont.)
e.g. total_mileage NUMBER (5, 1);
259.9
33.8
d) Floating-point Number with a variable number of
decimal places
e.g. s_gpa NUMBER;

3.89
2.7569
3.2
Dr. Chen, Oracle Database System (Oracle)

20

4. Date and Time Data Types


Date, time data subtypes
Store actual date and time values
DATE
Dates from December 31, 4712 BC to December 31, 4712
AD
Default format DD-MON-YY
Default time format HH:MI:SS A.M.
fieldname DATE
Sample declaration:

OrderDate DATE NOT NULL;

Use one of the following format masks:

Dr. Chen, Oracle Database System (Oracle)

TO_DATE (
TO_DATE (
TO_DATE (

, MM/DD/YY)
, DD-MON-YYYY)
, HH:MI AM)
21

Table Design (continued)

Table 3-2

Oracle 11g Datatypes

Dr. Chen, Oracle Database System (Oracle)

22

Table Creation

Figure 3-1

CREATE TABLE syntax

Defining Columns
Column definition list must be enclosed in
parentheses
Datatype must be specified for each column
Maximum of 1,000 columns
Dr. Chen, Oracle Database System (Oracle)

23

Exercise: Create a new table of acctmanager based on


the following information
acctmanager
Amid

Amfirst

Amlast

AmeDate

Amsal

Amcomm

Region

VARCHAR2(4)

VARCHAR2(12)

VARCHAR2(12)

DATE

NUMBER(8,2)

NUMBER(7,2)

CHAR(2)

CREATE TABLE acctmanager


( amid

Dr. Chen, Oracle Database System (Oracle)

NOT NULL);

GROUP WORK
Complete the
CREATE command
manually!

24

Exercise: Create a new table of acctmanager based on


the following information
acctmanager
Amid

Amfirst

Amlast

AmeDate

Amsal

Amcomm

Region

VARCHAR2(4)

VARCHAR2(12)

VARCHAR2(12)

DATE

NUMBER(8,2)

NUMBER(7,2)

CHAR(2)

CREATE TABLE acctmanager


( amid VARCHAR2(4) PRIMARY KEY,
SELECT *
amfirst VARCHAR2(12) NOT NULL,
FROM acctmanager;
amlast VARCHAR2(12) NOT NULL,
amedate DATE DEFAULT SYSDATE,
amsal NUMBER(8,2),
amcomm NUMBER(7,2) DEFAULT 0,
region CHAR(2) NOT NULL);
Dr. Chen, Oracle Database System (Oracle)

25

Refresh the Database


1. Create a new folder on c:\ as follows:
c:\oradata\chapter3
2. Go to Blackboard and download data
files from Oracle chapter3 and save under
c:\oradata\chapter3\
3. Run the following script file
Start c:\oradata\chapter3\JLDB_Build_3.sql

Dr. Chen, Oracle Database System (Oracle)

26

Exercise Your Turn


Type the following commands:
1) SELECT TABLE_NAME FROM USER_TABLES;
2) DROP TABLE ACCTMANAGER CASCADE
CONSTRAINTS;
3) DROP TABLE ACCTMANAGER2 CASCADE
CONSTRAINTS;

4) SELECT TABLE_NAME FROM USER_TABLES;


You now are able to create acctmanager table
Dr. Chen, Oracle Database System (Oracle)

27

CREATE TABLE Command Example


What is the difference
between these two versions:
Virtual Column/
(Derived/computed)
Is this a good approach?

Figure 3-2

The creation of the ACCTMANAGER table

Dr. Chen, Oracle Database System (Oracle)

28

Viewing Table Structures: DESCRIBE


DESCRIBE displays the structure of a specified table

Figure 3-4

The DESCRIBE command

Dr. Chen, Oracle Database System (Oracle)

29

Table Creation through Subqueries


You can use subqueries to retrieve data
from an existing table
Requires use of AS keyword
New column names can be assigned
CREATE TABLEAS

Figure 3-8

CREATE TABLE AS command syntax

Dr. Chen, Oracle Database System (Oracle)

30

CREATE TABLEAS Command


Example

Figure 3-7

Creating a table based on a subquery

SELECT * FROM cust_mkt;


Dr. Chen, Oracle Database System (Oracle)

31

Modifying Existing Tables


Accomplished through the ALTER TABLE
command
Use an ADD clause to add a column
Use a MODIFY clause to change a column
Use a DROP COLUMN to drop a column
ALTER TABLE Command Syntax

Figure 3-10 Arithmetic operations with NULL values


Dr. Chen, Oracle Database System (Oracle)

32

ALTER TABLEADD Command

Figure 3-12 The ALTER TABLE ADD command


Dr. Chen, Oracle Database System (Oracle)

33

ALTER TABLEMODIFY Command

Figure 3-18 The ALTER TABLE MODIFY command to increase the column width
Dr. Chen, Oracle Database System (Oracle)

34

Modification Guidelines
Column must be as wide as the data it
already contains
If a NUMBER column already contains
data, size cannot be decreased
Adding or changing default data does not
affect existing data

Dr. Chen, Oracle Database System (Oracle)

35

ALTER TABLESET UNUSED Command


Once marked for deletion, a column cannot be
restored
Storage space is freed at a later time

36
Dr. Chen, Oracle Database System (Oracle)

36

ALTER TABLEDROP UNUSED Command


Frees up storage space from columns previously
marked as unused

However, once a table is set UNUSED it cant be


DROPPED using the following (regular) command:
ALTER TABLE tablename
DROP COLUMN colname;
Show: test_UNUSED.sql
and test_UNUSED.doc
37
Dr. Chen, Oracle Database System (Oracle)

37

AUTHOR
AuthorID
LName
VARCHAR2(4) VARCHAR2(10)

FName
VARCHAR2(10)

SQL> SELECT * FROM author;


AUTH
---S100
J100
A100
M100
K100
P100
A105
B100
P105
W100
W105

LNAME
---------SMITH
JONES
AUSTIN
MARTINEZ
KZOCHSKY
PORTER
ADAMS
BAKER
PETERSON
WHITE
WHITE

FNAME
---------SAM
JANICE
JAMES
SHEILA
TAMARA
LISA
JUAN
JACK
TINA
WILLIAM
LISA

AUTH
---R100
F100
W110

LNAME
---------ROBINSON
FIELDS
WILKINSON

FNAME
---------ROBERT
OSCAR
ANTHONY

14 rows selected.
Dr. Chen, Oracle Database System (Oracle)

38

AUTHOR
AuthorID
LName
VARCHAR2(4) VARCHAR2(10)

FName
VARCHAR2(10)

SQL> describe author;


Name
Null?
Type
------------ -------- --------------AUTHORID
NOT NULL VARCHAR2(4)
LNAME
VARCHAR2(10)
FNAME
VARCHAR2(10)
SQL>
SQL> ALTER TABLE author SET UNUSED
COLUMN fname;
Table altered.

SQL> describe author;


Name
Null?
Type
----------- -------- ------------AUTHORID
NOT NULL VARCHAR2(4)
LNAME
VARCHAR2(10)
SQL>

Dr. Chen, Oracle Database System (Oracle)

Show: test_UNUSED.sql
and test_UNUSED.doc

SQL> ALTER TABLE author DROP COLUMN


lname;
Table altered.
SQL> ALTER TABLE author DROP COLUMN
fname;
ALTER TABLE author DROP COLUMN fname
*
ERROR at line 1:
ORA-00904: "FNAME": invalid identifier
SQL> ALTER TABLE author
2 DROP UNUSED COLUMNS;
Table altered.
SQL> describe author;
Name
Null?
Type
----------- -------- ------------AUTHORID
NOT NULL VARCHAR2(4)
SQL>

39

AUTHOR
AuthorID
LName
VARCHAR2(4) VARCHAR2(10)

FName
VARCHAR2(10)

SQL> SELECT * FROM author;


AUTH
---A100
A105
B100
F100
J100
K100
M100
P100
P105
R100
S100
AUTH
---W100
W105
W110
14 rows selected.
Dr. Chen, Oracle Database System (Oracle)

40

Practice all the rest of examples in the text.


A Script file is available on the Bb (file
name: Ch3Queries.sql)
After completing all examples, do the HW.

Dr. Chen, Oracle Database System (Oracle)

41

Homework - Hands-On Assignments


Email me with one attachment
(Oracle_ch3_Spool_Lname_Fname.) to:
chen@jepson.gonzaga.edu
with subject title of
bmis441_Oracle_ch3
Read and Practice all examples on Chapters 3
1. Run the script files (in the folder \oradata\chapter3\):
JLDB_Build_3.sql
2. Read Oracle assignment and create a script file
Oracle_ch3_Lname_Fname.sql for questions (#1 to
#8; p.94) on Hands-on Assignments. .
3. Execute and test one problem at a time and make sure
they are all running successfully.
4. When you done, spool the script files (see next slide
for spooling instructions) and email the file
(Oracle_ch3_Spool_Lname_Fname.txt) to me by the
midnight before the next class. Turn in a hardcopy to me
in the class.
Dr. Chen, Oracle Database System (Oracle)

42

How to Spool your Script and Output Files


After you tested the script file of Oracle_ch3_Lname_Fname.sql successfully,
follow the instructions below to spool both script and output files:
Step 0. Run the following script file from SQL*Plus (since you have created
JLDB tables)
Start c:\oradata\chapter3J\LDB_Build_3.sql

1. type the following on SQL>


Spool c:\oradata\Oracle_ch3_Spool_Lname_Fname.txt (make sure your name is entered)

2. open Oracle_ch3_Lname_Fname.sql that you already tested


3. copy and paste all the SQL commands (including all comments) to the
SQL*PLUS
4. type Spool Off on the SQL>
The output should contain your personal information, all SQL commands and
their solution on the .txt file and saved in C: drive (oradata\ folder)
Email me with the spooled file (.txt) with attachment to:
chen@jepson.gonzaga.edu
with subject title of
bmis441_Oracle_ch3
Dr. Chen, Oracle Database System (Oracle)

43

End of chapter 3

Dr. Chen, Oracle Database System (Oracle)

44

You might also like