Universitatea Politehnica Bucureşti - Facultatea de Automatica si Calculatoare. 4. Managing Data. Tables, Indexes and Constraints

Similar documents
Tuning Considerations for Different Applications Lesson 4

DBA_VIEWS DBA_SEQUENCES

Oracle9i DBA Fundamentals I

ENHANCING DATABASE PERFORMANCE

Creating and Managing Tables Schedule: Timing Topic

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

Oracle Tables TECHGOEASY.COM

Seminar: Presenter: Oracle Database Objects Internals. Oren Nakdimon.

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

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

Data Warehousing & Big Data at OpenWorld for your smartphone

Question: Which statement would you use to invoke a stored procedure in isql*plus?

Optimal Physical Database Design for Oracle8i

Course Contents of ORACLE 9i

RDBMS Topic 4 Adv. SQL, MSBTE Questions and Answers ( 12 Marks)

ABSTRACT INTRODUCTION. Bhaskar Himatsingka, Oracle Corporation & Juan Loaiza, Oracle Corporation

Correctexams.com. Exam :1Z0-031 Title:Oracle9i: DBA Fundamentals I Version Number:Version Last Verified and Updated on Jan 4, 2003

RNDr. Michal Kopecký, Ph.D. Department of Software Engineering, Faculty of Mathematics and Physics, Charles University in Prague

Question: 1 Identify three components of an Oracle instance for which you can change the size dynamically. (Choose three.)

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

Oracle Alter Table Add Unique Constraint Using Index Tablespace

ROLLBACK SEGMENTS. In this chapter, you will learn about: Rollback Segment Management Page 272

Oracle Tuning Pack. Table Of Contents. 1 Introduction. 2 Installation and Configuration. 3 Documentation and Help. 4 Oracle SQL Analyze

Oracle.ActualTests.1Z0-023.v by.Ramon.151q

NORAD DBControl Online Whitepaper

04 Storage management 15/07/17 12:34 AM. Storage management

Oracle ActualTests v by BeCKS

ORACLE 12C NEW FEATURE. A Resource Guide NOV 1, 2016 TECHGOEASY.COM

Advanced indexing methods Usage and Abusage. Riyaj Shamsudeen Ora!nternals

Tablespace Usage By Schema In Oracle 11g Query To Check Temp

Appendix C. Database Administration. Using SQL. SQL Statements. Data Definition Statements (DDL)

CHAPTER. Getting Started with the Oracle Architecture

DumpsKing. Latest exam dumps & reliable dumps VCE & valid certification king

Exam: 1Z Title : Oracle9i: Performance Tuning. Ver :

D B M G Data Base and Data Mining Group of Politecnico di Torino

Oracle DB-Tuning Essentials

6232B: Implementing a Microsoft SQL Server 2008 R2 Database

Chapter 4 Database Administration

1z Oracle9i Performance Tuning. Version 19.0

Oracle 1Z0-235 Exam Questions & Answers

Oracle 1Z0-031 Exam Questions & Answers

Exam : 1Z : Oracle 9i Database Fundamentals I. Title. Ver :

Indexes (continued) Customer table with record numbers. Source: Concepts of Database Management

Lab # 4. Data Definition Language (DDL)

CHAPTER4 CONSTRAINTS

Introduction to Computer Science and Business

CHAPTER: 4 ADVANCE SQL: SQL PERFORMANCE TUNING (12 Marks)

C Examcollection.Premium.Exam.58q

Data Definition Language (DDL)

Experiences of Global Temporary Tables in Oracle 8.1

Data Organization and Processing I

VerifiedDumps. Get the Valid and Verified Exam Questions & Answers Dump for 100% Pass

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Part 4: B-Tree Indexes

King Fahd University of Petroleum and Minerals

File Structures and Indexing

C. Use the TO_CHAR function around SYSDATE, that is, 1_date := TO_CHAR (SYSDATE).

EDUVITZ TECHNOLOGIES

Customer PTC E-Newsletter Date: 4/9/03

Course Outline and Objectives: Database Programming with SQL

Oracle Syllabus Course code-r10605 SQL

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C

Kathleen Durant PhD Northeastern University CS Indexes

Exam Name: Oracle 11i Applications DBA: Fundamentals I Exam Type Oracle Exam Code: 1z0-235 Total Questions: 108

5. Single-row function

Implementation of Database Systems David Konopnicki Taub 715 Spring Sources

DATA CONSTRAINT. Prepared By: Dr. Vipul Vekariya

Copyright 2013, Oracle and/or its affiliates. All rights reserved.

Oracle Database 11gR2 Optimizer Insights

Difficult I.Q on Databases, asked to SCTPL level 2 students 2015

SQL is an English like language consisting of commands to store, retrieve, maintain & regulate access to your database.

Oracle 1z z0-146 Oracle Database 11g: Advanced PL/SQL. Practice Test. Version QQ:

einfach. gut. beraten. How to reorganize and why? DOAG Conference + Exhibition , Nuremberg Klaus Reimers

Oracle Alter Table Add Primary Key Using Index

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

Oracle Database Performance Tuning, Benchmarks & Replication

Oracle DB-Tuning Essentials

: ADMINISTRATION I EXAM OBJECTIVES COVERED IN THIS CHAPTER:

Indexing. Jan Chomicki University at Buffalo. Jan Chomicki () Indexing 1 / 25

Lecture7: SQL Overview, Oracle Data Type, DDL and Constraints Part #2

Objectives. After completing this lesson, you should be able to do the following:

IT Certification Exams Provider! Weofferfreeupdateserviceforoneyear! h ps://

Oracle Data Pump Internals

RMOUG Training Days 2018

SecureFiles Migration O R A C L E W H I T E P A P E R F E B R U A R Y

Oracle Architectural Components

MySQL Introduction. By Prof. B.A.Khivsara

Oracle MOOC: SQL Fundamentals

Lecture7: SQL Overview, Oracle Data Type, DDL and Constraints Part #2

Table Compression in Oracle9i Release2. An Oracle White Paper May 2002

ORACLE VIEWS ORACLE VIEWS. Techgoeasy.com

SQL Coding Guidelines

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

ORACLE DATABASE 12C INTRODUCTION

.. Spring 2008 CSC 468: DBMS Implementation Alexander Dekhtyar..

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

Physical Schema Design. Storage structures Indexing techniques in DBS

Oracle Database 10g: Introduction to SQL

Storage hierarchy. Textbook: chapters 11, 12, and 13

Transcription:

4. Managing Data Tables, Indexes and Constraints 25.11.2009 Administrarea Bazelor de Date I 1

Overview Managing Tables Managing Indexes Managing Data Integrity Using Clusters and Index-Organized Tables

Managing Tables

Objectives After completing this lesson you should be able to do the following: Distinguishing between different Oracle data types Distinguish between an extended versus a restricted ROWID Creating tables using appropriate storage settings Manage storage structures within a table Reorganize, truncate, and drop a table Drop a column within a table Control the space used by tables Analyze tables to check integrity and migration Retrieve information about tables from the data dictionary

Storing User Data There are several methods of storing user data in Oracle: Regular table Partitioned table Index-organized table Cluster

Regular Table Partitioned Table Storing User Data Range partitioning Hash partitioning Composite partitioning Types of partitioning List partitioning Each partition is a segment and can be stored separately Index-Organized Table Like a heap table with a primary key index Clustered Table A table or group of tables that share the same data blocks Have a cluster key identify the rows that are stored together

Oracle Built-in in Data Types Data type User-defined Scalar Built-in Collection Relationship CHAR(N), NCHAR(N) VARCHAR2(N), NVARCHAR2(N) NUMBER(P,S) DATE RAW(N) BLOB, CLOB, NCLOB, BFILE LONG, LONG RAW ROWID VARRAY TABLE REF

Data Types for Storing Large Objects LONG, LONG RAW Single column per table Up to 2 gigabytes SELECT returns data Data stored in-line No object type support Sequential access to chunks LOB Multiple columns per table Up to 4 gigabytes SELECT returns locator Data stored in-line or out-of-line Supports object types Random access to chunks

ROWID Data Type Unique identifier for a row Not stored explicitly as a column value stored in indexes to specify rows with a given set of key values Used to locate a row the fastest means (Extended) ROWID Format OOOOOO FFF BBBBBB RRR Data object number Relative file number Block number Row number 10 bytes of storage Displayed by 18 characters

Example SQL> SELECT department_id, rowid FROM hr.departments; DEPARTMENT_ID ROWID ----------------------- ----------- 10 AAABQMAAFAAAAA6AAA 20 AAABQMAAFAAAAA6AAB 30 AAABQMAAFAAAAA6AAC Data object number Block number Relative file number Row number for the department with ID=10

Restricted ROWID Can identify rows within a segment Needs less space X BBBBBBBB. RRRR. FFFF Block number Row number File number Does not contain the data object number

Collections Collections are objects that contain objects. VARRAYs are ordered sets of elements containing a count and a limit. Nested tables are tables with a column or variable of the TABLE data type. VARRAY Nested table

Creating a Table CREATE TABLE employees( empno NUMBER(4), last_name VARCHAR2(30) deptno NUMBER(2)) PCTFREE 20 PCTUSED 50 STORAGE(INITIAL 200K NEXT 200K PCTINCREASE 0 MINEXTENTS 1 MAXEXTENTS 50) TABLESPACE data01; Minimum number of extents that is to be allocated Maximum number of extents that is to be allocated The percentage of increase in extent size after NEXT extent

Creating a Table: Guidelines Place tables in separate tablespaces To avoid/reduce fragmentation: Use locally-managed tablespaces Use a few standard extent sizes for tables Use the CACHE clause for frequently used, small tables.

Creating Temporary Tables Created using the GLOBAL TEMPORARY clause: CREATE GLOBAL TEMPORARY TABLE hr.employees_temp AS SELECT * FROM hr.employees; Tables retain data only for the duration of a transaction or session. The clauses that control the duration of the rows are: ON COMMIT DELETE ROWS: Rows are visible within the transaction (default) ON COMMIT PRESERVE ROWS: Rows are visible for the entire session DML locks are not acquired on the data. You can create indexes, views, and triggers on temporary tables.

Setting PCTFREE and PCTUSED Compute PCTFREE (Average Row Size Initial Row Size) * 100 Average Row Size Compute PCTUSED 100 PCTFREE Average Row Size * 100 Available Data Space AVERAGE ROW SIZE can be obtained using the ANALYZE TABLE command

Row Migration and Chaining Before update After update

Row Migration Row Migration and Chaining If PCTFREE too small => insufficient space in a block to accommodate a row that grows as a result of an update Oracle then moves the entire row to a new block Row Chaining Occurs when a row is too large to fit into any block eq: columns that are very long Oracle divides the tow into smaller chunks called row pieces Can be minimized by setting a higher block size

Copying an Existing Table CREATE TABLE new_emp STORAGE(INITIAL 200K NEXT 200K PCTINCREASE 0 MAXEXTENTS 50) NOLOGGING TABLESPACE data01 AS SELECT * FROM scott.employees;

Changing Storage and Block Utilization Parameters ALTER TABLE scott.employees PCTFREE 30 PCTUSED 50 STORAGE(NEXT 500K MINEXTENTS 2 MAXEXTENTS 100);

Manually Allocating Extents ALTER TABLE scott.employees ALLOCATE EXTENT(SIZE 500K DATAFILE /DISK3/DATA01.DBF ); Extents may need to be allocated manually: To control the distribution of extents of a table across files Before loading data in bulk to avoid dynamic extension of tables

Nonpartitioned Table Reorganization ALTER TABLE hr.employees MOVE TABLESPACE data1; A nonpartitioned table can be moved without having to run the Export or Import utility It also allows the storage parameters to be changed Useful when: Moving a table from one tablespace to another Reorganizing the table to eliminate row migration After moving a table you must rebuild its indexes

After inserts High Water Mark Extent ID 0 1 2 3 4 After deletes High water mark Extent ID 0 1 2 3 4 Used block Unused block Free space after delete

Finding the High Water Mark: DBMS_SPACE.UNUSED_SPACE TOTAL_BLOCKS UNUSED_BLOCKS Extent ID 0 1 2 3 4 High water mark LAST_USED_EXTENT_FILE_ID, LAST_USED_EXTENT_BLOCK_ID

Deallocation of Unused Space Before deallocation ALTER TABLE scott.employees DEALLOCATE UNUSED; High water mark After deallocation Used block Unused block Free space after delete

Truncating a Table TRUNCATE TABLE hr.employees; Truncating a table Deletes all rows in a table Releases used space Corresponding indexes are also truncated A table referenced by a foreign key cannot be truncated

Dropping a Table DROP TABLE scott.departments CASCADE CONSTRAINTS; The extents used by the table are released The CASCADE CONTRAINTS is necessary if the table is the parent table in a foreign key relationship

Dropping a Column Removing a column from a table: ALTER TABLE hr.employees DROP COLUMN comments CASCADE CONSTRAINTS CHECKPOINT 1000; Removes the column length and data from each row, freeing space in the data block. Dropping a column in a large table takes a considerable amount of time. To resume an interrupted drop operation: Checkpoint occurs every 1000 rows SQL> ALTER TABLE hr.employees DROP COLUMN CONTINUE;

Renaming a Column ALTER TABLE hr.employees RENAME COLUMN hire_date TO start_date;

Mark a column as unused: Universitatea Politehnica Bucureşti - Facultatea de Automatica si Calculatoare Using the UNUSED Option ALTER TABLE hr.employees SET UNUSED COLUMN comments CASCADE CONSTRAINTS Relatively quick, no need to free the space, do it later, the data is not removed Drop unused columns: ALTER TABLE hr.employees DROP UNUSED COLUMNS CHECKPOINT 1000; Continue to drop column operation: ALTER TABLE hr.employees DROP COLUMNS CONTINUE CHECKPOINT 1000;

Validating Table Structure The Oracle server verifies the integrity of each data block. Use the CASCADE option to validate the structure of all indexes on the table, and perform cross-referencing between the table and its indexes. ANALYZE TABLE scott.employees VALIDATE STRUCTURE;

Detecting Row Migration The Oracle server gathers statistics based on sample data and updates data dictionary. ANALYZE TABLE scott.employees ESTIMATE STATISTICS; Check CHAIN_CNT SELECT chain_cnt FROM DBA_TABLES WHERE table_name= EMPLOYEES AND owner= SCOTT ;

Obtaining Table Information Information about tables can be obtained by querying the following views: DBA_TABLES DBA_OBJECTS SQL> SELECT table_name 2 FROM dba_tables WHERE owner= HR ; TABLE_NAME ---------------- COUTRIES DEPARTMENTS DEPARTMENTS_HIST EMPLOYEES EMPLOYEES_HIST

Retrieving Table Information DBA_OBJECTS OWNER OBJECT_NAME OBJECT_ID DATA_OBJECT_ID CREATED DBA_SEGMENTS OWNER SEGMENT_NAME TABLESPACE_NAME HEADER_FILE HEADER_BLOCK DBA_TABLES OWNER TABLE_NAME PCT_FREE PCT_USED INITIAL_EXTENT NEXT_EXTENT MIN_EXTENTS MAX_EXTENTS PCT_INCREASE CACHE BLOCKS EMPTY_BLOCKS CHAIN_CNT

Retrieving Extent Information DBA_EXTENTS OWNER SEGMENT_NAME EXTENT_ID FILE_ID BLOCK_ID BLOCKS

DBMS_ROWID Package Commonly used functions: Function Name ROWID_CREATE ROWID_OBJECT ROWID_RELATIVE_FNO ROWID_BLOCK_NUMBER ROWID_ROW_NUMBER ROWID_TO_ABSOLUTE_FNO ROWID_TO_EXTENDED ROWID_TO_RESTRICTED Description Creates a ROWID from individual components Returns the object identifier for a ROWID Returns the relative file number for a ROWID Returns the block number for a ROWID Returns the row number for a ROWID Returns the absolute file number for a ROWID Converts a ROWID from restricted to extended Converts a ROWID from extended to restricted 25/11/2009 Administrarea Bazelor de Date I

Managing Indexes

Objectives After completing this lesson you should be able to do the following: List the different types of indexes and their use Create various types of indexes Reorganize indexes Maintain indexes Monitor the usage of an index Obtain index information from the data dictionary Index = Tree structure that allows direct access to a row in a table

Logical Universitatea Politehnica Bucureşti - Facultatea de Automatica si Calculatoare Classification of Indexes Single column or concatenated Unique or nonunique Function-based Domain Physical Partitioned or nonpartitioned B-tree: Normal or reverse key Bitmap

Single column index Indexes Has only one column in the index key eq: an index on the employees number column Concatenated index (or composite index) Created on multiple columns in a table eq: an index on the department and job columns The maximum number of columns in a composite key index is 32 Unique index Guarantee that no rows of a table have duplicate values in the key column Function-based index Created when using functions or expressions that involve one or more columns in the table that is being indexed

B-Tree Index Index entry Root Branch Leaf Index entry header Key column length Key column value ROWID

Reverse Key Index Index on EMP (EMPNO) EMP table KEY ROWID EMPNO (BLOCK# ROW# FILE#) ----- ------------------- 1257 0000000F.0002.0001 2877 0000000F.0006.0001 4567 0000000F.0004.0001 6657 0000000F.0003.0001 8967 0000000F.0005.0001 9637 0000000F.0001.0001 9947 0000000F.0000.0001............ EMPNO ENAME JOB... ----- ----- -------- 7499 ALLEN SALESMAN 7369 SMITH CLERK 7521 WARD SALESMAN... 7566 JONES MANAGER 7654 MARTIN SALESMAN 7698 BLAKE MANAGER 7782 CLARK MANAGER........................

Bitmap Indexes Table File 3 Block 10 Block 11 Index Block 12 key start end ROWID ROWID bitmap <Blue, 10.0.3, 12.8.3, 1000100100010010100> <Green, 10.0.3, 12.8.3, 0001010000100100000> <Red, 10.0.3, 12.8.3, 0100000011000001001> <Yellow, 10.0.3, 12.8.3, 0010001000001000010>

Bitmap Indexes

Comparing B-Tree B and Bitmap Indexes B-tree Suitable for high-cardinality columns Updates on keys relatively inexpensive Inefficient for queries using OR predicates Bitmap Suitable for low-cardinality columns Updates to key columns very expensive Efficient for queries using OR predicates Useful for OLTP Useful for DSS 25/11/2009 Administrarea Bazelor de Date I

Creating B-Tree B Indexes CREATE INDEX scott.emp_lname_idx ON scott.employees(last_name) PCTFREE 30 STORAGE(INITIAL 200K NEXT 200K PCTINCREASE 0 MAXEXTENTS 50) TABLESPACE indx01;

Creating B-Tree B Indexes Syntax Options UNIQUE: Used to specify a unique index (nonunique is default) Schema: Owner of the index or table Index: Name of the index Table: Name of the table Column: Name of the column ASC/DESC: Indicates whether the index should be created in ascending or descending order TABLESPACE: Identifies the tablespace where the index will be created LOGGING: Specifies that the creation of the index and subsequent operations on the index are logged in the online redo file (this is the default)

Creating Indexes: Guidelines Balance query and DML needs Place in separate tablespace Use uniform extent sizes: multiples of five blocks or MINIMUM EXTENT size for tablespace Consider NOLOGGING for large indexes INITRANS should generally be higher on indexes than on the corresponding tables Index entries are smaller than the rows they index index blocks tend to have more entries per block

Creating Reverse Key Indexes CREATE UNIQUE INDEX scott.ord_ord_no_idx ON scott.ord(ord_no) REVERSE PCTFREE 30 STORAGE(INITIAL 200K NEXT 200K PCTINCREASE 0 MAXEXTENTS 50) TABLESPACE indx01;

Creating Bitmap Indexes CREATE BITMAP INDEX scott.ord_region_id_idx ON scott.ord(region_id) PCTFREE 30 STORAGE(INITIAL 200K NEXT 200K PCTINCREASE 0 MAXEXTENTS 50) TABLESPACE indx01; The CREATE_BITMAP_AREA_SIZE initialization parameter determines the amount of space used for storing bitmap segments in memory Default 8 MB

Changing Storage Parameters for Indexes ALTER INDEX scott.emp_lname_idx STORAGE(NEXT 400K MAXEXTENTS 100);

Allocating and Deallocating Index Space ALTER INDEX scott.ord_region_id_idx ALLOCATE EXTENT (SIZE 200K DATAFILE /DISK6/indx01.dbf ); ALTER INDEX scott.ord_ord_no_idx DEALLOCATE UNUSED;

Use this command to: Universitatea Politehnica Bucureşti - Facultatea de Automatica si Calculatoare Rebuilding Indexes Move an index to a different tablespace Improve space utilization by removing deleted entries Change a reverse key index to a normal B-tree index and vice versa ALTER INDEX scott.ord_region_id_idx REBUILD TABLESPACE indx02;

Coalescing Indexes Before coalescing After coalescing ALTER INDEX orders_id_idx COALESCE;

Checking Index Validity ANALYZE INDEX scott.ord_region_id_idx VALIDATE STRUCTURE; Check the index blocks for block corruption Populate the INDEX_STATS view with information about the index INDEX_STATS

Dropping Indexes Drop and re-create an index before bulk loads. Drop indexes that are infrequently needed and build them when necessary. Drop and recreate invalid indexes. DROP INDEX scott.dept_dname_idx;

Identifying Unused Indexes To start monitoring the usage of an index: ALTER INDEX hr.dept_id_idx MONITORING USAGE To stop monitoring the usage of an index: ALTER INDEX hr.dept_id_idx MONITORING USAGE Statistics displayed in V$OBJECT_USAGE

Obtaining Index Information DBA_INDEXES OWNER INDEX_NAME INDEX_TYPE TABLE_OWNER TABLE_NAME UNIQUENESS TABLESPACE_NAME LOGGING STATUS DBA_IND_COLUMNS INDEX_OWNER INDEX_NAME TABLE_OWNER TABLE_NAME COLUMN_NAME COLUMN_POSITION COLUMN_LENGTH

Maintaining Data Integrity

Objectives After completing this lesson you should be able to do the following: Implement data integrity constraints Maintain integrity constraints Obtain constraint information from the data dictionary

Data Integrity DI = data in a database adhere to business rules 3 primary ways: Data Database trigger Integrity constraint Application code Table

Types of Constraints Constraint NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK Description Specifies that a column cannot contain null values Designates a column or combination of columns as unique Designates a column or combination of columns as the table s primary key Designates a column or combination of columns as the foreign key in a referential integrity constraint Specifies a condition that each row of the table must satisfy

Constraint States DISABLE NOVALIDATE DISABLE VALIDATE ENABLE NOVALIDATE ENABLE VALIDATE = = Data entered is not checked Data in the table may not conform to the rules defined by the constraint New data Existing data

Constraint States DISABLE NOVALIDATE DISABLE VALIDATE ENABLE NOVALIDATE ENABLE VALIDATE = = Any modification of the constrained columns is not allowed The index on the constraint is dropped and the constraint is disabled New data Existing data

Constraint States DISABLE NOVALIDATE DISABLE VALIDATE ENABLE NOVALIDATE ENABLE VALIDATE = = New data that violates the constraint cannot be entered The table may contain data that is invalid New data Existing data

Constraint States DISABLE NOVALIDATE DISABLE VALIDATE ENABLE NOVALIDATE ENABLE VALIDATE = = A row that violates the constraint cannot be inserted into the table When a constraint changes to ENABLE VALIDATE the table is locked and all data in the table is checked for conformity New data Existing data

Constraint Checking You can defer checking constraints for validity until the end of the transaction: DML statement Check nondeferred constraints COMMIT Check deferred constraints

Defining Constraints Immediate or Deferred Use the SET CONSTRAINTS statement to make constraints either DEFERRED or IMMEDIATE The ALTER SESSION statement also has clauses to set constraints to DEFERRED or IMMEDIATE

Primary and Unique Key Enforcement Key enabled? Yes Is an index available for use? Yes No No Use existing index Constraint deferrable? Yes Do not use index No Create unique index Create nonunique index

Foreign Key Considerations To Drop parent table Truncate parent table Drop tablespace containing parent table Avoid locks on child table while performing DML on parent table Perform DML on child table Perform Cascade constraints Disable/drop foreign key Use CASCADE CONSTRAINTS clause Create index on foreign key Ensure tablespace containing parent key index online 25/11/2009 Administrarea Bazelor de Date I

Database Triggers DML action Trigger Table Trigger types INSERT or UPDATE or DELETE BEFORE or AFTER ROW or STATEMENT

Defining Constraints While Creating a Table CREATE TABLE scott.employees( empno NUMBER(4) CONSTRAINT emp_pk PRIMARY KEY DEFERRABLE USING INDEX STORAGE(INITIAL 100K NEXT 100K) TABLESPACE indx01, last_name VARCHAR2(30) CONSTRAINT emp_ln_nn NOT NULL, deptno NUMBER(2)) TABLESPACE data01;

Guidelines for Defining Constraints Primary and unique constraints: Place indexes in a separate tablespace Use nonunique indexes if bulk loads are frequent Self-referencing foreign keys: Define or enable foreign keys after initial load Defer constraint checking

Disabling Constraints Disable before bulk load, especially self-referencing foreign keys. Disable referencing foreign keys before disabling parent keys. ALTER TABLE scott.departments DISABLE CONSTRAINT dept_pk CASCADE; Unique indexes are dropped, but nonunique indexes are retained.

Enabling Constraints Enable NOVALIDATE No locks on table Primary/unique keys must use nonunique indexes ALTER TABLE scott.departments ENABLE NOVALIDATE CONSTRAINT dept_pk;

Enabling Constraints Enable VALIDATE Locks table Can use unique or nonunique indexes Needs valid table data ALTER TABLE scott.employees ENABLE VALIDATE CONSTRAINT emp_dept_fk;

Renaming Constraints Use the following to rename a constraint: ALTER TABLE employees RENAME CONSTRAINT emp_dept_fk TO employees_dept_fk;

Using the EXCEPTIONS Table 1. Create EXCEPTIONS table by running the utlexcpt.sql script. 2. Execute ALTER TABLE with EXCEPTIONS option. ALTER TABLE hr.employee ENABLE VALIDATE CONSTRAINT employee_dept_id_fk EXCEPTIONS INTO system.exceptions; 3. Use subquery on EXCEPTIONS to locate rows with invalid data. 4. Rectify the errors. 5. Reexecute ALTER TABLE to enable the constraint. SQL> SQL> SELECT rowid, id, id, last_name, dept_id 2 FROM hr.employee 3 WHERE ROWID in in (SELECT row_id 4 FROM exceptions) 5 FOR FOR UPDATE;

Disabling and Enabling Triggers Use ALTER TRIGGER to disable or enable one trigger. ALTER TRIGGER scott.emp_conv_ln DISABLE; Use ALTER TABLE to disable or enable all triggers. ALTER TABLE scott.employees ENABLE ALL TRIGGERS;

Dropping Constraints Drop constraints using this command: ALTER TABLE scott.employees DROP CONSTRAINT emp_ln_uk; Drop a table and any referencing foreign key using this command: DROP TABLE departments CASCADE CONSTRAINTS;

Dropping Triggers DROP TRIGGER scott.audit_dept;

Getting Constraint Information DBA_CONSTRAINTS OWNER CONSTRAINT_NAME CONSTRAINT_TYPE TABLE_NAME SEARCH_CONDITION R_OWNER R_CONSTRAINT_NAME DELETE_RULE STATUS DEFERRABLE DEFERRED VALIDATED GENERATED BAD LAST_CHANGE DBA_CONS_COLUMNS OWNER CONSTRAINT_NAME TABLE_NAME COLUMN_NAME POSITION

Getting Information on Triggers DBA_TRIGGERS OWNER TRIGGER_NAME TRIGGER_TYPE TRIGGERING_EVENT TABLE_OWNER TABLE_NAME STATUS DESCRIPTION TRIGGER_BODY DBA_TRIGGER_COLS TRIGGER_OWNER TRIGGER_NAME TABLE_OWNER TABLE_NAME COLUMN_NAME DBA_OBJECTS OWNER OBJECT_NAME OBJECT_TYPE STATUS

Using Clusters and Index-Organized Tables* *nu intra la examen

Objectives After completing this lesson you should be able to do the following: Create and maintain clusters Use index-organized tables Retrieve information about clusters and tables from the data dictionary

Distribution of Rows Within a Table Table Cluster Index-organized table Ordering of Rows Random Grouped Ordered

Clusters ORD_NO ----- PROD ------ QTY ------... 101 A4102 20 102 A2091 11 102 G7830 20 102 N9587 26 101 A5675 19 101 W0824 10 ORD_NO ------ ORD_DT ------ CUST_CD ------ 101 05-JAN-97 R01 102 07-JAN-97 N45 Cluster Key (ORD_NO) 101 ORD_DT CUST_CD 05-JAN-97 R01 PROD QTY A4102 20 A5675 19 W0824 10 102 ORD_DT CUST_CD 07-JAN-97 N45 PROD QTY A2091 11 G7830 20 N9587 26 Unclustered ORD and ITEM tables Clustered ORD and ITEM tables

Cluster Types Index cluster Hash cluster Hash function

1. Create a cluster. 2. Create a cluster index. Universitatea Politehnica Bucureşti - Facultatea de Automatica si Calculatoare Creating Index Clusters CREATE CLUSTER scott.ord_clu (ord_no NUMBER(3)) SIZE 200 TABLESPACE DATA01 STORAGE(INITIAL 5M NEXT 5M PCTINCREASE 0); CREATE INDEX scott.ord_clu_idx ON CLUSTER scott.ord_clu TABLESPACE INDX01 STORAGE(INITIAL 1M NEXT 1M PCTINCREASE 0);

3. Create tables in the cluster. Creating Index Clusters CREATE TABLE scott.ord (ord_no NUMBER(3) CONSTRAINT ord_pk PRIMARY KEY, ord_dt DATE, cust_cd VARCHAR2(3)) CLUSTER scott.ord_clu(ord_no); CREATE TABLE scott.item (ord_no NUMBER(3) CONSTRAINT item_ord_fk REFERENCES scott.ord, prod VARCHAR2(5), qty NUMBER(3), CONSTRAINT item_pk PRIMARY KEY(ord_no,prod)) CLUSTER scott.ord_clu(ord_no);

1. Create a cluster. Universitatea Politehnica Bucureşti - Facultatea de Automatica si Calculatoare 2. Create tables in a cluster. Creating Hash Clusters CREATE CLUSTER scott.off_clu (country VARCHAR2(2),postcode VARCHAR2(8)) SIZE 500 HASHKEYS 1000 TABLESPACE DATA01 STORAGE(INITIAL 5M 5M NEXT 5M 5M PCTINCREASE 0); CREATE TABLE scott.office( office_cd NUMBER(3), cost_ctr NUMBER(3), country VARCHAR2(2), postcode VARCHAR2(8)) CLUSTER scott.off_clu(country,postcode);

Defining SIZE for Clusters Defines space used by all the rows for a given key. Used in both types of cluster to estimate: The maximum number of key values per block for an index cluster The exact number of key values per block for a hash cluster

Parameters Specific to Hash Clusters HASHKEYS: Number of key values HASH IS: Optional user-defined hash function Key 21 Key 11 Key 12 Key 1 Key 2 Key 3 Key 22 Preallocated blocks Overflow block

Altering Clusters Change storage and block space usage parameters Change SIZE for index clusters Allocate and deallocate space ALTER CLUSTER scott.ord_clu SIZE 300 STORAGE (NEXT 2M); SIZE, HASH IS, or HASHKEYS cannot be altered for hash clusters

Dropping Clusters Use INCLUDING TABLES to drop tables and cluster DROP CLUSTER scott.ord_clu INCLUDING TABLES; or drop tables before dropping cluster. DROP TABLE scott.ord; DROP TABLE scott.item; DROP CLUSTER scott.ord_clu;

Situations Where Clusters Are Useful Criterion Index Hash Uniform key distribution Evenly spread key values Rarely updated key Often joined master-detail tables Predictable number of key values Queries using equality predicate on key 25/11/2009 Administrarea Bazelor de Date I

Retrieving Cluster Information DBA_CLUSTERS OWNER CLUSTER_NAME TABLESPACE_NAME KEY_SIZE CLUSTER_TYPE FUNCTION HASHKEYS DBA_CLU_COLUMNS OWNER CLUSTER_NAME CLU_COLUMN_NAME TABLE_NAME TAB_COLUMN_NAME DBA_TAB_COLUMNS OWNER TABLE_NAME COLUMN_NAME DATA_TYPE DATA_LENGTH DATA_PRECISION DATA_SCALE DBA_CLUSTER_ HASH_EXPRESSIONS OWNER CLUSTER_NAME HASH_EXPRESSION

Index-Organized Tables Indexed access on table Accessing index- organized table ROWID Non-key columns Key column Row header

Index-Organized Tables Compared with Regular Tables Regular Table Unique identifier ROWID ROWID implicit Supports several indexes FTS returns rows in no specific order Unique constraints allowed Distribution, replication, and partitioning supported Index-Organized Table Identified by primary key No ROWID No secondary indexes Full index scans return rows in PK order No support for unique constraints Distribution, replication, and partitioning not supported

Creating Index-Organized Tables CREATE TABLE scott.sales ( office_cd NUMBER(3), qtr_end DATE, revenue NUMBER(10,2), review VARCHAR2(1000), CONSTRAINT sales_pk PRIMARY KEY(office_code, qtr_end)) ORGANIZATION INDEX TABLESPACE data01 PCTTHRESHOLD 20 OVERFLOW TABLESPACE data02;

Row Overflow IOT tablespace Segment = PK Name Type = Index Overflow tablespace Segment = SYS_IOT_OVER_n Type=Table Block Rows within PCTTHRESHOLD Row bigger than PCTTHRESHOLD

Retrieving IOT Information from Data Dictionary DBA_TABLES OWNER TABLE_NAME IOT_TYPE IOT_NAME TABLESPACE_NAME DBA_INDEXES OWNER TABLE_NAME INDEX_NAME INDEX_TYPE PCT_THRESHOLD INCLUDE_COLUMN