1 Lecture 4 Data Integrity: Primary and Foreign Keys.

Slides:



Advertisements
Similar presentations
Fall 2005 ICS184/EECS116 – Notes 08 1 ICS 184/EECS116: Introduction to Data Management Lecture Note 8 SQL: Structured Query Language -- DDL.
Advertisements

Copyright  Oracle Corporation, All rights reserved. 6 Writing Correlated Subqueries.
Maintenance Modifying the data –Add records –Delete records –Update records Modifying the design –Add fields into tables –Remove fields from a table –Change.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
Constraints We have discussed three types of integrity constraints: primary keys, not null constraints, and unique constraints. CREATE TABLE Movies ( title.
Copyright  Oracle Corporation, All rights reserved. 9 Manipulating Data: INSERT, UPDATE, DELETE.
A Guide to MySQL 7. 2 Objectives Understand, define, and drop views Recognize the benefits of using views Use a view to update data Grant and revoke users’
SQL DDL constraints Restrictions on the columns and tables 1SQL DDL Constraints.
SQL's Data Definition Language (DDL) – View, Sequence, Index.
Database Management System Lecture 6 The Relational Database Model – Keys, Integrity Rules.
Concepts of Database Management, Fifth Edition Chapter 4: The Relational Model 3: Advanced Topics.
Constraints  Constraints are used to enforce rules at table level.  Constraints prevent the deletion of a table if there is dependencies.  The following.
4-1 Copyright  Oracle Corporation, All rights reserved. Data Manipulation Language (DML)
1 Copyright © 2006, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
1 Information Retrieval and Use (IRU) CE An Introduction To SQL Part 1.
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
10 Creating and Managing Tables Objectives At the end of this lesson, you will be able to: Describe the main database objects Create tables Describe.
SQL- DQL (Oracle Version). 2 SELECT Statement Syntax SELECT [DISTINCT] column_list FROM table_list [WHERE conditional expression] [GROUP BY column_list]
Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
Session 2: SQL (A): Parts 1 and 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Chapter 8 Part 2 SQL-99 Schema Definition, Constraints, Queries, and Views.
4 Displaying Data from Multiple Tables Important Legal Notice:  Materials on this lecture are from a book titled “Oracle Education” by Kochhar, Gravina,
Copyright س Oracle Corporation, All rights reserved. 4 Displaying Data from Multiple Tables.
11-1 Copyright  Oracle Corporation, All rights reserved. What Are Constraints? Constraints enforce rules at the table level. Constraints prevent.
1 SQL - II Data Constraints –Applying data constraints Types of data constraints –I/O constraints The PRIMARY KEY constraints The FOREIGN KEY constraints.
Chapter 9 Constraints. Chapter Objectives  Explain the purpose of constraints in a table  Distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK,
Oracle 11g: SQL Chapter 4 Constraints.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Copyright  Oracle Corporation, All rights reserved. 11 Including Constraints.
Copyright  Oracle Corporation, All rights reserved. Introduction.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Relational State Constraints These slides.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
More SQL Data Management Topics zIntegrity Constraints zOuter Join zUnion.
SQL: Part 1 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.
INCLUDING CONSTRAINTS lecture5. Outlines  What are Constraints ?  Constraint Guidelines  Defining Constraint  NOT NULL constraint  Unique constraint.
11 Including Constraints Objectives At the end of this lesson, you will be able to: Describe constraints Create and maintain constraints At the.
9 Manipulating Data. 9-2 Objectives At the end of this lesson, you should be able to: Describe each DML statement Insert rows into a table Update rows.
Copyright  Oracle Corporation, All rights reserved. 12 Creating Views.
9-1 © Prentice Hall, 2007 Topic 9: Physical Database Design Object-Oriented Systems Analysis and Design Joey F. George, Dinesh Batra, Joseph S. Valacich,
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Relational State Assertions These slides.
At the end of this lesson, you will be able to: Describe constraints Create and maintain constraints.
Including Constraints. What Are Constraints? Constraints enforce rules at the table level. You can use constraints to do the following: – Enforce rules.
Copyright س Oracle Corporation, All rights reserved. 12 Creating Views.
Lecture 2 Joins and sub-queries. 2 Topics zJoins ySimple; Outer zSub-queries yaliases zIN Operator zNULL values zSaving and running files.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
SQL Statements SELECT INSERTUPDATEDELETECREATEALTERDROPRENAMETRUNCATECOMMITROLLBACKSAVEPOINTGRANTREVOKE Data Retrieval Language (DRL) Data Retrieval Language.
Copyright  Oracle Corporation, All rights reserved. 4 Displaying Data from Multiple Tables.
Displaying Data from Multiple Tables. Objectives After completing this lesson, you should be able to do the following: –Write SELECT statements to access.
4 Displaying Data from Multiple Tables. 4-2 Objectives At the end of this lesson, you should be able to: Write SELECT statements to access data from more.
2 Copyright © 2009, Oracle. All rights reserved. Managing Schema Objects.
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Including Constraints
SQL Creating and Managing Tables
Database Systems Instructor Name: Lecture-12.
Manipulating Data Schedule: Timing Topic 40 minutes Lecture
Writing Correlated Subqueries
SQL Creating and Managing Tables
What Is a View? EMPNO ENAME JOB EMP Table EMPVU10 View
SQL Creating and Managing Tables
(SQL) Displaying Data from Multiple Tables
A Guide to SQL, Eighth Edition
IST 318 Database Administration
Displaying Data from Multiple Tables
Integrity Constraints
Presentation transcript:

1 Lecture 4 Data Integrity: Primary and Foreign Keys

2 But first - table aliases zTable name prefixes prevent ambiguity in a query remember emp.deptno=dept.deptno zBut they can be tedious to enter zSo we can define temporary labels in the FROM clause and use them elsewhere in the query. These temporary labels are called table aliases

3 Example without aliases zTo list information about all the employees in Chicago, enter: SELECTDEPT.DEPTNO, DNAME, LOC, ENAME, JOB FROM EMP, DEPT WHEREEMP.DEPTNO = DEPT.DEPTNO ANDEMP.DEPTNO = 30;

4 Abbreviating a Table Name using aliases ( Again to list information about all the employees in Chicago) SELECT D.*, ENAME, JOB FROM EMP E, DEPT D WHERE E.DEPTNO = D.DEPTNO AND E.DEPTNO = 30; Alias D.* retrieves all of the columns of the DEPT table This produces the same results as the last query Aliases E and D defined in the FROM clause The ‘join- condition’ defines the relationship between the two tables

5

6 Joining a table to itself zAliasing allows you to join a table to itself as though it was two separate tables. zUseful when we want to join one row in a table to another row in the same table. EMP MANAGER WORKER

7 List employees whose salary exceeds their manager’s SELECT WORKER.ENAME, WORKER.SAL, MANAGER.ENAME, MANAGER.SAL FROM EMP WORKER, EMP MANAGER WHEREWORKER.MGR = MANAGER.EMPNO ANDWORKER.SAL > MANAGER.SAL;

8 Manager Worker

9 Result is ENAMESAL SCOTT3000 JONES2975 FORD3000 JONES2975 zSCOTT’s row is joined to JONES’s because SCOTT’s MGR is 7566 and JONES’s EMPNO is 7566

10 Topics zReferential Integrity yTable constraints: xPrimary Keys xForeign Keys xOn delete cascade xCheck xDefault

11 Referential Integrity zOracle 7 onwards allows the use of table constraints to enforce referential integrity. That is, the data in tables must be consistent. Imagine inserting an employee with department 60! The table constraints allow us to enforce that this cannot happen. z(reading chapter 5 Dowling)

12 Definition zReferential Integrity; rules in a database that ensure that data is valid and consistent. zWhereas individual constraints can be used to ensure the validity of data in a single column or a table, referential integrity constraints ensure the validity of data between tables. – N.Dowling Database Design and Management (1998)

13 Primary Key zColumn(s) can have the primary key constraint placed on them, this has the following affect: yNo duplicate values yUnique index created for column(s) yCannot have NULL values

14 Primary Key zExamples from “our” tables are empno in myemp and deptno in mydept. zOnly one Primary key is allowed per table but the key can consist of several columns

15 Foreign Key zReferences a primary key in another table, example deptno in myemp (foreign key) references deptno in mydept (primary key) and is thus used to join the tables. zForeign Keys can also be specified in table constraints.

16 deptnodname loc empnoenamejobdeptno. MYDEPT TABLE primary key foreign key MYEMP TABLE mgrhiredate

17 Referential Integrity zTo examine this let us look at an example zCurrently (as there are no table constraints) we can insert an employee with department number 60. INSERT INTO myemp (empno, deptno) VALUES (1234, 60);

18

19 Table Constraints zWe can use alter table to add constraints: ALTER TABLE mydept ADD CONSTRAINT tab_mydept_pk PRIMARY KEY (deptno); zThis defines deptno as a primary key in table mydept. This means NULLs are no longer allowed and every value must be unique.

20 Table Constraints zIn the previous example, we named the constraint tab_mydept_pk. The name is arbitrary but using a name like tab_mydept_pk tells us a lot about the constraint. zOracle will use this name in any error messages it generates (thus helping us to identify the cause of the problem).

21 Table Constraints zNow we add the foreign key constraint to the myemp table ALTER TABLE myemp ADD CONSTRAINT tab_myemp_fk FOREIGN KEY (deptno) REFERENCES mydept (deptno);

22 Table Constraints zNow try to insert an employee with department number 60. zINSERT INTO myemp (empno, deptno) VALUES (1234, 60); zERROR at line 1: ORA-02291: integrity constraint (SPB001.TAB_MYEMP_FK) violated - parent key not found

23 Table Constraints zWe can also ensure that if a master or primary key row is deleted all the foreign or detail records get deleted with the ON DELETE CASADE constraint

24 Table Constraints zALTER TABLE myemp ADD CONSTRAINT tab_emp_fk FOREIGN KEY (deptno) REFERENCES mydept (deptno) ON DELETE CASCADE;

25 Table Constraints zChecks can also be applied to data or defaults supplied with table constraints. These are used to define conditions that every row must fulfil. zCONSTRAINT salary_check CHECK (sal > 2000 and deptno =10) zThis condition can ONLY refer to columns within the same table

26 Table Constraints zThe default constraint defines a value for a column that will be assigned whenever a row is inserted that does not have an explicit value for the column zCREATE TABLE little_example (city VARCHAR2(20) DEFAULT (‘Stirling’), text VARCHAR2(5) DEFAULT (‘#####’));

27 Table Constraints zThe unique constraint ensure that one or more columns are unique within that table. Unlike a primary key, NULLs are allowed. zCREATE TABLE another_example (cityVARCHAR(20) UNIQUE);

28 Table Constraints zCan dropped, disabled and enabled ALTER TABLE DROP CONSTRAINT ; ALTER TABLE DISABLE CONSTRAINT ; ALTER TABLE ENABLE CONSTRAINT ;

29 Table Constraints zThese can be placed on a table when it is created. CREATE TABLE new_emp (a_empno NUMBER(4), …, CONSTRAINT tab_new_emp_pk PRIMARY KEY(a_empno),…);

30 Summary zReferential Integrity yTable constraints: xPrimary Keys xForeign Keys xOn delete cascade xCheck xDefault