Including Constraints. Copyright Oracle Corporation. All rights reserved.

Similar documents
RDBMS Using Oracle. Lecture Week 7 Introduction to Oracle 9i SQL Last Lecture. kamran.munir@gmail.com. Joining Tables

Managing Objects with Data Dictionary Views. Copyright 2006, Oracle. All rights reserved.

Chapter 1. Writing Basic. SQL Statements

Objectives. Oracle SQL and SQL*PLus. Database Objects. What is a Sequence?

Displaying Data from Multiple Tables

Displaying Data from Multiple Tables. Chapter 4

Database Design. Marta Jakubowska-Sobczak IT/ADC based on slides prepared by Paula Figueiredo, IT/DB

Producing Readable Output with SQL*Plus

SQL Introduction Chapter 7, sections 1 & 4. Introduction to SQL. Introduction to SQL. Introduction to SQL

5. CHANGING STRUCTURE AND DATA

Subqueries Chapter 6

A basic create statement for a simple student table would look like the following.

PRIMARY KEY, FOREIGN KEY and CHECK Constraints. Copyright 2011, Oracle. All rights reserved.

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Aggregating Data Using Group Functions

Oracle/SQL Tutorial 1

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

How To Name A Program In Apl/Sql

SQL> SELECT ename, job, sal Salary. 1.4.Will the SELECT statement execute successfully? True/False

Procedural Extension to SQL using Triggers. SS Chung

Using TimesTen between your Application and Oracle. between your Application and Oracle. DOAG Conference 2011

CSI 2132 Lab 3. Outline 09/02/2012. More on SQL. Destroying and Altering Relations. Exercise: DROP TABLE ALTER TABLE SELECT

Programming with SQL

Training Guide. PL/SQL for Beginners. Workbook

Chapter 2: Security in DB2

Examine the structure of the EMPLOYEES table: EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25)

How To Create A Table In Sql (Ahem)

Oracle 12c New Features For Developers

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING DR.NAVALAR NEDUNCHEZHIAYN COLLEGE OF ENGINEERING, THOLUDUR , CUDDALORE DIST.

9 Using Triggers. Using Triggers 9-1

Teach Yourself InterBase

14 Triggers / Embedded SQL

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

Mini User's Guide for SQL*Plus T. J. Teorey

DECLARATION SECTION. BODY STATEMENTS... Required

There are five fields or columns, with names and types as shown above.

SQL interview questions and answers

Oracle For Beginners Page : 1

Data Models and Database Management Systems (DBMSs) Dr. Philip Cannata

Introduction to SQL and database objects

Oracle Database 10g Express

Relational Algebra. Query Languages Review. Operators. Select (σ), Project (π), Union ( ), Difference (-), Join: Natural (*) and Theta ( )

Maximizing Materialized Views

Oracle Database 10g: Introduction to SQL

SQL. Short introduction

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

MONASH UNIVERSITY. Faculty of Information Technology

SQL*Plus User s Guide and Reference

Conversion Functions

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Review of Business Information Systems Third Quarter 2013 Volume 17, Number 3

CSC 443 Data Base Management Systems. Basic SQL

SQL Tuning Proven Methodologies

Database Design Process. ER Model. Goals. Relational Model. SQL - The Language of Databases. IT420: Database Management and Organization

Dictionary (catálogo)

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

FINDING ORACLE TABLE METADATA WITH PROC CONTENTS

Hacking and Protecting Oracle DB. Slavik Markovich CTO, Sentrigo

ORACLE 10g Lab Guide

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

Date / Time Arithmetic with Oracle

news from Tom Bacon about Monday's lecture

Using Temporary Tables to Improve Performance for SQL Data Services

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

2. Oracle SQL*PLUS Winter Some SQL Commands. To connect to a CS server, do:

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

5.1 Database Schema Schema Generation in SQL

3.GETTING STARTED WITH ORACLE8i

Question 1. Relational Data Model [17 marks] Question 2. SQL and Relational Algebra [31 marks]

Oracle Database 12c: Introduction to SQL Ed 1.1

Lecture 6. SQL, Logical DB Design

Writing Control Structures

Oracle 10g PL/SQL Training

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1

Language Reference Guide

AVOIDANCE OF CYCLICAL REFERENCE OF FOREIGN KEYS IN DATA MODELING USING THE ENTITY-RELATIONSHIP MODEL

Databases What the Specification Says

Database programming 20/08/2015. DBprog news. Outline. Motivation for DB programming. Using SQL queries in a program. Using SQL queries in a program

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Retrieval: Multiple Tables and Aggregation

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1

Oracle For Beginners Page : 1

Programming Database lectures for mathema

Extracting META information from Interbase/Firebird SQL (INFORMATION_SCHEMA)

Database Query 1: SQL Basics

VARRAY AND NESTED TABLE

Database 10g Edition: All possible 10g features, either bundled or available at additional cost.

Relational Databases. Christopher Simpkins

Structured Query Language (SQL)

Data Masking. Procedure

Overview of PL/SQL. About PL/SQL

SQL 2: GETTING INFORMATION INTO A DATABASE. MIS2502 Data Analytics

David Dye. Extract, Transform, Load

Ch.5 Database Security. Ch.5 Database Security Review

Mul$media im Netz (Online Mul$media) Wintersemester 2014/15. Übung 03 (Nebenfach)

Transcription:

11 Including Constraints Copyright Oracle Corporation. All rights reserved.

Objectives After completing this lesson, you should be able to do the following: Describe constraints Create and maintain constraints 11-2 Copyright Oracle Corporation. All rights reserved.

What Are Constraints? Constraints enforce rules at the table level. Constraints prevent the deletion of a table if there are dependencies. The following constraint types are valid in Oracle: NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK 11-3 Copyright Oracle Corporation. All rights reserved.

Constraint Guidelines Name a constraint or the Oracle Server will generate a name by using the SYS_Cn format. Create a constraint: At the same time as the table is created After the table has been created Define a constraint at the column or table level. View a constraint in the data dictionary. 11-4 Copyright Oracle Corporation. All rights reserved.

Defining Constraints CREATE TABLE [schema.]table (column datatype [DEFAULT expr] [column_constraint],... [table_constraint][,...]); CREATE TABLE emp( empno NUMBER(4), ename VARCHAR2(10),... deptno NUMBER(7,2) NOT NULL, CONSTRAINT emp_empno_pk PRIMARY KEY (EMPNO)); 11-5 Copyright Oracle Corporation. All rights reserved.

Defining Constraints Column constraint level column [CONSTRAINT constraint_name] constraint_type, Table constraint level column,... [CONSTRAINT constraint_name] constraint_type (column,...), 11-6 Copyright Oracle Corporation. All rights reserved.

The NOT NULL Constraint Ensures that null values are not permitted for the column EMP EMPNO ENAME JOB... COMM DEPTNO 7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7782 CLARK MANAGER 10 7566 JONES MANAGER 20... NOT NULL constraint (no row can contain a null value for this column) Absence of NOT NULL constraint (any row can contain null for this column) NOT NULL constraint 11-7 Copyright Oracle Corporation. All rights reserved.

The NOT NULL Constraint Defined at the column level SQL> CREATE TABLE emp( 2 empno NUMBER(4), 3 ename VARCHAR2(10) NOT NULL, 4 job VARCHAR2(9), 5 mgr NUMBER(4), 6 hiredate DATE, 7 sal NUMBER(7,2), 8 comm NUMBER(7,2), 9 deptno NUMBER(7,2) NOT NULL); 11-8 Copyright Oracle Corporation. All rights reserved.

DEPT The UNIQUE Key Constraint UNIQUE key constraint DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON Insert into 50 SALES DETROIT 60 BOSTON Not allowed (DNAME SALES already exists) Allowed 11-9 Copyright Oracle Corporation. All rights reserved.

The UNIQUE Key Constraint Defined at either the table level or the column level SQL> CREATE TABLE dept( 2 deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13), 5 CONSTRAINT dept_dname_uk UNIQUE(dname)); 11-10 Copyright Oracle Corporation. All rights reserved.

The PRIMARY KEY Constraint DEPT PRIMARY KEY DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON Insert into 20 MARKETING DALLAS Not allowed (DEPTNO 20 already exists) FINANCE NEW YORK Not allowed (DEPTNO is null) 11-11 Copyright Oracle Corporation. All rights reserved.

The PRIMARY KEY Constraint Defined at either the table level or the column level SQL> CREATE TABLE dept( 2 deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13), 5 CONSTRAINT dept_dname_uk UNIQUE (dname), 6 CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno)); 11-12 Copyright Oracle Corporation. All rights reserved.

PRIMARY KEY EMP The FOREIGN KEY Constraint DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS... EMPNO ENAME JOB... COMM DEPTNO 7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30... Insert into 7571 FORD MANAGER... 200 9 7571 FORD MANAGER... 200 20 FOREIGN KEY Not allowed (DEPTNO 9 does not exist in the DEPT table) Allowed 11-13 Copyright Oracle Corporation. All rights reserved.

The FOREIGN KEY Constraint Defined at either the table level or the column level SQL> CREATE TABLE emp( 2 empno NUMBER(4), 3 ename VARCHAR2(10) NOT NULL, 4 job VARCHAR2(9), 5 mgr NUMBER(4), 6 hiredate DATE, 7 sal NUMBER(7,2), 8 comm NUMBER(7,2), 9 deptno NUMBER(7,2) NOT NULL, 10 CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno) 11 REFERENCES dept (deptno)); 11-14 Copyright Oracle Corporation. All rights reserved.

FOREIGN KEY Constraint Keywords FOREIGN KEY Defines the column in the child table at the table constraint level REFERENCES Identifies the table and column in the parent table ON DELETE CASCADE Allows deletion in the parent table and deletion of the dependent rows in the child table 11-15 Copyright Oracle Corporation. All rights reserved.

The CHECK Constraint Defines a condition that each row must satisfy Expressions that are not allowed: References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns Calls to SYSDATE, UID, USER, and USERENV functions Queries that refer to other values in other rows..., deptno NUMBER(2), CONSTRAINT emp_deptno_ck CHECK (DEPTNO BETWEEN 10 AND 99),... 11-16 Copyright Oracle Corporation. All rights reserved.

Adding a Constraint ALTER TABLE table ADD [CONSTRAINT constraint] type (column); Add or drop, but not modify, a constraint Enable or disable constraints Add a NOT NULL constraint by using the MODIFY clause 11-17 Copyright Oracle Corporation. All rights reserved.

Adding a Constraint Add a FOREIGN KEY constraint to the EMP table indicating that a manager must already exist as a valid employee in the EMP table. SQL> ALTER TABLE emp 2 ADD CONSTRAINT emp_mgr_fk 3 FOREIGN KEY(mgr) REFERENCES emp(empno); Table altered. 11-18 Copyright Oracle Corporation. All rights reserved.

Dropping a Constraint Remove the manager constraint from the EMP table. SQL> ALTER TABLE emp 2 DROP CONSTRAINT emp_mgr_fk; Table altered. Remove the PRIMARY KEY constraint on the DEPT table and drop the associated FOREIGN KEY constraint on the EMP.DEPTNO column. SQL> ALTER TABLE dept 2 DROP PRIMARY KEY CASCADE; Table altered. 11-19 Copyright Oracle Corporation. All rights reserved.

Disabling Constraints Execute the DISABLE clause of the ALTER TABLE statement to deactivate an integrity constraint. Apply the CASCADE option to disable dependent integrity constraints. SQL> ALTER TABLE emp 2 DISABLE CONSTRAINT emp_empno_pk CASCADE; Table altered. 11-20 Copyright Oracle Corporation. All rights reserved.

Enabling Constraints Activate an integrity constraint currently disabled in the table definition by using the ENABLE clause. SQL> ALTER TABLE emp 2 ENABLE CONSTRAINT emp_empno_pk; Table altered. A UNIQUE or PRIMARY KEY index is automatically created if you enable a UNIQUE key or PRIMARY KEY constraint. 11-21 Copyright Oracle Corporation. All rights reserved.

Viewing Constraints Query the USER_CONSTRAINTS table to view all constraint definitions and names. SQL> SELECT constraint_name, constraint_type, 2 search_condition 3 FROM user_constraints 4 WHERE table_name = 'EMP'; CONSTRAINT_NAME C SEARCH_CONDITION ------------------------ - ------------------------- SYS_C00674 C EMPNO IS NOT NULL SYS_C00675 C DEPTNO IS NOT NULL EMP_EMPNO_PK P... 11-22 Copyright Oracle Corporation. All rights reserved.

Viewing the Columns Associated with Constraints View the columns associated with the constraint names in the USER_CONS_COLUMNS view. SQL> SELECT constraint_name, column_name 2 FROM user_cons_columns 3 WHERE table_name = 'EMP'; CONSTRAINT_NAME COLUMN_NAME ------------------------- ---------------------- EMP_DEPTNO_FK DEPTNO EMP_EMPNO_PK EMPNO EMP_MGR_FK MGR SYS_C00674 EMPNO SYS_C00675 DEPTNO 11-23 Copyright Oracle Corporation. All rights reserved.

Summary Create the following types of constraints: NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK Query the USER_CONSTRAINTS table to view all constraint definitions and names. 11-24 Copyright Oracle Corporation. All rights reserved.

Practice Overview Adding constraints to existing tables Adding more columns to a table Displaying information in data dictionary views 11-25 Copyright Oracle Corporation. All rights reserved.