1 the oracle database system building a database database course the hebrew university of jerusalem

54
1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

Post on 20-Dec-2015

244 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

1

The Oracle Database System

Building a Database

Database CourseThe Hebrew University of Jerusalem

Page 2: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

2

Technical Basics

Page 3: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

3

Connecting to the Database

At the command line prompt, write:

sqlplus login/[email protected]

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

password

To disconnect use the command:quit

Page 4: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

4

Connecting to the Database

Page 5: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

5

Running SQL Files

Instead of typing SQL commands into the SQLPLUS terminal, you can load commands from a file Use the command @file from SQLPLUS to load

the file file.sql Invoke the SQLPLUS command with the extra

parameter @file to load the file at connection: sqlplus login/[email protected] @file

Page 6: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

6

Spooling the Output

Output can be placed in a file: spool myFile.out

Spooling can be turned off with: spool off

Page 7: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

7

Tables Creation

Page 8: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

8

Creating a Table

The basic format of the CREATE TABLE command is:

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

);

Page 9: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

9

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

Page 10: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

10

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

Page 11: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

11

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

Page 12: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

12

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

);

Page 13: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

13

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

);

Page 14: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

14

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)

);

Unique Constraint

The name of the constraint

Page 15: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

15

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 implies NOT NULL and UNIQUE. There can only be one primary key.

Page 16: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

16

Another Table

CREATE TABLE Department(DeptNum NUMBER PRIMARY KEY,Name VARCHAR2(20),ManagerId NUMBER

);

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

Page 17: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

17

Foreign Key Constraint(Referential Integrity)

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),FOREIGN KEY (Dept) REFERENCES

Department(DeptNum));

Must be unique

Page 18: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

18

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)

);

Page 19: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

19

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?

Page 20: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

20

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 as

FOREIGN KEY (Dept) REFERENCES

Department(DeptNum) ON DELETE CASCADE

then Employees working in 312 will be deleted

automatically from the Employee table

Page 21: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

21

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:

Page 22: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

22

Solution to Cyclic Constraints

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

ALTER TABLE Department

ADD(FOREIGN KEY (ManagerId)

REFERENCES Employee(SSN));

Page 23: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

23

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

Page 24: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

24

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)

);

Page 25: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

25

Table Alteration

Page 26: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

26

Altering Tables

Table definition can be altered after its creation Adding columns Changing columns’ definition Dropping columns Adding constraints And more…

Use the reserved word ALTER

Page 27: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

27

Altering Tables (continues)

Adding a column:ALTER TABLE Employee ADD (

Mname VARCHAR2(20),Birthday DATE

); Changing columns’ definition:

ALTER TABLE Emplyee Modify (Mname VARCHAR2(10)

);

Cannot be NOT NULL unless the

table is empty

Page 28: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

28

Altering Tables (continues)

Dropping columns:ALTER TABLE Employee DROP COLUMN

Mname;

Dropping multiple columns:

ALTER TABLE Employee DROP (Mname, Birthday);

Adding constraints:ALTER TABLE Department ADD(

FOREIGN KEY (ManagerId) REFERENCES Employee(SSN));

Page 29: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

29

Deleting a Table

To delete the table Employee :

DROP TABLE Employee;

Page 30: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

30

User’s Table List

ORACLE may print tables that hold some general information about the tables in your database

Such Tables are: Tab, Cat, User_Tables (too detailed...)

To see the list of all your tables you can print: SELECT * FROM Cat; SELECT tname FROM Tab; SELECT table_name from User_Tables;

Page 31: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

31

Table Data Maintenance

Page 32: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

32

The Employee Table

> Describe Employee

Name Null? Type-------- -------- ------------SSN NUMBERFNAME VARCHAR2(20)LNAME VARCHAR2(20)GENDER CHAR(1)SALARY NOT NULL NUMBER(5)

Page 33: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

33

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)

Order is not important

Page 34: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

34

Some More Details…

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

Example:INSERT INTO Employee

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

Page 35: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

35

Deleting Rows

General format:DELETE FROM Table WHERE Cond;

Deletes all rows satisfying Cond from Table For example, to remove the employee with

SSN 121 from the Employee table:DELETE FROM Employee WHERE

SSN = 121;

Page 36: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

36

Deleting Rows (continues)

To remove all male employees having a salary greater than 15000 shekels:

DELETE FROM Employee WHERE

Gender = ‘M’ AND Salary > 15000;

We will later discuss WHERE clauses…

Case sensitive

Page 37: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

37

Updating Rows (continues)

We can update fields of rows in a table General format:

UPDATE Table SET Field1=value1,,,FieldN=valueNWHERE Cond

Now we can reduce salaries instead of firing employees:

UPDATE Employee SET Salary = 15000 WHERE Gender = ‘M’ AND

Salary > 15000;

Page 38: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

38

The ORACLE Bulk Loader

A tool that provides easy insertion of large amounts of rows into tables.

The idea: the field values of the rows are kept in a file, the format of which is defined by us.

For example, it can automatically load 3 employees from the file myEmployees.dat that contains the following lines:

Sara|Cohen|121Benny|Kimelfeld|134Yaron|Kanza|156

Page 39: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

39

The Control File

The control file is the direct input of the loader A simple control file:

LOAD DATA

INFILE <dataFile> [APPEND] INTO TABLE <tableName> FIELDS TERMINATED BY '<separator>‘(<list of all attribute names to load>)

Page 40: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

40

The Control File (continues)

<dataFile>: The name of the data file

<tableName>: The name of the table into which the data will be loaded

(appended if APPEND is specified, or else the table must be empty)

<separator>: A string that separates two field values of a row

The attributes are separated by commas and enclosed in parentheses

Page 41: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

41

The Control File (continues)

As an example, the following control file loads the employees from myEmployees.dat:

LOAD DATA

INFILE myEmployees.dat INTO TABLE Employees FIELDS TERMINATED BY '|' (Fname, Lname, SSN)

The attributes that are unspecified will be set to NULL

Page 42: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

42

The Data File

The Bulk Loader considers every single line to represent one row in the table Even an empty line! (which will usually result in

an error) Spaces are not ignored in the data file!

thus the rows ‘sara| cohen|121’ and ‘sara|cohen|121’ define different functionalities

The NULL value is implied by the NULL keyword or the empty string

Page 43: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

43

The Data File (continues)

The control and the data files can be combined into one .ctl file using the following format:

LOAD DATA INFILE *INTO TABLE Employees FIELDS TERMINATED BY '|' (Fname, Lname, SSN)BEGINDATA Sara|Cohen|121Benny|Kimelfeld|134Yaron|Kanza|156

Page 44: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

44

The Bulk Invocation

To invoke the bulk loader, issue the following command directly from the Unix shell:sqlldr <yourName> control=<ctlFile> log=<logFile> bad=<badFile>

All fields are optional File names that have no extension are

automatically extended (by .dat, .log or .bad) Erroneous lines in the data file are ignored

and written into badFile, and any other relevant information is written into logFile.

Page 45: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

45

Bulk Loader Important Remarks

Before using the Bulk Loader, make sure your personal ORACLE environment is properly set up

The tables you fill using the Bulk Loader should be created prior to the loader invocation

Before invoking the Bulk Loader you have to make sure that NO SQLPLUS SESSIONS ARE OPENNED!

Page 46: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

46

Table Printing and Formatting

Page 47: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

47

Format Example

Consider the following table print:

Page 48: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

48

Format Example (continues)

Absolutely not readable! Solution: we write some commands in a format file

and we get:

Page 49: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

49

Printing a Table

To print a table use the sql command: SELECT * FROM table_name;

Page 50: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

50

Add a Title

We can add a title to a table printing page using the command: TTITLE ‘title’

Page 51: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

51

Change a Column’s Heading

We can change a column’s heading using the command: COLUMN ‘col_name’ HEADING ‘heading’

Page 52: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

52

Define a Column Size

We can define the size of a column: COLUMN ‘col_name’ format ‘format’ Format Examples:

a18: an ASCII text of size 18 90.99: a number with 4 digits, a decimal point,

minus sign (for negative numbers) and 0 before the dot for numbers smaller than 1

We can ask ORACLE to cut words to fit the defined space using the command: COLUMN ‘col_name’ truncated

Page 53: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

53

Define a Column Size

Page 54: 1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

54

The Whole Picture