37
Oracle8 - The Complete Reference. Koch & Loney 1 Chapter 17 Creating, Dropping, and Altering Tables and Views Presented by Victor Matos

Oracle8 - The Complete Reference. Koch & Loney1 Chapter 17 Creating, Dropping, and Altering Tables and Views Presented by Victor Matos

  • View
    218

  • Download
    0

Embed Size (px)

Citation preview

Oracle8 - The Complete Reference. Koch & Loney 1

Chapter 17

Creating, Dropping, and

Altering Tables and Views

Presented by Victor Matos

Oracle8 - The Complete Reference. Koch & Loney 2

Goals• Create tables containing integrity rules. • Use different datatypes for the columns of a table.• Populate tables using the “insert into table” command.• Populate tables using the subquery option.• Create/drop views.

Oracle8 - The Complete Reference. Koch & Loney 3

Data Structures in Oracle8

• A database can include one or many:– Table Stores data– View Virtual tables facilitating process– Sequence Automatic serial numbers.– Index Improve performance.– Constraint Define data behavior.

Oracle8 - The Complete Reference. Koch & Loney 4

Tables

• Can be created at any time using SQL-DML.

• Do not need to have a pre-allocated storage.

• Can be modify on real-time.

• All data in a relational database is stored in tables.

Oracle8 - The Complete Reference. Koch & Loney 5

Tables• Each column is given a

– column name, – a datatype (defining characteristics of the data to be entered in the column), and a – width (quantity of space to allocate for data to be entered into the column).

Oracle8 - The Complete Reference. Koch & Loney 6

Tables

• Usually in a relational database, some of the columns in different tables contain the same information. In this way, the tables can refer to one another.

Oracle8 - The Complete Reference. Koch & Loney 7

Create Table Command

• Syntax

create table [schema.]tableName

(column1 datatype [DEFAULT expr]

[column_constraint],

. . .

[table_Constraints] );

Oracle8 - The Complete Reference. Koch & Loney 8

Create Table Command

• The components of the command are:– schema same as the owner’s name.– tableName is the name of the table.– column is the name of the column.– datatype Oracle’s datatype and size.– column_contraint field validation rule.– table_constraint integrity rule on the table.

Oracle8 - The Complete Reference. Koch & Loney 9

Create Table Command

• Example-1: Make the BADWEATHER table.

drop table BADWEATHER/create table BADWEATHER ( CITY VARCHAR2(13) NOT NULL , SAMPLEDATE DATE NOT NULL , NOON NUMBER(4,1), MIDNIGHT NUMBER(4,1), PRECIPITATION NUMBER )/

remove previous table

Oracle8 - The Complete Reference. Koch & Loney 10

Create Table Command

• Example-2: Create an EMPLOYEE table.CREATE TABLE scott.emp (empno NUMBER CONSTRAINT pk_emp PRIMARY KEY, ename VARCHAR2(10) CONSTRAINT nn_ename NOT NULL CONSTRAINT upper_ename CHECK (ename = UPPER(ename)), job VARCHAR2(9), mgr NUMBER CONSTRAINT fk_mgr REFERENCES scott.emp(empno), hiredate DATE DEFAULT SYSDATE, sal NUMBER(10,2) CONSTRAINT ck_sal CHECK (sal > 500), comm NUMBER(9,0) DEFAULT NULL, deptno NUMBER(2) CONSTRAINT nn_deptno NOT NULL CONSTRAINT fk_deptno REFERENCES scott.dept(deptno) ) PCTFREE 5 PCTUSED 75;

Oracle8 - The Complete Reference. Koch & Loney 11

Referencing Another User’s Tables

• Constraints should reference objects in the current database.

• If the referred table does not belong to the user making the constraint, the owner’s name must be used to prefix the table name... references JANE.CUSTOMERS ...

Oracle8 - The Complete Reference. Koch & Loney 12

DEFAULT Option

• Indicates a default value to be used when inserting a record.... OrderDate DATE DEFAULT SysDate ...

• Use only literal values (“...”), numbers, expressions, SQL functions such as USER, or SYSDATE.

Oracle8 - The Complete Reference. Koch & Loney 13

Rules for Naming a Table

• TableName must begin with a letter.

• Up to 30-chars long.

• Alphabetic, digits, #, $, _ symbols are ok.

• Can not duplicate the name of another object already created by the user.

Oracle8 - The Complete Reference. Koch & Loney 14

Oracle DatatypesDatatype Description

Varchar2(size) Variable length string

Char(size) Fixed length string

Number Real & Integer numbers.

Date Calendar & Clock

RAW Variable length binary data.

LONG Variable Length strings up to 2GB

Oracle8 - The Complete Reference. Koch & Loney 15

Deciding on a Proper Width

• A character column that is not wide enough for the data you want to put in it will cause an insert to fail and result in this message

Error...ORA-1401:inserted value too large for column

• Maximum CHAR allocation is 2,000 chars.

• VARCHAR2 can store up to 4,000 chars.

Oracle8 - The Complete Reference. Koch & Loney 16

NUMBER Precision

• Make a NUMBER field wide enough for your actual data, otherwise– Oracle will report an error “value too large”, or– Precision will be lost on some of the least

significant digits.

• Decimals are rounded to the next valid representation.

Oracle8 - The Complete Reference. Koch & Loney 17

Table Constraints

• Enforce maintenance-table behavior. Rules can be checked when a record is– inserted– deleted– updated

• Prevent the removal of referenced tables.

Oracle8 - The Complete Reference. Koch & Loney 18

Table Constraints

Constraint Description

NOT NULL This column must contain data.

UNIQUE Duplicate values are not acceptable.

PRIMARY KEY Column uniquely identifies the row.

FOREIGN KEY Refers to a key-column in anothertable.

CHECK Specifies a validation condition.

Oracle8 - The Complete Reference. Koch & Loney 19

The Candidate Key

• A candidate key is a combination of one or more columns, the values of which make a unique identifier for the row.

drop table BADWEATHER;

create table BADWEATHER ( CITY VARCHAR2(13) NOT NULL , SAMPLEDATE DATE NOT NULL , NOON NUMBER(4,1), MIDNIGHT NUMBER(4,1), PRECIPITATION NUMBER,

UNIQUE (City, SampleDate) )/

Oracle8 - The Complete Reference. Koch & Loney 20

The Primary Key

• A primary key is one of the candidate keys.

• Only one primary-key per table is allowed.

drop table BADWEATHER;

create table BADWEATHER ( CITY VARCHAR2(13) NOT NULL , SAMPLEDATE DATE NOT NULL , NOON NUMBER(4,1), MIDNIGHT NUMBER(4,1), PRECIPITATION NUMBER,

PRIMARY KEY (City, SampleDate) )/

Oracle8 - The Complete Reference. Koch & Loney 21

The Primary Key

• An in-line primary key is an immediate definition applying on only one column.

drop table WORKER2;

create table WORKER2 ( Name VARCHAR2(25) PRIMARY KEY ,

Age NUMBER, Address VARCHAR(15)

)/

Oracle8 - The Complete Reference. Koch & Loney 22

The Foreign Key

• A foreign-key is one or more columns which refer to the key of another table.

drop table WORKER2;

create table WORKER2 ( Name VARCHAR2(25) PRIMARY KEY ,

Age NUMBER, Address VARCHAR(15)

REFERENCES LODGING(Lodging))

/

Oracle8 - The Complete Reference. Koch & Loney 23

The Check Constraint

• Checks state that values of a column must be within certain valid ranges.

drop table WORKER2;

create table WORKER2 ( Name VARCHAR2(25) PRIMARY KEY ,

Age NUMBER CHECK (Age between 18 and 65), Address VARCHAR(15)

)/

The condition must be TRUE for new records to be inserted

Oracle8 - The Complete Reference. Koch & Loney 24

Naming Constraints

• All constraints are stored in the data dictionary.

• Name constraints are easy to manipulate– create / drop– enable / disable– alter.

Oracle8 - The Complete Reference. Koch & Loney 25

Named Constraints

• • Use a table_guide name combination, where guide is– table_PK Primary Key– table_FK Foreign Key– table_UK Unique Key– table_Field_CK Check rule on Field.

Oracle8 - The Complete Reference. Koch & Loney 26

Named Constraints

drop table WORKER2

/create table WORKER2 ( Name VARCHAR2(25) constraint WORKER2_PK

PRIMARY KEY,Age NUMBER constraint WORKER2_AGE_CK

CHECK (Age Between 18 and 65), Address VARCHAR(15) constraint WORKER2_Address_FK REFERENCES LODGING(Lodging)

)/

Oracle8 - The Complete Reference. Koch & Loney 27

Altering Tables

• Tables can be altered in two ways– changing a column’s definition (modify), or

– adding a new column to an existing table (add)

alter table LODGING add ( constraint Lodging_PK PRIMARY KEY (Lodging) )

NOTE: Use the DESC operator to see the current table structure.

Oracle8 - The Complete Reference. Koch & Loney 28

Rules for Add/Modify Table

• When adding a column do not include the NOT NULL clause.

• You may add a NOT NULL in 3 steps– 1. Add the column– 2. Fill every possible row with data.– 3. Modify the column to be NOT NULL.

• Increase CHAR/VARCHAR2 width at any time.• Add more digits to a NUMBER at any time.

Oracle8 - The Complete Reference. Koch & Loney 29

Rules for Views

• Views based on a single table can insert, delete, and update the underlying table.

• You can not insert if the base table has any not null columns not included in the view.

• You can not insert, update if columns in the view are generated with functions or calculations.

• You can not maintain the base table if the view includes: group by, distinct, rowNum.

Oracle8 - The Complete Reference. Koch & Loney 30

Read-Only Views

create or replace view RAIN asselect City, Precipitationfrom BADWEATHERwith read only;

Comment: Read-only views are also called SNAP-SHOTS

Oracle8 - The Complete Reference. Koch & Loney 31

Create a Table from a Table

• Use the create table ... as select-statm.

drop table RAIN;

create table RAINasselect * from BADWEATHER;

You can use the name of an existing object.

Oracle8 - The Complete Reference. Koch & Loney 32

Create a Table from a Table

• To copy only the structure -and no data- do as in the example below

create table RAINasselect * from BADWEATHERwhere true = false;

The condition is false and results in no row selected

Oracle8 - The Complete Reference. Koch & Loney 33

Index-Only Tables

• An index-only table is stored as if the entire table were an index.

• They can be used in order to• increase performance

• enforce uniqueness of data

• Only one key can be used to index the table.

• Good idea only when data is very stable.

Oracle8 - The Complete Reference. Koch & Loney 34

Index-Only Tables

drop table WORKER3;

create table WORKER3 ( Name VARCHAR2(25),

Age NUMBER, Address VARCHAR(15)

constraint WORKER3_PK PRIMARY KEY (Name))ORGANIZATION INDEX;

/

Oracle8 - The Complete Reference. Koch & Loney 35

Partitioned Tables

• Large tables could be split into more than one physical

table-location. Partitioning may improve performance.create table WORKER5 ( Name VARCHAR2(25),

Age NUMBER, Address VARCHAR(15),

constraint WORKER5_PK PRIMARY KEY (Name))PARTITION by range (Name) (partition PART1 values less than ('F') tablespace Ohio1_TS, partition PART2 values less than (MAXVALUE)

tablespace Ohio2_TS);

Oracle8 - The Complete Reference. Koch & Loney 36

Summary

• SQL tables are created using the commandcreate table [schema.]tablname (

column datatype [col_constraint], ... )

[table_Constraint];

• Constructing a table requires• Table name,

• Column names, datatypes, lengths,

• Integrity constraints.

Oracle8 - The Complete Reference. Koch & Loney 37

Summary

• Constraint types– NOT NULL

– UNIQUE

– PRIMARY KEY

– FOREIGN KEY

– CHECK

• UNIQUE indexes are created automatically with– PRIMARY KEY and

– UNIQUE constraints