Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in."— Presentation transcript:

1 SQL Training Database Concepts

2 Confidential & Proprietary Copyright © 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:

3 Confidential & Proprietary Copyright © 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

4 What is a Relational Database?

5 Confidential & Proprietary Copyright © 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 productIDproductTypeIDproductName 11Floor Measurement 21Consumer Solutions 31Astra Applications 41Assortment Space 51Customized Research 71Newspaper 85Television 95Radio 105Magazines

6 Confidential & Proprietary Copyright © 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 subscribedProductIDproductIDdeliveryTypeIDsubscribedProductNamestartEffectiveDateendEffectiveDate 4223Secret Shopper4-Mar-04 10953Corporate| concept work6-May-07 11253Corporate| BASES12-Dec-04 11153Corporate| Magazine Index20-Oct-07 11053Corporate| Order Track2-May-04 5023Corporate Channel15-May-04

7 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Relational Database Page 7 Tables are related by common fields.

8 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Page 8 subscribedProductIDproductIDdeliveryTypeIDsubscribedProductNamestartEffectiveDateendEffectiveDate 4223Secret Shopper4-Mar-04 10953Corporate| concepts work6-May-07 11253Corporate| BASES12-Dec-04 11153Corporate| Magazine Index20-Oct-07 11053Corporate| Order Track2-May-04 5023CorporateChannel15-May-04 productIDproductTypeIDproductName 11Measurement 21Consumer Solutions 31Astra Applications 41Assortment Space 51Customized Research 71Newspaper 85Television 95Radio 105Magazine productTypeIDproductTypeName 1Retail 2Consumer 3Mobile 4Print 5Media deliveryTypeIDdeliveryTypeDescription 1Database 2Report 3Application SubscribedProduct Product ProductType DeliveryType pk fk pk fk pk Relational Database Primary & Foreign Keys Create Relationships

9 Normalization

10 Confidential & Proprietary Copyright © 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.

11 Confidential & Proprietary Copyright © 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 Contact Name Phone Component Price VendorContact NamePhoneComponents SoldPrices Cable SpecialistsDennis Limanek321-985-9658Flux Capacitor, Fuel Cell5.06, 987.65 Switched Components Inc.Sharon Linnell659-854-9658Inverter, Steel Enclosure5.02, 51.23 GenCoFrank Barbuto517-711-1547Cell Housing, Base Slab9.50,18.77 Inverter SuppliesLisa Allega123-145-9652Breaker Board32.20 Stabilized Switching IncSusan McMahon652-451-8522DC Switch, Transformer12.00,13.25 Component SourcePaul Butot470-256-9853Conduit Tray29.98 Vendor may supply many parts. Vendor Table Data

12 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. 12 First Normal Form Vendor Name Contact Name Phone Component Price Vendor VendorID VendorName VendorFirstName VendorLastName Phone VendorComponent VendorID Component Price To put the table in 1NF we will break the data into two separate tables. VendorIDVendorName VendorFirstNameVendorLastName Phone 1Cable SpecialistsDennisLimanek321-985-9658 2Switched Components Inc.SharonLinnell659-854-9658 3GenCoFrankBarbuto517-711-1547 4Inverter SuppliesLisaAllega123-145-9652 5Stabilized Switching IncSusanMcMahon652-451-8522 6Component SourcePaulButot470-256-9853 VendorIDComponentPrice 1Flux Capacitor5.06 1Fuel Cell 987.65 2Inverter5.02 2Steel Enclosure51.23 3Cell Housing9.50 3Base Slab18.77 4Breaker Board32.20 5DC Switch12.00 5Transformer13.25 6Conduit Tray29.98 Vendor VendorComponent

13 Confidential & Proprietary Copyright © 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 VendorID VendorName VendorFirstName VendorLastName Phone VendorComponent VendorID Component Price Parent Table Dependent/Child Table Foreign Key Primary Key

14 Confidential & Proprietary Copyright © 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 WarehouseID Name Manager Phone Fax Address City Province Postal Code Inventory ComponentID WarehouseID Description Weight StockedQty Are these tables in Second Normal Form?

15 Confidential & Proprietary Copyright © 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 WarehouseID Name Manager Phone Fax Address City Province Postal Code Inventory ComponentID WarehouseID Description Weight StockedQty 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?

16 Confidential & Proprietary Copyright © 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 ComponentID WarehouseID StockedQty Component ComponentID Description Weight Inventory ComponentID WarehouseID Description Weight StockedQty Warehouse WarehouseID Name Manager Phone Fax Address City Province Postal Code

17 Confidential & Proprietary Copyright © 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)

18 Confidential & Proprietary Copyright © 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.

19 Structure of an ORACLE Database

20 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Database Object Hierarchy Database Tablespace Table IndexView Page 20

21 Confidential & Proprietary Copyright © 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

22 Confidential & Proprietary Copyright © 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

23 What is Structured Query Language?

24 Confidential & Proprietary Copyright © 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

25 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. A Little Practice 1.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

26 Creating Database Tables

27 Confidential & Proprietary Copyright © 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 TypeMandatory 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;

28 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Common Oracle Datatypes DatatypeParametersExampleDescription VARCHAR2(n)n = 1 to 4,000VARCHAR2(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). DATENoneDATEUse this datatype for Date, Time and Timestamp CHAR(n)n = 1 to 2000CHAR(14)Text string with a fixed length. Page 28

29 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Creating Tables Oracle uses Structured Query Language (SQL) to create tables. create table ProductType ( productTypeID INTEGERnot null, productTypeNameVARCHAR2(50) not null, constraint pkproductType primary key (productTypeID) ); create table Product ( productIDINTEGERnot null, productTypeIDINTEGERnot null, productNameVARCHAR2(100)not null, constraint pkproduct primary key (productID), constraint fkproduct_producttype foreign key (productTypeID) references ProductType (productTypeID) ); Page 29

30 Confidential & Proprietary Copyright © 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

31 Preserving Data Integrity

32 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Column Domain Constraints You 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 INTEGERnot null, userFirstNameVARCHAR2(50) not null, userLastNameVARCHAR2(50)not null, userDepartmentVARCHAR2(50)not null, userLocationVARCHAR2(50), hourlyRateNUMBER(7,2)not null, overtimeRateNUMBER(7,2)not null, workPhoneVARCHAR2(25), mobilePhoneVARCHAR2(25), emailVARCHAR2(50), constraint pkNielsenUser primary key (nielsenUserID), constraint CHECK_hourlyRate Check (hourlyRate > 45)); Page 32

33 Confidential & Proprietary Copyright © 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.

34 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. 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: CustomerID Foreign Key: CustomerTypeID Primary Key: ProductID Foreign Key: ModalityID Page 34 Parent Table Child Table Parent & Child Table Primary Key: UserID Foreign Key: CustomerID Primary Key: CustomerTypeID Referential Integrity helps to maintain data integrity.

35 Confidential & Proprietary Copyright © 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 customerIDcustomerTypeIDcustomerNamecustomerSymbol 12Avon Products Inc.AVP 22Church & Dwight Co. Inc.CHD 32Kimberly-ClarkKMB 42Pepsico, Inc.PEP 52McDonald's Corp.MCD 62The Coca-Cola CompanyKO 72Kellogg Co.K userIDcustomerIDstreetcitypostalcodefirstNamelastName 22111873 Springs RdNew York10105-0196BettySmith 391440 W Laurel AveNew York10105-0196HollyTerry 1482320 Beard Creek RdPrinceton08543-5297MarthaJohnson 22722003 Bluegrass CirPrinceton08543-5297ElizabethPope 753718 Avenida de IndependenceDallas75261-9100MiguelCortes 1003300 Highway 10 EDallas75261-9100JamesKellock 17143800 Eastside HwyNew York10577LilyParker 1395718 Avenida de IndependenceOak Brook60523MiguelCortes 19051756 Park AveOak Brook60523AndreaAllen 69667 Oneida StreetAtlanta30313RonnieFischer Child Table: Users Parent Table: Customer

36 Confidential & Proprietary Copyright © 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 customerIDcustomerTypeIDcustomerNamecustomerSymbol 12Avon Products Inc.AVP 22Church & Dwight Co. Inc.CHD 32Kimberly-ClarkKMB 42Pepsico, Inc.PEP 52McDonald's Corp.MCD 62The Coca-Cola CompanyKO 72Kellogg Co.K userIDcustomerIDstreetcitypostalcodefirstNamelastName 22111873 Springs RdNew York10105-0196BettySmith 391440 W Laurel AveNew York10105-0196HollyTerry 1482320 Beard Creek RdPrinceton08543-5297MarthaJohnson 22722003 Bluegrass CirPrinceton08543-5297ElizabethPope 753718 Avenida de IndependenceDallas75261-9100MiguelCortes 1003300 Highway 10 EDallas75261-9100JamesKellock 17143800 Eastside HwyNew York10577LilyParker 1395718 Avenida de IndependenceOak Brook60523MiguelCortes 19051756 Park AveOak Brook60523AndreaAllen 69667 Oneida StreetAtlanta30313RonnieFischer Child Table: Users Parent Table: Customer

37 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Adding Constraints create table Users ( userIDINTEGER not null, customerIDINTEGER not null, provinceIDINTEGER not null, roleIDINTEGER not null, streetVARCHAR2(100), cityVARCHAR2(50), postalCodeVARCHAR2(25), firstNameVARCHAR2(50), lastNameVARCHAR2(50), phoneVARCHAR2(25), emailVARCHAR2(50), faxVARCHAR2(25), constraint pkusers primary key (userID), constraint fkuser_customer foreign key (customerID) references Customer (customerID)); Page 37

38 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Implementing Referential Integrity DELETE CASCADE When 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 ( userIDINTEGER not null, customerIDINTEGER not null, provinceIDINTEGER not null, roleIDINTEGER not null, streetVARCHAR2(100), … faxVARCHAR2(25), constraint pkusers primary key (userID), constraint fkuser_customer foreign key (customerID) references Customer (customerID) on delete cascade);

39 Confidential & Proprietary Copyright © 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 Customer ADD CONSTRAINT pkCustomer PRIMARY KEY (CustomerID); ALTER TABLE Users ADD CONSTRAINT fkCustomer_Users FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID); Page 39

40 Confidential & Proprietary Copyright © 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 :

41 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Confidential & Proprietary Copyright © 2009 The Nielsen Company Alter Table - Examples To add a column to the Product Table: ALTER TABLE Product ADD (IssueDate Date); To increase the column size to 60 characters: ALTER TABLE Product MODIFY (ProductNameVARCHAR(100)); To set the default value of a column. ALTER TABLE Incident MODIFY (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 Product DROP CONSTRAINT fkProduct_ProductType; Page 41

42 Improving Performance

43 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Indexes for Performance Primary Key Constraints Query Performance Disk Space Requirements Locks 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

44 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Create Index <Jensen Jensen CREATE INDEX ULastName on Users (LastName); Jensen Monroe Withrow <Blackman Blackman Harris Adams Allen Blackman Dobler Einstein Harris Janus Jensen Miller Monroe Thomas Stevens Withrow Wronski 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

45 Confidential & Proprietary Copyright © 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

46 Database Catalog Databases are Self Describing

47 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Oracle Catalog 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

48 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Oracle Catalog - Describe DESCRIBE Customer; Page 48

49 Confidential & Proprietary Copyright © 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

50 Confidential & Proprietary Copyright © 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_NAMETABLE_TYPE CUSTOMERTYPETABLE CUSTOMERTABLE GEOGRAPHICREGIONTABLE COUNTRYTABLE PROVINCETABLE ROLESTABLE USERSTABLE DELIVERYTYPETABLE PRODUCTTYPETABLE PRODUCTTABLE SUBSCRIBEDPRODUCTTABLE PROCESSTABLE SUBPROCESSTABLE FACTORYSCHEDULETABLE FACTORYTABLE SUBSCRIBEDPRODUCTUSERSTABLE LOGONEVENTTABLE SCHEDMAINTTABLE INCIDENTPRIORITYTABLE INCIDENTCATEGORYTABLE INCIDENTTYPETABLE INCIDENTSTATUSTABLE INCIDENTTABLE CORPORATEUSERTABLE

51 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Oracle Catalog 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 = “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_name FROM user_constraints C, user_cons_columns CC WHERE C.owner = CC.owner and C.constraint_name = CC.constraint_name and C.table_name = CC.table_name and C.table_name = 'PRODUCT'; Page 51 OWNERCONSTRAINT_NAMECONSTRAINT_TYPETABLE_NAMECOLUMN_NAME CORPORATEOLTPSYS_C0030667CPRODUCTPRODUCTID CORPORATEOLTPSYS_C0030668CPRODUCTPRODUCTTYPEID CORPORATEOLTPSYS_C0030669CPRODUCTPRODUCTNAME CORPORATEOLTPPKPRODUCTPPRODUCTPRODUCTID CORPORATEOLTPFKPRODUCT_PRODUCTTYPERPRODUCTPRODUCTTYPEID

52 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Oracle Catalog SELECT COLUMN_ID, COLUMN_NAME, DATA_TYPE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE, NULLABLE FROM USER_TAB_COLUMNS WHERE 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_IDCOLUMN_NAMEDATA_TYPEDATA_LENGTHDATA_PRECISIONDATA_SCALENULLABLE 1PRODUCTIDNUMBER22 0N 2PRODUCTTYPEIDNUMBER22 0N 3PRODUCTNAMEVARCHAR2100 N

53 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Oracle Catalog 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. SELECT Index_Name, Index_Name, Table_Name, Column_Name FROM USER_IND_COLUMNS WHERE Table_Name = 'CUSTOMER'; Page 53 INDEX_NAME TABLE_NAMECOLUMN_NAME PKCUSTOMER CUSTOMERCUSTOMERID IDXCUSTOMERNAME CUSTOMERCUSTOMERNAME

54 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Oracle Catalog USERS_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_NAMETEXT SAMPLE Select customername, customersymbol, billingcity, billingprovince, billingpostalcode……. VIEW_NAMETEXT SAMPLE Select customername,customersymbol,billingcity,billingprovince,billingpostalcode,userid,firstname, lastname from customer c, users u where c.customerid = u.customerid; Page 54

55 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Oracle Catalog - Quick Reference Catalog Table NamePurpose USER_CATALOGContains 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_CONSTRAINTSContains 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_COLUMNSContains rows that match the constraint name to Table columns. USER_INDEXESContains one row for every index, including the indexes on Catalog tables. USER_IND_COLUMNSContains rows that match the index name to Table columns. USER_TABLESContains one row for each table in the Catalog. Search this table on the Owner column. For example, Where Owner = ‘CORPORATEOLTP’. USER_TAB_COLUMNSContains one row for every column of each table including the columns of the Catalog tables. USER_USERSContains a row for each User in the Catalog. UserIDs and Passwords are kept in this table. Passwords are encrypted. USER_VIEWSContains one or more rows for each view. The text of each View in the Catalog is kept in this table. USER_DATA_FILESContains the name of each datafile, its size, and its associated tablespace. Page 55

56 Confidential & Proprietary Copyright © 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

57 Workshop

58 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Workshop - Create Tables 1.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

59 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Add these tables to the Database Column Specifications yourlastname_F_Schedule Page 59 Column NameNull?Type F_SCHEDULEID (PK)NOT NULLINTEGER SUBPROCESSIDNOT NULLINTEGER PRODUCTTYPEIDNOT NULLINTEGER PROCESSIDNOT NULLINTEGER LEVELNUMBERNOT NULLINTEGER DAYDESCRIPTIONNOT NULLVARCHAR2(50) ESTIMATEDSTARTDATENOT NULLDATE ESTIMATEDENDDATENOT NULLDATE ESTIMATEDELAPSEMINUTESNOT NULLNUMBER(38)

60 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Add these tables to the Database Column Specifications yourlastname_LogonEvent Page 60 Column NameNull?Type LOGONEVENTID (PK)NOT NULLINTEGER REQUIREDPRODUCTUSERSIDNOT NULLINTEGER LOGONDATENOT NULLDATE LOGOFFDATENOT NULLDATE DATABASEREADSNOT NULLINTEGER DATABASEWRITESNOT NULLINTEGER RESPONSETIMENOT NULLINTEGER DBRESPONSETIMENOT NULLINTEGER NETWORKRESPONSETIMENOT NULLINTEGER MEMORYUSAGENOT NULLINTEGER CPUUTILIZATIONNOT NULLINTEGER DISKUTILIZATIONNOT NULLINTEGER CONCURRENTUSERSNOT NULLINTEGER

61 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Add these tables to the Database Column Specifications yourlastname_Survey Page 61 Column NameNull?Type SURVEYID (PK)NOT NULLINTEGER CUSTOMERIDNOT NULLINTEGER USERIDNOT NULLINTEGER REQUIREDPRODUCTIDNOT NULLINTEGER SURVEYDATE DATE Q1 INTEGER Q2 INTEGER Q3 INTEGER Q4 INTEGER Q5 INTEGER Q6 INTEGER Q7 INTEGER


Download ppt "SQL Training Database Concepts. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain how data is stored in."

Similar presentations


Ads by Google