sql training database concepts. confidential & proprietary copyright © 2009 cardinal...

61
SQL Training Database Concepts

Upload: morgan-sullivan

Post on 26-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

SQL Training

Database Concepts

Page 2: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Lesson Objectives

• Explain how data is stored in a relational database

• Describe the purpose primary and foreign keys

• Explain the role of SQL

• Explain the role of referential integrity

• Explain the role of indexes in improving database performance

• Explain the purpose of the Oracle Catalog

Page 2

At the end of this lesson you will be able to:

Page 3: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Lesson Plan

What is a Relational Database

Introduction to Oracle

What is SQL

Creating Database Tables

Preserving Data Integrity

Improving Performance

Using the Database Catalog

Page 3

Page 4: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

What is a Relational Database?

Page 5: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

What is a Table?

Columns, Fields, Attributes

Rows, Records

A table is a set of related data that contains: 

Columns, Fields, Attributes Rows, Records

A Relational Database is a set of related Tables.

Product

Page 5

productID productTypeID productName 1 1 Floor Measurement

2 1 Consumer Solutions

3 1 Astra Applications

4 1 Assortment Space

5 1 Customized Research

7 1 Newspaper

8 5 Television

9 5 Radio

10 5 Magazines

Page 6: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Relational Database

• Each column has a unique name.

• Entries in columns are single-valued (not a list of values).

• Entries in columns are of the same kind.

• Each row is unique. No two rows can have the same primary key value.

Each table must follow these rules:

Primary Key

SubscribedProduct

Note: All rows are not shown.

Page 6

subscribedProductID productID deliveryTypeID subscribedProductName startEffectiveDate endEffectiveDate

42 2 3 Secret Shopper 4-Mar-04  

109 5 3 Corporate| concept work 6-May-07  

112 5 3 Corporate| BASES 12-Dec-04  

111 5 3 Corporate| Magazine Index 20-Oct-07  

110 5 3 Corporate| Order Track 2-May-04  

50 2 3 Corporate Channel 15-May-04  

Page 7: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Relational Database

Page 7

Tables are related by common fields.

Page 8: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.Page 8

subscribedProductID productID deliveryTypeID subscribedProductName startEffectiveDate endEffectiveDate

42 2 3 Secret Shopper 4-Mar-04  

109 5 3 Corporate| concepts work 6-May-07  

112 5 3 Corporate| BASES 12-Dec-04  

111 5 3 Corporate| Magazine Index 20-Oct-07  

110 5 3 Corporate| Order Track 2-May-04  

50 2 3 CorporateChannel 15-May-04  

productID productTypeID productName 1 1 Measurement2 1 Consumer Solutions3 1 Astra Applications

4 1 Assortment Space5 1 Customized Research7 1 Newspaper 8 5 Television9 5 Radio10 5 Magazine

productTypeID productTypeName1 Retail2 Consumer3 Mobile4 Print5 Media

deliveryTypeID deliveryTypeDescription1 Database2 Report3 Application

SubscribedProduct

Product

ProductType

DeliveryType

pk fk fk

pk fk pk

pk

Relational Database

Primary & Foreign Keys Create Relationships

Page 9: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

Normalization

Page 10: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.10

Table Design - Normalization

• Advantages:

• Data redundancy can be reduced.

• Efficient disk space usage

• Increase efficiency of database updates

• Increase data integrity.

• Minimize unwanted side effects of database updates, inadvertent deletions or insertion errors.

• Disadvantages:

• Requires more complicated SQL coding.

• The more tables you have to join to retrieve the data the slower your query runs.

• Can increase I/O and CPU overhead. Reduced database performance.

• Normalization is a set of guidelines (steps) used to optimally design a database to reduce redundant data and modification anomalies.

Page 11: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.11

First Normal Form• A table is said to be in First Normal Form if:

• The Table does not contain any repeating groups.

• Each column has a unique name.

• The order of the columns doesn’t matter.

• No two rows may be identical.

• Each cell must contain a single value.

Vendor

VendorContact NamePhoneComponentPrice

Vendor Contact Name Phone Components Sold Prices

Cable Specialists Dennis Limanek 321-985-9658 Flux Capacitor, Fuel Cell 5.06, 987.65

Switched Components Inc. Sharon Linnell 659-854-9658 Inverter, Steel Enclosure 5.02, 51.23

GenCo Frank Barbuto 517-711-1547 Cell Housing, Base Slab 9.50,18.77

Inverter Supplies Lisa Allega 123-145-9652 Breaker Board 32.20

Stabilized Switching Inc Susan McMahon 652-451-8522 DC Switch, Transformer 12.00,13.25

Component Source Paul Butot 470-256-9853 Conduit Tray 29.98

Vendor may supply many parts.•Vendor Table Data

Page 12: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.12

First Normal Form

Vendor

NameContact NamePhoneComponentPrice

Vendor

VendorIDVendorNameVendorFirstNameVendorLastNamePhone

VendorComponent

VendorIDComponentPrice

• To put the table in 1NF we will break the data into two separate tables.

VendorID VendorName VendorFirstName VendorLastName Phone

1 Cable Specialists Dennis Limanek 321-985-9658

2 Switched Components Inc. Sharon Linnell 659-854-9658

3 GenCo Frank Barbuto 517-711-1547

4 Inverter Supplies Lisa Allega 123-145-9652

5 Stabilized Switching Inc Susan McMahon 652-451-8522

6 Component Source Paul Butot 470-256-9853

VendorID Component Price

1 Flux Capacitor 5.06

1 Fuel Cell 987.65

2 Inverter 5.02

2 Steel Enclosure 51.23

3 Cell Housing 9.50

3 Base Slab 18.77

4 Breaker Board 32.20

5 DC Switch 12.00

5 Transformer 13.25

6 Conduit Tray 29.98

Vendor

VendorComponent

Page 13: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.13

First Normal Form

• We added primary and foreign key fields to the tables.

• Primary Key Uniquely identifies a row, record in parent table.

• Foreign Key Matching row in another table, record in child table.

• Primary – Foreign keys form the One to Many relationships between tables.

Vendor

VendorIDVendorNameVendorFirstNameVendorLastNamePhone

VendorComponent

VendorID

ComponentPrice

Parent Table

Dependent/Child Table

Foreign KeyPrimary Key

Page 14: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.14

Second Normal Form

• A Table is in Second Normal Form if it is in 1NF and every • Non-Keyed column is fully dependent on the entire primary key.

Warehouse

WarehouseIDNameManagerPhoneFaxAddressCityProvincePostal Code

Inventory

ComponentIDWarehouseIDDescriptionWeightStockedQty

• Are these tables in Second Normal Form?

Page 15: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.15

Second Normal Form

• A Table is in Second Normal Form if it is in First Normal Form• And every Non-Keyed column is fully dependent on the entire primary key.

Warehouse

WarehouseIDNameManagerPhoneFaxAddressCityProvincePostal Code

Inventory

ComponentIDWarehouseIDDescriptionWeightStockedQty

• The Description and Weight fields are dependent only on the ComponentID key. Neither have anything to do with WarehouseID.

NO

•How do we fix it?

Page 16: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.16

Second Normal Form• A Table is in Second Normal Form if it is in First Normal Form• And every Non-Keyed column is fully dependent on the entire primary key.

• To put the tables in 2NF we put the Description and Weight fields into a new table named Component.

• Description and Weight are fully dependent on the primary key of the Component table (ComponentID)

• StockedQty is fully dependant on the primary key of Inventory (ComponentID, WarehouseID).

Inventory

ComponentIDWarehouseIDStockedQty

Component

ComponentIDDescriptionWeight

Inventory

ComponentIDWarehouseIDDescriptionWeightStockedQty

Warehouse

WarehouseIDNameManagerPhoneFaxAddressCityProvincePostal Code

Page 17: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.17

Third Normal Form

• The key, the whole key, and nothing but the key.

• A Table is in Third Normal Form if it is in Second Normal Form and every Non-Keyed Column is NOT dependent on any other Non-Keyed column.• Look for calculated fields.

• Look for non-key fields that serve as a primary key in another table.

•Product

•ProductID•FuelSourceID•ProductCode•ProductDescription•ProductPrice•PowerRating•Voltage•Frequency•ShippingCost•Weight

• Shipping Cost = (Weight * Carrier Mileage rate * Mileage) +• Carrier Fixed Rate + Delivery Method Charge• Weight = Sum (Weight of all Components)

Page 18: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.18

Can a database be Too Normalized?

• When designing a database you need to keep two important objectives in mind:

• 1. Keep your database free of modification anomalies

• 2. Speed

• Unfortunately, these are two competing objectives.

• To make sure modification anomalies don’t corrupt your data, you should normalize your Tables.

• However, separating data into different Tables will slow operations.

• You need to use good judgment and common sense to arrive at a compromise to provide acceptable data integrity and performance.

Page 19: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

Structure of an ORACLE Database

Page 20: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Database Object Hierarchy

Database

Tablespace

Table

Index View

Page 20

Page 21: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Oracle Database

• Oracle uses the word database to mean the physical and logical structure that you use to store information.

• In an oracle database you can create many different database objects (tables, views, indexes, etc.) All objects are stored in this one database.

• Internally, the Oracle database is divided into a System Tablespace, and one or more User Tablespaces.

• The System Tablespace holds the Oracle Catalog rows. The User Tablespace holds the rows of all User Tables.

users01.dbf users02.dbf system01.dbf

Users Tablespace System Tablespace

Page 21

Page 22: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Oracle Tablespace

• Tables reside in tablespaces. Tablespaces reside in databases.

• Oracle stores data logically in tablespaces and physically in datafiles.

• A tablespace may contain multiple tables.

• All databases have at least one tablespace, the System Tablespace, which Oracle creates automatically when you create the database.

Page 22

Page 23: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

What is Structured Query Language?

Page 24: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Structured Query Language

Data Control

(DCL)

• Grant• Revoke

User Privileges

Data Definition

(DDL)

• Create• Alter• Drop

Tables, Views,

Constraints

Data Manipulation (DML)

• Select• Insert• Update• Delete

Retrieve and

Manipulate Data

• SQL is the language most commonly used to create and process data in relational databases.

• SQL can be used with Access, DB2, MySQL, Oracle, MS SQL Server, Sybase, or any other relational database.

Page 24

Page 25: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

A Little Practice1. To count the rows in a table, use the following command:

Select count(*) from table_name;

2. To view the rows in a table, use the following command:

Select * from table_name;

3. To view the definition of the table, use the following command:

Describe table_name;

Page 25

Page 26: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

Creating Database Tables

Page 27: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Creating Tables• A table contains many columns. Each column must include a Data Type, Value

Set (optional), and a Mandatory indicator.

• Valid Oracle Data Types include Number, VarChar2, Char, and Date.

• Value Sets can include itemized values and ranges.

• Mandatory fields cannot be Null.

Attribute Data Type Mandatory

ProductID INTEGER yes

ProductTypeID INTEGER yes

ProductName VARCHAR2(100) yes

Product Table

Page 27

Note: Use the “describe” SQL command to display the table definition in the Oracle catalog:

For example: describe Product;

Page 28: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Common Oracle Datatypes Datatype Parameters Example Description

VARCHAR2(n) n = 1 to 4,000 VARCHAR2(25) Text string with a variable length. Specify the maximum length (n) when defining the column. If your data is shorter than the maximum size, Oracle adjusts the length of the column to the size of the data, which is a great space-saver.

NUMBER(p,s) p = 1 to 38,

s = -84 to 127

NUMBER(10,2) Use this datatype only for numbers. Specify the precision (p), which is the number of digits, and the scale (s), which is the number of digits to the right of the decimal place. Oracle truncates data that doesn’t fit into the scale.

If you use INTEGER as the datatype, Oracle will create the field with a datatype of Number(38).

DATE None DATE Use this datatype for Date, Time and Timestamp

CHAR(n) n = 1 to 2000 CHAR(14) Text string with a fixed length.

Page 28

Page 29: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Creating TablesOracle uses Structured Query Language (SQL) to create tables.

create table ProductType (

productTypeID INTEGER not null,

productTypeName VARCHAR2(50) not null,

constraint pkproductType primary key (productTypeID)

);

create table Product (

productID INTEGER not null,

productTypeID INTEGER not null,

productName VARCHAR2(100) not null,

constraint pkproduct primary key (productID),

constraint fkproduct_producttype foreign key (productTypeID)

references ProductType (productTypeID)

);

Page 29

Page 30: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Create Table

As you create Oracle Tables and Indexes, you must provide a valid name for the object. These names must adhere to the following rules:

 1. Names must be from 1 to 30 characters long.

 2. Names can be case sensitive depending on deployment. Our Oracle server is not case sensitive.

 3. A name must begin with an alphabetic character.

 4. Names can only contain alphanumeric characters _, $, and #.

 5. A name cannot be an Oracle reserved word.

Page 30

For a listing of Oracle reserved words:

http://download.oracle.com/docs/cd/B19306_01/em.102/b40103/app_oracle_reserved_words.htm

Page 31: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

Preserving Data Integrity

Page 32: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Column Domain ConstraintsYou can constrain column values in a table to a particular range.

The column constraint will be validated when a column value is updated or inserted.

create table NielsenUser (

nielsenUserID INTEGER not null,

userFirstName VARCHAR2(50) not null,

userLastName VARCHAR2(50) not null,

userDepartment VARCHAR2(50) not null,

userLocation VARCHAR2(50),

hourlyRate NUMBER(7,2) not null,

overtimeRate NUMBER(7,2) not null,

workPhone VARCHAR2(25),

mobilePhone VARCHAR2(25),

email VARCHAR2(50),

constraint pkNielsenUser primary key (nielsenUserID),

constraint CHECK_hourlyRate Check (hourlyRate > 45));

Page 32

Page 33: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Column Domain Constraints

Page 33

If you try to enter an hourly rate less than 45, you will receive an error.

Page 34: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Referential Integrity

Referential Integrity

“Thou shall not create orphans.”

Every child (foreign key) must have a matching parent (primary key).

You can not delete a parent if there is a matching child.

You can not add a child record if you do not have a matching parent record.

Primary Key: CustomerIDForeign Key: CustomerTypeID

Primary Key: ProductID

Foreign Key: ModalityID

Page 34

Parent Table Child TableParent & Child Table

Primary Key: UserIDForeign Key: CustomerID

Primary Key: CustomerTypeID

Referential Integrityhelps to maintain

data integrity.

Page 35: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

In the Customer table change customerName to “Avon Inc” for CustomerID 1.

Delete UserID 1 from the Users Table.

Add CustomerID 8 to the Customer Table.Allowed

Referential Integrity

Page 35

customerID customerTypeID customerName customerSymbol1 2 Avon Products Inc. AVP2 2 Church & Dwight Co. Inc. CHD3 2 Kimberly-Clark KMB4 2 Pepsico, Inc. PEP5 2 McDonald's Corp. MCD6 2 The Coca-Cola Company KO7 2 Kellogg Co. K

userID customerID street city postalcode firstName lastName22 1 11873 Springs Rd New York 10105-0196 Betty Smith39 1 440 W Laurel Ave New York 10105-0196 Holly Terry

148 2 320 Beard Creek Rd Princeton 08543-5297 Martha Johnson227 2 2003 Bluegrass Cir Princeton 08543-5297 Elizabeth Pope75 3 718 Avenida de Independence Dallas 75261-9100 Miguel Cortes

100 3 300 Highway 10 E Dallas 75261-9100 James Kellock171 4 3800 Eastside Hwy New York 10577 Lily Parker139 5 718 Avenida de Independence Oak Brook 60523 Miguel Cortes190 5 1756 Park Ave Oak Brook 60523 Andrea Allen69 6 67 Oneida Street Atlanta 30313 Ronnie Fischer

Child Table: Users

Parent Table: Customer

Page 36: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Change CustomerID 1 to CustomerID 2 in the Customer Table.

Delete CustomerID 3 from the Customer Table.

Add UserID 999 with a CustomerID 8 to the Users Table.Not Allowed

Referential Integrity

Page 36

customerID customerTypeID customerName customerSymbol1 2 Avon Products Inc. AVP2 2 Church & Dwight Co. Inc. CHD3 2 Kimberly-Clark KMB4 2 Pepsico, Inc. PEP5 2 McDonald's Corp. MCD6 2 The Coca-Cola Company KO7 2 Kellogg Co. K

userID customerID street city postalcode firstName lastName22 1 11873 Springs Rd New York 10105-0196 Betty Smith39 1 440 W Laurel Ave New York 10105-0196 Holly Terry

148 2 320 Beard Creek Rd Princeton 08543-5297 Martha Johnson227 2 2003 Bluegrass Cir Princeton 08543-5297 Elizabeth Pope75 3 718 Avenida de Independence Dallas 75261-9100 Miguel Cortes

100 3 300 Highway 10 E Dallas 75261-9100 James Kellock171 4 3800 Eastside Hwy New York 10577 Lily Parker139 5 718 Avenida de Independence Oak Brook 60523 Miguel Cortes190 5 1756 Park Ave Oak Brook 60523 Andrea Allen69 6 67 Oneida Street Atlanta 30313 Ronnie Fischer

Child Table: Users

Parent Table: Customer

Page 37: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Adding Constraintscreate table Users (

userID INTEGER not null,

customerID INTEGER not null,

provinceID INTEGER not null,

roleID INTEGER not null,

street VARCHAR2(100),

city VARCHAR2(50),

postalCode VARCHAR2(25),

firstName VARCHAR2(50),

lastName VARCHAR2(50),

phone VARCHAR2(25),

email VARCHAR2(50),

fax VARCHAR2(25),

constraint pkusers primary key (userID),

constraint fkuser_customer foreign key (customerID) references Customer (customerID));

Page 37

Page 38: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Implementing Referential IntegrityDELETE CASCADEWhen rows of a Parent Table are deleted, all associated Child Table rows are also deleted.

Is this a good thing to do?

Page 38

create table Users (

userID INTEGER not null,

customerID INTEGER not null,

provinceID INTEGER not null,

roleID INTEGER not null,

street VARCHAR2(100),

fax VARCHAR2(25),

constraint pkusers primary key (userID),

constraint fkuser_customer foreign key (customerID) references Customer (customerID)

on delete cascade);

Page 39: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Implementing Referential Integrity

You can also alter the Tables and add the referential integrity rules.

To Create the Primary Key and Foreign Key for the Customer and User Tables:

ALTER TABLE CustomerADD CONSTRAINT pkCustomer PRIMARY KEY (CustomerID);

ALTER TABLE Users ADD CONSTRAINT fkCustomer_Users FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID);

Page 39

Page 40: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Using Primary and Foreign Keys

• Use the same field name for both the primary and foreign key

• Names should be descriptive

• Keep the same data types between primary and foreign keys

• Keys should be numeric

• Improve load performance by adding constraints after the data is loaded

Page 40

When using primary and foreign keys remember :

Page 41: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

•Confidential & ProprietaryCopyright © 2009 The Nielsen Company

Alter Table - ExamplesTo add a column to the Product Table: 

ALTER TABLE ProductADD (IssueDate Date);

 To increase the column size to 60 characters: 

ALTER TABLE ProductMODIFY (ProductNameVARCHAR(100));

 To set the default value of a column. 

ALTER TABLE IncidentMODIFY (IncidentStatusID INTEGER DEFAULT 1);

 To drop a referential integrity constraint on a table: 

ALTER TABLE Product DROP CONSTRAINT pkProduct CASCADE;

 

Note: The CASCADE option drops any foreign keys that reference the primary key.

ALTER TABLE ProductDROP CONSTRAINT fkProduct_ProductType;

Page 41

Page 42: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

Improving Performance

Page 43: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Indexes for Performance

Primary Key Constraints Query Performance

Disk Space RequirementsLocks during Update

• Oracle provides two types of indexes: Unique and Non-unique.

• Unique indexes enforce unique key constraints and improve query performance.

• Non-unique indexes improve query performance.

• Indexes are implemented internally as B-tree structures.

Index rules include:

• An Order By statement in a Select statement can reference any column in a table – whether or not the column is indexed.

• The maximum number of columns in an index is 16.

• An index does not store Null values.

• An index can be created only for a Table, not a View.

Page 43

Page 44: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Create Index

<JensenJensen

CREATE INDEX ULastName on Users (LastName);

JensenMonroeWithrow

<BlackmanBlackmanHarris

AdamsAllen

BlackmanDoblerEinstein

HarrisJanus

JensenMiller

MonroeThomasStevens

WithrowWronski

Jensen - RowID

Miller - RowID

Leaf Blocks

Branch Blocks

Oracle uses B-Tree indexes that are balanced to equalize access time to any row.

Branch blocks point to lower level index blocks. The lowest level index blocks (leaf blocks) contain the corresponding RowID that is used to locate the actual row.

Page 44

Page 45: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Create Index

CREATE UNIQUE INDEX idxCustomerName ON Customer (customerName);

CREATE INDEX idxCity ON Users (city);

• When you create an Index, Oracle automatically allocates the index data in the database.

• Unique indexes enforce unique key constraints and improve query performance.

• Non-unique indexes improve query performance.

Page 45

Page 46: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

Database Catalog

Databases are Self Describing

Page 47: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Oracle Catalog

CATALOG

Relational Objects

Create Database

Create Table

Create View

Create Index

Databases

Tables

Columns Keys

Views

Indexes

• The Catalog holds all database objects.

• The Catalog is a set of Relational Tables.

• The Catalog can be queried to gather information.

• The Catalog can only be updated with DDL commands. Update, Insert and Delete SQL commands cannot be issued “directly” against the catalog.

A Database is self-describing. All the information about the database is stored in the database.

Page 47

Page 48: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Oracle Catalog - Describe

DESCRIBE Customer;

Page 48

Page 49: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Oracle Catalog

DBA Catalog versus USER Catalog

• For MANY of the examples we will look at, there is a DBA and a USER view.

• For example: DBA_Catalog and USER_Catalog view.

• As you would guess, the DBA views are only available if you have DBA privileges.

• The type of data shown by each view is the same. The difference is that the DBA view will show the data for ALL users and the USER view will show the data only for the current user.

Page 49

Page 50: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Oracle Catalog

USER_CATALOG: Contains one row for every Table or View owned by the current user.

SELECT *

FROM User_Catalog;

Note: Use this User_Catalog query to determine if all the Tables in the next workshop are created successfully.

Page 50

TABLE_NAME TABLE_TYPE

CUSTOMERTYPE TABLE

CUSTOMER TABLE

GEOGRAPHICREGION TABLE

COUNTRY TABLE

PROVINCE TABLE

ROLES TABLE

USERS TABLE

DELIVERYTYPE TABLE

PRODUCTTYPE TABLE

PRODUCT TABLE

SUBSCRIBEDPRODUCT TABLE

PROCESS TABLE

SUBPROCESS TABLE

FACTORYSCHEDULE TABLE

FACTORY TABLE

SUBSCRIBEDPRODUCTUSERS TABLE

LOGONEVENT TABLE

SCHEDMAINT TABLE

INCIDENTPRIORITY TABLE

INCIDENTCATEGORY TABLE

INCIDENTTYPE TABLE

INCIDENTSTATUS TABLE

INCIDENT TABLE

CORPORATEUSER TABLE

Page 51: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Oracle CatalogUSER_CONSTRAINTS: Contains a description of the referential constraints placed on Tables in the Catalog. Search this Table on the Table_Name column. For example, Where Table_Name = “PRODUCT”.

USER_CONS_COLUMNS: Contains rows that match the constraint name to Table columns.

SELECT C.owner, C.constraint_name, constraint_type, C.table_name, column_nameFROM user_constraints C, user_cons_columns CCWHERE C.owner = CC.owner and

C.constraint_name = CC.constraint_name andC.table_name = CC.table_name andC.table_name = 'PRODUCT';

Page 51

OWNER CONSTRAINT_NAME CONSTRAINT_TYPE TABLE_NAME COLUMN_NAME

CORPORATEOLTP SYS_C0030667 C PRODUCT PRODUCTID

CORPORATEOLTP SYS_C0030668 C PRODUCT PRODUCTTYPEID

CORPORATEOLTP SYS_C0030669 C PRODUCT PRODUCTNAME

CORPORATEOLTP PKPRODUCT P PRODUCT PRODUCTID

CORPORATEOLTP FKPRODUCT_PRODUCTTYPE R PRODUCT PRODUCTTYPEID

Page 52: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Oracle Catalog

SELECT COLUMN_ID, COLUMN_NAME,DATA_TYPE,DATA_LENGTH,DATA_PRECISION,DATA_SCALE,NULLABLE

FROM USER_TAB_COLUMNSWHERE TABLE_NAME = 'PRODUCT'ORDER BY COLUMN_ID;

USER_TABLES: Contains one row for each table in the Catalog. Only tables for the current user will be listed. For example, Where Owner = ‘CORPORATEOLTP’.

USER_TAB_COLUMNS: Contains one row for every column of each table including the columns of the Catalog tables.

Page 52

COLUMN_ID COLUMN_NAME DATA_TYPE DATA_LENGTH DATA_PRECISION DATA_SCALE NULLABLE

1 PRODUCTID NUMBER 22 0 N

2 PRODUCTTYPEID NUMBER 22 0 N

3 PRODUCTNAME VARCHAR2 100 N

Page 53: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Oracle CatalogUSER_INDEXES: Contains one row for every index, including the indexes on Catalog tables.

USER_IND_COLUMNS: Contains rows that match the index name to Table columns.

SELECT Index_Name, Index_Name, Table_Name, Column_Name

FROM USER_IND_COLUMNS

WHERE Table_Name = 'CUSTOMER';

Page 53

INDEX_NAME INDEX_NAME TABLE_NAME COLUMN_NAME

PKCUSTOMER PKCUSTOMER CUSTOMER CUSTOMERID

IDXCUSTOMERNAME IDXCUSTOMERNAME CUSTOMER CUSTOMERNAME

Page 54: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Oracle CatalogUSERS_VIEWS: Contains one or more rows for each view. The text of each View in the Catalog is kept in this table.

SELECT View_Name, Text

FROM USER_Views;

Note: The text is truncated. To avoid this you must first …Set Long 8192

Run the SQL again. This time you will get …

VIEW_NAME TEXT

SAMPLE Select customername, customersymbol, billingcity, billingprovince, billingpostalcode…….

VIEW_NAME TEXT

SAMPLE Select customername,customersymbol,billingcity,billingprovince,billingpostalcode,userid,firstname,lastname from customer c, users u where c.customerid = u.customerid;

Page 54

Page 55: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Oracle Catalog - Quick ReferenceCatalog Table Name Purpose

USER_CATALOG Contains one row for every Table or View in the Catalog. Use this catalog table to get a list of all Tables attached to an Owner, for example ’CORPORATEOLTP’.

USER_CONSTRAINTS Contains a description of the referential constraints placed on Tables in the Catalog. Search this Table on the Table_Name column. For example,

Where Table_Name = ‘CUSTOMER’.

USER_CONS_COLUMNS Contains rows that match the constraint name to Table columns.

USER_INDEXES Contains one row for every index, including the indexes on Catalog tables.

USER_IND_COLUMNS Contains rows that match the index name to Table columns.

USER_TABLES Contains one row for each table in the Catalog. Search this table on the Owner column. For example, Where Owner = ‘CORPORATEOLTP’.

USER_TAB_COLUMNS Contains one row for every column of each table including the columns of the Catalog tables.

USER_USERS Contains a row for each User in the Catalog. UserIDs and Passwords are kept in this table. Passwords are encrypted.

USER_VIEWS Contains one or more rows for each view. The text of each View in the Catalog is kept in this table.

USER_DATA_FILES Contains the name of each datafile, its size, and its associated tablespace.

Page 55

Page 56: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Class Discussion – Review Key Concepts

• How data is stored in a relational database?

• What is the purpose primary and foreign keys?

• What is referential integrity? Why is it important?

• What is the role of indexes?

• What is SQL?

• What is the purpose of the Oracle Catalog?

Page 56

Page 57: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

Workshop

Page 58: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Workshop - Create Tables1. Add the following tables to the database using a script:

yourlastname_F_Schedule yourlastname_LogonEvent yourlastname_Survey

When you code the Create Table statements, make sure that you code Parent tables before you code Child Tables (always create Parents before Children).

2. In the same file, create a series of Drop Table statements. They will take the format: Drop Table tablename; Place the drop statements before the create statements. Drop all Tables in the proper sequence (always drop Children before Parents). Your file will now resemble this:

• Drop Table users;• Drop Table customer;• Create Table users…• Create Table customer….• Create Index idx_billingcity….

Then save the _CreateSchema.sql file. (See Handout A as an example.)

3. Test your create schema script.

Page 58

Page 59: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Add these tables to the Database

Column Specifications

yourlastname_F_Schedule

Page 59

Column Name Null? TypeF_SCHEDULEID (PK) NOT NULL INTEGERSUBPROCESSID NOT NULL INTEGERPRODUCTTYPEID NOT NULL INTEGER

PROCESSID NOT NULL INTEGERLEVELNUMBER NOT NULL INTEGERDAYDESCRIPTION NOT NULL VARCHAR2(50)ESTIMATEDSTARTDATE NOT NULL DATEESTIMATEDENDDATE NOT NULL DATEESTIMATEDELAPSEMINUTES NOT NULL NUMBER(38)

Page 60: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Add these tables to the Database

Column Specifications

yourlastname_LogonEvent

Page 60

Column Name Null? TypeLOGONEVENTID (PK) NOT NULL INTEGERREQUIREDPRODUCTUSERSID NOT NULL INTEGERLOGONDATE NOT NULL DATELOGOFFDATE NOT NULL DATEDATABASEREADS NOT NULL INTEGERDATABASEWRITES NOT NULL INTEGERRESPONSETIME NOT NULL INTEGERDBRESPONSETIME NOT NULL INTEGERNETWORKRESPONSETIME NOT NULL INTEGERMEMORYUSAGE NOT NULL INTEGERCPUUTILIZATION NOT NULL INTEGERDISKUTILIZATION NOT NULL INTEGERCONCURRENTUSERS NOT NULL INTEGER

Page 61: SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Add these tables to the Database

Column Specifications

yourlastname_Survey

Page 61

Column Name Null? TypeSURVEYID (PK) NOT NULL INTEGERCUSTOMERID NOT NULL INTEGERUSERID NOT NULL INTEGERREQUIREDPRODUCTID NOT NULL INTEGERSURVEYDATE DATEQ1 INTEGERQ2 INTEGERQ3 INTEGERQ4 INTEGERQ5 INTEGERQ6 INTEGERQ7 INTEGER