The Oracle Database System. Connecting to the Database At the command line prompt, write: sqlplus...

Post on 17-Jan-2016

230 views 0 download

transcript

The Oracle Database System

Connecting to the Database

At the command line prompt, write:

sqlplus login/password@stud.cs

In the beginning your password is the same as your login. You can change your password with the command:

password

Creating a Table

The basic format of the CREATE TABLE command is:

CREATE TABLE TableName(Column1 DataType1 ColConstraint, …ColumnN DataTypeN ColConstraint,TableConstraint1, …TableConstraintM

);

An Example

If you issue the command describe Cars you get:

Name Null? Type

-------- ----- ------------

LICENSE NUMBER

COLOR VARCHAR2(15)

CREATE TABLE Cars(

License NUMBER,

Color VARCHAR2(15));

Note that the definition is case insensitive

Data Types

CHAR(n) String of length n (n <= 2000)

VARCHAR2(n) Variable length string of size <= n

(n <= 4000)

DATE Valid dates

CLOB Character large object (<= 4Gb)

NUMBER Up to 40 digits

NUMBER(n) Number of size n

NUMBER(n,m) Number of size n with m digits after decimal place

Constraints in Create Table

• Adding constraints to a table enables the database system to enforce data integrity.

• However, adding constraints also makes inserting data slower.

• Different types of constraints:* Not Null * Default Values* Unique * Primary Key* Foreign Key * Check Condition

Not Null Constraint

CREATE TABLE Employee(

SSN NUMBER NOT NULL,

Fname VARCHAR2(20),

Lname VARCHAR2(20),

Gender CHAR(1),

Salary NUMBER(5) NOT NULL,

Dept NUMBER

);

Default Values

CREATE TABLE Employee(

SSN NUMBER NOT NULL,

Fname VARCHAR2(20),

Lname VARCHAR2(20),

Gender CHAR(1) DEFAULT(‘F’),

Salary NUMBER(5) NOT NULL,

Dept NUMBER

);

Unique Constraint

CREATE TABLE Employee(

SSN NUMBER UNIQUE NOT NULL,

Fname VARCHAR2(20),

Lname VARCHAR2(20),

Gender CHAR(1) DEFAULT(‘F’),

Salary NUMBER(5) NOT NULL,

Dept NUMBER,

constraint Emp_UQ UNIQUE(Fname, Lname)

);

Primary Key Constraint

CREATE TABLE Employee(

SSN NUMBER PRIMARY KEY,

Fname VARCHAR2(20),

Lname VARCHAR2(20),

Gender CHAR(1) DEFAULT(‘F’),

Salary NUMBER(5) NOT NULL,

Dept NUMBER,

constraint Emp_UQ UNIQUE(Fname, Lname)

);

Primary Key also implies NOT NULL. There can only be one primary key.

Another Table

CREATE TABLE Department(

DeptNum NUMBER PRIMARY KEY,

Name VARCHAR2(20),

ManagerId NUMBER

);

Shouldn’t all department numbers in Employee appear in Department?

Foreign Key ConstraintCREATE TABLE Employee(

SSN NUMBER PRIMARY KEY,

Fname VARCHAR2(20),

Lname VARCHAR2(20),

Gender CHAR(1) DEFAULT(‘F’),

Salary NUMBER(5) NOT NULL,

Dept NUMBER,

constraint Emp_UQ UNIQUE(Fname, Lname),

FOREIGN KEY (Dept) REFERENCES Department(DeptNum)

);

Alternative Notation

CREATE TABLE Employee(

SSN NUMBER PRIMARY KEY,

Fname VARCHAR2(20),

Lname VARCHAR2(20),

Gender CHAR(1) DEFAULT(‘F’),

Salary NUMBER(5) NOT NULL,

Dept NUMBER REFERENCES Department(DeptNum),

constraint Emp_UQ UNIQUE(Fname, Lname)

);

Understanding Foreign Keys

• The constraint on the last table should be read as: “The field Dept in Employee is a foreign key that references the field DeptNum in Department”

• Meaning: Every non-null value in the field Dept in Employee must appear in the field DeptNum in Department.

What happens to Employees in department 312 when Department 312 is removed from the Department table?

Deleting a Referenced Value

If nothing additional is specified, then Oracle will

not allow Department 312 to be deleted if there

are Employees working in this department.

If the constraint is written asFOREIGN KEY (Dept) REFERENCES

Department(DeptNum) ON DELETE CASCADE

then Employees working in 312 will be deleted

automatically from the Employee table

Remembering ER-Diagrams

Person CarOwns

ssn

name address

since license color

model

What foreign keys appear naturally in this context?

CREATE TABLE Owns(

SSN NUMBER REFERENCES Person(SSN),

License NUMBER REFERENCES Car(License),

Since DATE);

Cyclic Foreign Keys

CREATE TABLE Department(

DeptNum NUMBER PRIMARY KEY,

Name VARCHAR2(20),

ManagerId NUMBER REFERENCES Employee(SSN)

);

Do you see a problem in inserting data now?

We should revise the Department table:

Solution to Cyclic Constraints

Add one of the constraints later on (after insertion):

ALTER TABLE Department

ADD(FOREIGN KEY (ManagerId)

REFERENCES Employee(SSN));

Check Conditions

• A check condition is a Boolean expression:– “And”s and “Or”s of conditions of the type X > 5…

• On a column: it can refer only to the column

• On a table: it can refer only to multiple columns in the table

Check Constraints

CREATE TABLE Employee(

SSN NUMBER PRIMARY KEY,

Fname VARCHAR2(20),

Lname VARCHAR2(20),

Gender CHAR(1) DEFAULT(‘F’)

CHECK(Gender = ‘F’ or

Gender = ‘M’) ,

Salary NUMBER(5) NOT NULL,

CHECK (Gender = ‘M’ or Salary > 10000)

);

Deleting a Table

• To delete the table Employee :

DROP TABLE Employee;

Inserting Data Into a Table

Inserting a Row

• To insert a row into the Employee table:INSERT INTO Employee(SSN, Fname, Lname, Salary)

VALUES(121, ‘Sara’, ‘Cohen’, 10000);

• The remaining columns get default values (or NULL)

• The fields needn’t be specified if values are specified for all columns and in the order defined by the table

Some More Details…

• An example of inserting into the Owns table:

INSERT INTO Owns

VALUES(121, 4545, ’01-DEC-02’);

• We can also use the Oracle Loader: Details in Ex2…

Querying the Data

Example Tables Used

Reserves

sid bid day

22

58

101

103

10/10/96

11/12/96

Sailors

sid sname rating age

22

31

58

Dustin

Lubber

Rusty

7

8

10

45.0

55.5

35.0

Boats

bid bname color

101

103

Nancy

Gloria

red

green

Basic SQL Query

SELECT [Distinct] target-list

FROM relation-list

WHERE condition;

•relation-list: A list of relation names (possibly with a range-variable after each name)

•target-list: A list of fields of relations in relation-list

•condition: A Boolean condition

•DISTINCT: Optional keyword to delete duplicates

Basic SQL Query

SELECT Distinct A1,…,An

FROM R1,…,Rm

WHERE C;

This translates to the expression in relational algebra:

A1,…,An (C(R1 x…x Rm))

Sailors Who Reserved Boat 103

SELECT sname

FROM Sailors, Reserves

WHERE Sailors.sid = Reserves.sid and

bid = 103;

sname

(Sailors.sid = Reserves.sid bid = 103 (Sailors x Reserves))

Sailors Reserves

sid sname rating age sid bid day

22 Dustin 7 45.0 22 101 10/10/96

22 Dustin 7 45.0 58 103 11/12/96

31 Lubber 8 55.5 22 101 10/10/96

31 Lubber 8 55.5 58 103 11/12/96

58 Rusty 10 35.0 22 101 10/10/96

58 Rusty 10 35.0 58 103 11/12/96

Sailors x ReservesSailors.sid = Reserves.sid bid = 103

sname

Range Variables

SELECT S.sname

FROM Sailors S, Reserves R

WHERE S.sid = R.sid and

R.bid = 103;

• Range variables are good style.

• They are necessary if the same relation appears twice in the FROM clause

Sailors Who’ve Reserved a Boat

SELECT sid

FROM Sailors S, Reserves R

WHERE S.sid = R.sid;

Would adding DISTINCT give a different result?

Expressions and Strings

SELECT age, (age-5)*2 as age1

FROM Sailors,

WHERE sname LIKE ‘B_%B’;

• Expressions in SELECT clause

• Renaming of column in result

• String comparison: _ is a single character and % is 0 or more characters

Sailors who’ve reserved a red or green boat

SELECT S.sid

FROM Sailors S, Boats B, Reserves R

WHERE S.sid = R.sid and R.bid = B.bid and (B.color = ‘red’ or

B.color = ‘green’);

sid

(color = ‘red’ color = ‘green’

(Sailors Reserves Boats))

What would happen if we replaced or by and ?

Sailors who’ve reserved red or green boat

SELECT S.sid

FROM Sailors S, Boats B, Reserves R

WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘red’

UNION

SELECT S.sid

FROM Sailors S, Boats B, Reserves R

WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘green’;

What would happen if we wrote MINUS? Or INTERSECT?

The Second Version in Relational Algebra

sid

(color = ‘red’

(Sailors Reserves Boats))

sid

(color = ‘green’

(Sailors Reserves Boats))

Sailors who’ve reserved red and green boat

SELECT S.sid

FROM Sailors S, Boats B1, Reserves R1,

Boats B2, Reserves R2

WHERE S.sid = R1.sid and R1.bid = B1.bid and B1.color = ‘red’ and

S.sid = R2.sid and R2.bid = B2.bid and B2.color = ‘green’;

Nested Queries

SELECT S.sid

FROM Sailors S

WHERE S.sid IN (SELECT R.sid

FROM Reserves R

WHERE R.bid = 103);

Names of sailors who’ve reserved boat 103:

The SELECT, FROM and WHERE clauses can have sub-queries. They are computed using nested loops.

What would happen if we wrote NOT IN?

Correlated Nested Queries

SELECT S.sid

FROM Sailors S

WHERE EXISTS (SELECT *

FROM Reserves R

WHERE R.bid = 103 and

S.sid = R.sid);

Names of sailors who’ve reserved boat 103:

What would happen if we wrote NOT EXISTS?

More Set-Comparison Queries

SELECT *

FROM Sailors S1

WHERE S1.age > ANY (SELECT S2.age

FROM Sailors S2);

Sailors who are not the youngest:

We can also use op ALL (op is >, <, =, >=, <=, or <>).

Some Small Details

Input and Output Files

• Commands can be put in a file and then read into Oracle:

start commands.sql

• Output can be placed in a file:

spool commands.out• Spooling can be turned off with:

spool off