Designing Tables for an Oracle Database System. From theory to practice

Similar documents
From theory to practice. Designing Tables for an Oracle Database System. Sqlplus. Sqlplus. Technicalities. Add the following to your.

From theory to practice. Designing Tables for a postgresql Database System. psql. Reminder. A few useful commands

CS2300: File Structures and Introduction to Database Systems

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

Translating an ER Diagram to a Relational Schema

2. E/R Design Considerations

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

High-Level Database Models (ii)

CSC 453 Database Technologies. Tanu Malik DePaul University

CSE 530A. ER Model to Relational Schema. Washington University Fall 2013

The Relational Model 2. Week 3

Using DDL Statements to Create and Manage Tables. Copyright 2004, Oracle. All rights reserved.

SQL Data Definition and Data Manipulation Languages (DDL and DML)

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data.

Using DDL Statements to Create and Manage Tables. Copyright 2004, Oracle. All rights reserved.

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

Translation of ER-diagram into Relational Schema. Dr. Sunnie S. Chung CIS430/530

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

High Level Database Models

SQL Data Definition: Table Creation

SQL: DDL. John Ortiz Cs.utsa.edu

Full file at

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

Lab # 4. Data Definition Language (DDL)

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

From ER to Relational Model. Book Chapter 3 (part 2 )

Data Definition Language (DDL)

SQL Introduction. CS 377: Database Systems

Database Management Systems. Chapter 3 Part 2

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Unit 1 - Chapter 4,5

LAB 3 Notes. Codd proposed the relational model in 70 Main advantage of Relational Model : Simple representation (relationstables(row,

Using DDL Statements to Create and Manage Tables. Copyright 2006, Oracle. All rights reserved.

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng.

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

The Entity-Relationship Model

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

CONCEPTUAL DESIGN: ER TO RELATIONAL TO SQL

Physical Design of Relational Databases

1 INTRODUCTION TO EASIK 2 TABLE OF CONTENTS

The Relational Model. Outline. Why Study the Relational Model? Faloutsos SCS object-relational model

DATABASE MANAGEMENT SYSTEMS

Keys are fields in a table which participate in below activities in RDBMS systems:

The Entity-Relationship Model. Overview of Database Design

Database Technology. Topic 3: SQL. Olaf Hartig.

The Relational Model. Chapter 3

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

The Relational Model. Roadmap. Relational Database: Definitions. Why Study the Relational Model? Relational database: a set of relations

The Relational Model. Chapter 3. Database Management Systems, R. Ramakrishnan and J. Gehrke 1

SQL DATA DEFINITION LANGUAGE

Data Modeling. Yanlei Diao UMass Amherst. Slides Courtesy of R. Ramakrishnan and J. Gehrke

Where Are We? Next Few Lectures. Integrity Constraints Motivation. Constraints in E/R Diagrams. Keys in E/R Diagrams

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

COSC344 Database Theory and Applications. Lecture 6 SQL Data Manipulation Language (1)

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

Basic SQL. Basic SQL. Basic SQL

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Relational Databases Fall 2017 Lecture 7

3ISY402 DATABASE SYSTEMS

Database Management Systems,

Introduction to Databases

Conceptual Design. The Entity-Relationship (ER) Model

Principles of Data Management

Database Programming with PL/SQL

Database Technology. Topic 2: Relational Databases and SQL. Olaf Hartig.

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

SQL Data Definition Language

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Integrity constraints, relationships. CS634 Lecture 2

Introduction to Data Management. Lecture #5 (E-R Relational, Cont.)

Applied Databases. Sebastian Maneth. Lecture 7 Simple SQL Queries. University of Edinburgh - February 6 st, 2017

Relational Databases BORROWED WITH MINOR ADAPTATION FROM PROF. CHRISTOS FALOUTSOS, CMU /615

Handout 6 Logical design: Translating ER diagrams into SQL CREATE statements

The Relational Model (ii)

Applied Databases. Sebastian Maneth. Lecture 7 Simple SQL Queries. University of Edinburgh - February 1 st, 2016

Database Management Systems,

Structured Query Language (SQL)

Relational Model. CSE462 Database Concepts. Demian Lessa. Department of Computer Science and Engineering State University of New York, Buffalo

DATA CONSTRAINT. Prepared By: Dr. Vipul Vekariya

The Relational Model. Week 2

Database Laboratory Note (MS SQL Server 2000)

SQL DATA DEFINITION LANGUAGE

CSE 530A. ER Model. Washington University Fall 2013

CIS 330: Applied Database Systems. ER to Relational Relational Algebra

Database design process

Data Storage and Query Answering. Data Storage and Disk Structure (4)

A <column constraint> is a constraint that applies to a single column.

Introduction to Data Management. Lecture #4 (E-R à Relational Design)

Overview Relational data model

Relational Model. Topics. Relational Model. Why Study the Relational Model? Linda Wu (CMPT )

Introduction to Data Management. Lecture #6 E-Rà Relational Mapping (Cont.)

Creating Tables, Defining Constraints. Rose-Hulman Institute of Technology Curt Clifton

Database Modelling. Lecture 4 (b): Database Integrity, Keys & Constraints. Akhtar Ali 10/14/2014 1

Database Applications (15-415)

Downloaded from

Database Logical Design

SQL Simple Queries. Chapter 3.1 V3.01. Napier University

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Transcription:

Designing Tables for an Oracle Database System Database Course, Fall 2004 From theory to practice The Entity- Relationship model: a convenient way of representing the world. The Relational model: a model of organizing data using tables. Oracle: a database infrastructure which implements the relational model. Converting ER->Relational model is important! SQL(Structured Query Language): A language used to get information from an oracle database.

Technicalities Add the following to your.cshrc file: source ~db/oraenv You will be able to use Oracle after you log out and log in again. You can run Oracle from os, pita, inferno, etc. Cannot run from xil-es. If you are on xil, do rlogin to one of these computers (e.g., rlogin inferno- 01) Connecting to the Oracle 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: To disconnect, type: quit password Remember: (almost) Every command must end with a semicolon (;)

Running Commands from an.sql File Instead of typing commands into the SQLPLUS terminal, you can load commands from a file (no special format is required). Invoke by: 1. Use the command @file from SQLPLUS to load the file file.sql Or: 2. Invoke the SQLPLUS command with the extra parameter @file to load the file at connection: sqlplus login/password@stud.cs @file Spooling the Output Output can be placed in a file: spool myfile.out (output file updates after next command) Spooling can be turned off with: spool off

Tables The basic element in oracle is a table. A table has columns (attributes), and rows (tuples). Every column has a Name and Type (of the data it stores), and some columns have constraints. Some tables may have additional constraints. Creating Tables in SQL Id Name Dept. Age 0345 Eyal Sales 28 0965 Yair Transport 34 7665 Ori Warehouse 31

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 CREATE TABLE Employee( ID NUMBER NOT NULL, F VARCHAR2(20), L VARCHAR2(20), Gender CHAR(1), Salary NUMBER(5) NOT NULL, Dept NUMBER );

An Example (cont.) Oracle is case insensitive in Column s! If you type describe Employee you get: Name Null? Type ----------- ------------ ------------ SSN FNAME LNAME GENDER NOT NULL NUMBER VARCHAR2(20) VARCHAR2(20) CHAR(1) SALARY NOT NULL NUMBER(5) DEPT NUMBER Notice that describe describes the structure and not the contents of the table.

Examples of Data Types CHAR(n) VARCHAR2(n) LONG CLOB BLOB DATE TIMESTAMP NUMBER NUMBER(n) NUMBER(n,m) Others String of length n (n <= 2000) Variable length string of size <= n (n <= 4000) Variable length string of length (<= 2GB) Character large object (<= 4GB) Binary large object (<= 4GB) Valid dates (up to seconds) Valid timestamps (up to milliseconds) Up to 40 digits Integer of size n Number of size n with m digits after decimal place XML, Abstract types, etc. What happens if we insert: ' abc' into char(5)? ' abc' into varchar(5)? ' abc' into char(2)? ' abc' into varchar(2)? 105.32 into number(3,2)? 105.32 into number(5,2)? 105.32 into number(4,1)? 105.32 into number(3)? 105.32 into number? 105.1 into number(7,5)? abc abc Wrong! Wrong! Wrong! 105.32 105.3 105 105.32 Wrong! Why not always use number and not number(n,m)? Why not always use varchar2(4000) or long? Where is the boolean datatype?

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, F VARCHAR2(20), L VARCHAR2(20), Gender CHAR(1), Salary NUMBER(5) NOT NULL, Dept NUMBER );

Default Values CREATE TABLE Employee( SSN NUMBER NOT NULL, F VARCHAR2(20), L VARCHAR2(20), Gender CHAR(1) DEFAULT( F ), Salary NUMBER(5) NOT NULL, Dept NUMBER ); Unique Const raint (Synt ax 1) CREATE TABLE Employee( SSN NUMBER UNIQUE NOT NULL, F VARCHAR2(20), L VARCHAR2(20), Gender CHAR(1) DEFAULT( F ), Salary NUMBER(5) NOT NULL, Dept NUMBER );

Unique Const raint (Synt ax 2) CREATE TABLE Employee( SSN NUMBER NOT NULL, F VARCHAR2(20), L VARCHAR2(20), Gender CHAR(1) DEFAULT( F ), Salary NUMBER(5) NOT NULL, Dept NUMBER, UNIQUE(SSN) ); Unique Constraint (Another Example) CREATE TABLE Employee( SSN NUMBER UNIQUE NOT NULL, F VARCHAR2(20), L VARCHAR2(20), Gender CHAR(1) DEFAULT( F ), Salary NUMBER(5) NOT NULL, Dept NUMBER, UNIQUE(F, L) ); How else can this be written?

Primary Key Constraint CREATE TABLE Employee( SSN NUMBER PRIMARY KEY, F VARCHAR2(20), L VARCHAR2(20), Gender CHAR(1) DEFAULT( F ), Salary NUMBER(5) NOT NULL, Dept NUMBER, UNIQUE(F, L) ); Primary Key implies: * NOT NULL * UNIQUE. There can only be one primary key. Primary Key Constraint (Syntax 2) CREATE TABLE Employee( SSN NUMBER, F VARCHAR2(20), L VARCHAR2(20), Gender CHAR(1) DEFAULT( F ), Salary NUMBER(5) NOT NULL, Dept NUMBER, UNIQUE(F, L), PRIMARY KEY(ssn) );

Another Table CREATE TABLE Department( Dept NUMBER PRIMARY KEY, Name VARCHAR2(20), ManagerId NUMBER ); Shouldn t all department numbers in Employee appear in Department? Foreign Key Constraint CREATE TABLE Employee( ID NUMBER PRIMARY KEY, F VARCHAR2(20), L VARCHAR2(20), Gender CHAR(1) DEFAULT( F ), Salary NUMBER(5) NOT NULL, Dept NUMBER, UNIQUE(F, L), FOREIGN KEY (Dept) REFERENCES Department(Dept) ); NOTE: Dept must be unique (or primary key) in Department

Foreign Key Const raint (Synt ax 2) CREATE TABLE Employee( ID NUMBER PRIMARY KEY, F VARCHAR2(20), L VARCHAR2(20), Gender CHAR(1) DEFAULT( F ), Salary NUMBER(5) NOT NULL, Dept NUMBER, UNIQUE(F, L), FOREIGN KEY (Dept) REFERENCES Department ); NOTE: Dept must be the of the field in Department, too Employee ID FName 02334 Larry 04556 Magic Foreign Key LName Bird Johnson Gender M M Sallary 230000 270000 Dept 12 45 Foreign Key Department Dept Name ManID 12 Sales 988 45 Repair 876

Understanding Foreign Keys The const r aint on t he last t able should be r ead as: The field Dept in Employee is a foreign key that references the field Dept in Department Meaning: Every non-null value in the field Dept of Employee must appear in the field Dept of 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 as FOREIGN KEY (Dept) REFERENCES Department ON DELETE CASCADE then Employees working in 312 will be deleted automatically from the Employee table, when 312 is deleted from Departments

Cyclic Foreign Keys We should revise the Department table: CREATE TABLE Department( Dept NUMBER PRIMARY KEY, Name VARCHAR2(20), ManagerId NUMBER, FOREIGN KEY (ManagerId) REFERENCES Employee(SSN) ); Do you see a problem in defining these tables and in inserting data now? Foreign Key ID FName LName Gender Sallary Dept Foreign Key Dept Name ManID

Solution to Cyclic Constraints Add one of the constraints later on (after insertion): CREATE TABLE Department( Dept NUMBER PRIMARY KEY, Name VARCHAR2(20), ManagerId NUMBER); Insert data here 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 condit ions of t he t ype 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, F VARCHAR2(20), L 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; Mind the order of dropping when there are foreign key constraints. Why? Can use: DROP TABLE Employee cascade constraints;

Translating ER- Diagrams to Table Definitions Relations vs. Tables We show how to translate ER-Diagrams to table definitions Sometimes, people translate ER-Diagrams to relation definition, which is more abstract than table definitions. e.g., Employee(SSN, F, L, Gender, Salary, Dept); table definitions contain, in addition, constraints and datatypes

Simple entity translation id Actor birthday address General Rule: Create a table with the of the Entity. There is a column for each attribute The key in the diagram is the primary key of the table Simple entity translation id Actor birthday address Relation: Actor (id,, birthday, address) create table Actor(id varchar2(20) primary key, varchar2(40), birthday date, address varchar2(100));

Translating Entities with Relationships birthday (without constraints) title id Actor Acted In Film year address salary Create tables for the entities as before Create a table with the of the relationship Relationship table attributes: its own attributes (salary) + all keys of the relating entities (title, id). Q: What is the primary key of the table? A: A composite of both entity keys Q: What foreign keys are needed? A: From the relationship table to the entities type birthday Translating relationships (without constraints) title id Actor Acted In Film year address salary type What would be the relation for ActedIn? How would you define the table for ActedIn?

Translating Recursive Relationships (without constraints) manager id Employee worker Manages address Relation: Manages (Wid, Mid) What would be the table definition? create table Manages( Eid varchar2(20), Mid varchar2(20), Foreign key Eid references Employee(id), Foreign key Mid references Employee(id), Primary key(eid, Mid)); If we want to make sure an employee is not his own manager we can express it with Check Translating relationships (key constraints): Option 1 id Director Directed Film title salary year Option 1: Same as without key constraints (3 tables), except that t he r elat ionship pr imar y key is? title.

id Translating relationships (key constraints): Option 1 Director Directed Film title salary year create table Directed( id varchar2(20), title varchar2(40), salary integer, primary key (title), foreign key id references Director, foreign key title references Film); id Translating relationships (key constraints): Option 2 Director Directed Film title salary year Option 2: Do not create a table for the relationship Add information columns that would have been in the relationship's table to the table of the entity with the key constraint Why couldn t we do t his wit h a r egular r elat ion?

id Translating relationships (key constraints): Option 2 Director Directed Film title salary year create table Film( title varchar2(40), year integer, primary key (title), id varchar2(20), salary integer, foreign key(id) references Director); Translating relationships (key constraints) A R B C What are the different options for translating this diagram?

id Translating relationships (participation constraints) Director Directed Film title salary year General Rule: If both participation and key constraint exist, use Option 2 from before (only 2 tables). Add the not null constraint to ensure that there will always be values for the key of the other entity id Translating relationships (participation constraints) Director Directed Film title salary year create table Film( title varchar2(40), year integer, id varchar2(20), salary integer, foreign key (id) references Director, primary key (title)); Where should we add NOT NULL?

id Translating relationships (participation constraints) Actor Acted In Film title salary year How would we translate this? Translating Weak Entity Sets Organization year Gives Award phone number money create table award( ) varchar2(40), year integer, money number(6,2), o_ varchar2(40), primary key(, year, o_), foreign key (o_) references Organization() on delete cascade

Translating ISA: Option 1 address Movie Person id ISA picture Actor Director create table MoviePerson(... ) create table Actor(id varchar2(20), picture bfile, primary key(id), foreign key (id) references MoviePerson)) create table Director(...) Translating ISA: Option 2 address Movie Person id ISA picture Actor Director No table for MoviePerson! create table Actor(id varchar2(20), address varchar2(100), varchar2(20), picture blob, primary key(id)); create table Director(...)

Which Option To Choose? What would you choose if: Actor and Director DO NOT COVER MoviePerson? Actor OVERLAPS Director? Organization phone number picture Translating Aggregation Actor Gives salary Acted In Won Award year Film year title type Create table for Won using: key of ActedIn key of Award (careful, award is a weak entity)

Summary Tables Primary key Remarks Simple Entity Single table The entity key a column for each attr. Simple 3 (2 entities For the relation: Foreign keys Relationship +relationship) Both entity keys from rel. Table Key constraint 3 as before or Key of Foreign keys constrained ent. from rel. Table 2 (one for each entity) Foreign key from constr. Entity Key and 2 Regular Constrained Participation entity has a constr. non-null f. key Tables Primary key Remarks Weak Entity 2: parent and Weak: its own Foreign keys weak entities and parent keys from weak ent. ISA: covers 2: only child Parent key and no overlap entities ISA: otherwise 3: parent and Parent key Foreign keys child entities from child ent. Aggregation 3: 2 aggregates For Foreign keys and relationship relationship: from relationship keys of both table aggregates

This document was created with Win2PDF available at http://www.daneprairie.com. The unregistered version of Win2PDF is for evaluation or non-commercial use only.