Step 0 How to begin and what you need to do before you start?

Similar documents
Step 0 How to begin and what you need to do before you start?

Step 0 How to begin and what you need to do before you start?

Step 0 How to begin and what you need to do before you start?

Step 0 How to install VirtualBox on Windows operating system?

Step 0 How to begin and what you need to do before you start?

Step 0 How to begin and what you need to do before you start?

CSIT115/CSIT815 Data Management and Security Assignment 2

CHAPTER4 CONSTRAINTS

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

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

Data Definition Language (DDL)

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

School of Computing and Information Technology. Examination Paper Autumn 2016

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

The appendix contains information about the Classic Models database. Place your answers on the examination paper and any additional paper used.

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.

School of Computing and Information Technology. Examination Paper Autumn Session 2017

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

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Creating Tables, Defining Constraints. Rose-Hulman Institute of Technology Curt Clifton

SQL Server. Lecture3 Cascading referential integrity constraint

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

Comp 5311 Database Management Systems. 4b. Structured Query Language 3

Eessaar, E. "On Query-based Search of Possible Design Flaws of SQL Databases" Introduction Queries that are used to detect design flaws...

School of Computing and Information Technology Session: Spring CSCI835 Database Systems (Bridging Subject) Sample class test 23 July 2018

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

Conceptual Design. The Entity-Relationship (ER) Model

Lecture 07. Spring 2018 Borough of Manhattan Community College

Database Programming - Section 10. Instructor Guide

Oracle Create Table Foreign Key On Delete No

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

CS2300: File Structures and Introduction to Database Systems

Referential integrity

Module 9: Managing Schema Objects

MTAT Introduction to Databases

3ISY402 DATABASE SYSTEMS

DATA CONSTRAINT. Prepared By: Dr. Vipul Vekariya

Where Are We? Next Few Lectures. Integrity Constraints Motivation. Constraints in E/R Diagrams. Keys in E/R Diagrams

Practice questions recommended before the final examination

DATABASE TECHNOLOGY - 1MB025 (also 1DL029, 1DL300+1DL400)

DATABASE DESIGN - 1DL400

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

DATABASE DESIGN - 1DL400

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data.

Chapter 17: Table & Integrity Contraints. Informatics Practices Class XII. By- Rajesh Kumar Mishra. KV No.1, AFS, Suratgarh

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Cross-loading of Legacy Data Using the Designer/2000 Repository Data Model OBJECTIVES ABSTRACT

Logical database design

Full file at

CSCI235/CSCI835 Database Systems Assignment 1 5 August 2018

Relational Data Structure and Concepts. Structured Query Language (Part 1) The Entity Integrity Rules. Relational Data Structure and Concepts

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Relational Databases Fall 2017 Lecture 7

DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E)

LABSHEET 1: creating a table, primary keys and data types

Basic SQL. Basic SQL. Basic SQL

SQL Introduction. CS 377: Database Systems

3.1. Keys: Super Key, Candidate Key, Primary Key, Alternate Key, Foreign Key

5 Integrity Constraints and Triggers

AN ALGORITHM FOR MAPPING THE RELATIONAL DATABASES TO MONGODB A CASE STUDY

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

3.2.4 Enforcing constraints

COSC Assignment 2

SQL DATA DEFINITION LANGUAGE

ASSIGNMENT NO 2. Objectives: To understand and demonstrate DDL statements on various SQL objects

CSCU9Q5 Introduction to MySQL. Data Definition & Manipulation (Over ~two Lectures)

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

Data Modeling. Yanlei Diao UMass Amherst. Slides Courtesy of R. Ramakrishnan and J. Gehrke

Drop Table If Exists Sql Command Not Properly Ended

Translation of ER-diagram into Relational Schema. Dr. Sunnie S. Chung CIS430/530

Programming the Database

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Concepts of Database Management Seventh Edition. Chapter 4 The Relational Model 3: Advanced Topics

Downloaded from

Integrity constraints, relationships. CS634 Lecture 2

4 Schema Definition with SQL / DDL (II)

SQL: Data Definition Language

School of Computing and Information Technology Session: Spring CSCI835 Database Systems (Bridging Subject) Sample class test 23 July 2018

Lab # 4. Data Definition Language (DDL)

BI4Dynamics AX/NAV Integrate external data sources

ISYS1055/1057 Database Concepts Week 9: Tute/Lab SQL Programming

ACCESS isn t only a great development tool it s

Logical Database Design. ICT285 Databases: Topic 06

Microsoft MOS- Using Microsoft Office Access Download Full Version :

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

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

Domain Constraints Referential Integrity Assertions Triggers. Authorization Authorization in SQL

Chapter 11 How to create databases, tables, and indexes

Announcements (September 18) SQL: Part II. Solution 1. Incomplete information. Solution 3? Solution 2. Homework #1 due today (11:59pm)

Solved MCQ on fundamental of DBMS. Set-1

Intermediate SQL ( )

How to design a database

SQL Data Definition and Data Manipulation Languages (DDL and DML)

Introduction to Data Management CSE 344

Lecture 5. Monday, September 15, 2014

SQL STRUCTURED QUERY LANGUAGE

Database Applications (15-415)

Parameterizing an iway Data Quality Server SQL Statement From an Input File or the Command Line

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

Transcription:

Written and cooked by Janusz R. Getta, School of Computing and Information Technology, University of Wollongong Building 3, room 2120, ext 4339, jrg@uow.edu.au, http://www.uow.edu.au/ jrg ËÁ̽½ Ø Å Ò Ñ ÒØ Ò Ë ÙÖ ØÝ Ê Ô º½ ÀÓÛ ØÓ Ö Ø Ò ÓÛ ØÓ ÐØ Ö Ø Ö Ð Ø ÓÒ Ð Ø Ð Table of contents Step 0 How to begin and what you need to do before you start? Step 1 How to create a new relational table? Step 2 How to add a column to a relational table? Step 3 How to add a referential integrity constraint to a relational table? Step 4 How to enforce a domain consistency constraint? Step 5 How to make an attribute compulsory? Step 6 How to remove a column from a relational table? Step 7 How to drop a referential integrity constraint? Step 8 How to add a row whout dropping a referential integrity constraint Step 9 How to delete a row referenced by a value of foreign key? Step 10 How to update a value of primary key? Step 0 How to begin and what you need to do before you start? A printable copy of this experiment in pdf format is available here (www.uow.edu.au/~jrg/115/howto/ e4-1.pdf). Logon to your Win 7 system and start VirtualBox. Next, either import your appliance from your USB drive and start imported virtual machine or use one of the brand new virtual machines available on your Win 7 system. Logon to Ubuntu operating system as csit115 user. Start Terminal icon to open Terminal application. We use command line interface to communicate with mysql database server. Next, we create a new folder to save SQL scripts used and created in the present experiment. To create a new folder recipe4.1 execute the following command in Terminal window. mkdir recipe4.1 A new folder recipe4.1 will is created in the current folder of a user csit115 i.e. in a folder /home/csit115. Next, make a folder recipe4.1 the current folder of csit115 user. Execute a command cd recipe4.1 to navigate to a folder recipe4.1. Then start to start a command based interface to MySQL database server and to logon as a user csit115 execute the following command. mysql csit115 -p -v Next, use a command use csit115; 1

to connect to a database csit115. Next, download and uncompress SQL scripts in zip format (www. uow.edu.au/~jrg/115/howto/home4.zip) used in this experiment. The scripts should be uncompressed into an earlier created folder recipe4.1. Next, execute a script file dbcreate4-1.sql (www.uow.edu.au/~jrg/115/howto/dbcreate4-1.sql) to create a sample relational database. To remove the database from your account you may use a script dbdrop4-1.sql (www.uow.edu.au/~jrg/115/ HOWTO/dbdrop4-1.sql) Do not execute the script now! A sample database created now contains information about departments, locations of departments, employees, and locations of employees. Analysis of primary and foreign keys in a file dbcreate4-1.sql (www.uow.edu.au/ ~jrg/115/howto/dbcreate4-1.sql) with CREATE TABLE statements provides a logical schema (www.uow. edu.au/~jrg/115/howto/schema1.pdf) of a sample database. Reverse engineering of a logical schema (www.uow.edu.au/~jrg/115/howto/schema1.pdf) provides an equivalent conceptual schema (www.uow.edu.au/~jrg/115/howto/schema2.pdf) of a sample database. A further restructuring provides a conceptual schema (www.uow.edu.au/~jrg/115/howto/schema3.pdf) equivalent to the previous one. Step 1 How to create a new relational table? This action adds a new relational table to a collection of relational tables created in the previous step. Assume that we would like to add to the database created in the previous step information about the projects and departments involved in implementation of the projects. To simplify a design, assume that each department and all employees from such a department work on exactly one project and each project can be implemented by more than one department. Projects are described by project number (PNUM), title TITLE), budget (BUDGET), start, and end dates (STARTD, ENDD). As we mentioned above, an association between the projects and departments is one-to-many. Therefore, we have to create a new relational table PROJECT where PNUM is a primary key. As a consequence, we have to add PNUM as a foreign key to a table DEPARTMENT. To create a new relational table PROJECT execute a script file prjcreate.sql (www.uow.edu.au/~jrg/115/ HOWTO/prjcreate.sql). The script contains the following CREATE TABLE statement: CREATE TABLE PROJECT( PNUM DECIMAL(6) NOT NULL, TITLE VARCHAR(200) NOT NULL, BUDGET DECIMAL(9,2) NULL, STARTD DATE NOT NULL, ENDD DATE NOT NULL, CONSTRAINT PROJECT_PKEY PRIMARY KEY (PNUM)); Execute a statement describe PROJECT; 2

to verify the structures of a relational table PROJECT. After addition of a relational table PROJECT a sample database has the following conceptual schema (www.uow. edu.au/~jrg/115/howto/schema4.pdf). Step 2 How to add a column to a relational table? Now, we add a column PNUM to a relational table DEPARTMENT. A script file pnumadd.sql (www.uow.edu.au/ ~jrg/115/howto/pnumadd.sql) contains the following ALTER TABLE statement, that adds a column PNUM to a relational table DEPARTMENT. ALTER TABLE DEPARTMENT ADD (PNUM DECIMAL(6)); Execute a script pnumadd.sql (www.uow.edu.au/~jrg/115/howto/pnumadd.sql) and then execute the following command to verify the results. describe DEPARTMENT; Step 3 How to add a referential integrity constraint to a relational table? Now, the tables PROJECT and DEPARTMENT are ready to be linked through a referential integrity constraint. An attribute PNUM in a table DEPARTMENT should become a foreign key referencing a primary key attribute (PNUM) in a table PROJECT. This action adds a referential integrity constraint to a table DEPARTMENT. The action makes an attribute PNUM a foreign key referencing PNUM in a table PROJECT. A script file refcreate.sql (www.uow.edu.au/~jrg/115/ HOWTO/refcreate.sql) contains the following ALTER TABLE statement. ALTER TABLE DEPARTMENT ADD CONSTRAINT DEPARTMENT_FKEY FOREIGN KEY (PNUM) REFERENCES PROJECT(PNUM); Execute a script refcreate.sql (www.uow.edu.au/~jrg/115/howto/refcreate.sql) and next execute the following command describe DEPARTMENT; to verify the results. It is possible to get more information about referential integrity constraint from a system data dictionary (system catalog) tables included in a database INFORMATION_SCHEMA. For example execute the following statement SELECT CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = csit115 ; to list the names and types of constraints create by csit115 user. 3

Accesing the relational tables included in a database INFORMATION_SCHEMA (data dictionary or system catalog) is tried in another recipe in this group. Step 4 How to enforce a domain consistency constraint? Next, we add a consistency constraint to a relational table PROJECT that enforces a start date (STARTD) of each project to be older than end date (ENDD). This action enforces a domain consistency constraint saying that each project must take least 4 weeks. To enforce the consistency constraints listed above execute a script file checkcreate.sql (www.uow.edu.au/ ~jrg/115/howto/checkcreate.sql) that contains the following ALTER TABLE statement. ALTER TABLE PROJECT ADD CONSTRAINT PROJECT_CHECK CHECK (STARTD <= ADDDATE(ENDD, -28)); Verification of the results with a statement SELECT CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = csit115 ; does not confirm the existence of a constraint PROJECT_CHECK. It is because MySQL does not enforce domain constraint. Syntax of ALTER TABLE statement is accepted and a constraint is not enforced. CHECK condition listed above uses a function ADDDATE(date, days) that adds days to a given date. The same condition can be also expressed as DATEDIFF(ENDD, STARTD) >= 28 which means that the condition is true if it passed 28 or more days from STARTD to ENDD. A function DATEDIFF(date1,date2) finds the total number of days from date2 to date1. A call to a standard function CURDATE() returns the current date. Hence, a call to a function ADDATE(CURDATE(), -1) means yesterday while a call ADDDATE(CURDATE(), 1) means tomorrow. A function SYSDATE() returns date and timewhen the function executes wth a precision up to a single second. For example, a statement: SELECT SYSDATE() FROM DUAL; lists the most precise date and time. An expression ADDTIME(SYSDATE(), -1:20:5 ) means 1 hour 20 minutes and 5 seconds ago and an expression ADDTIME(SYSDATE(), 3:0:1 ) 3 hours and 1 second in the future. A function ADDTIME(date-time, period) adds a period of time formatted as days hour:minutes:seconds to date-time. Step 5 How to make an attribute compulsory? Next, we add a consistency constraint to a relational table PROJECT that forces a value of an attribute (BUDGET) to be provided( NOT NULL) for each project. This action makes an attribute BUDGET compulsory for each row in PROJECT table. To achieve this goal we have to change NOT NULL/NULL clause of an attribute BUDGET. A script file setnotnull.sql (www.uow.edu.au/~jrg/ 4

115/HOWTO/setnotnull.sql) contains the following ALTER TABLE statement. ALTER TABLE PROJECT MODIFY BUDGET DECIMAL(9,2) NOT NULL; Execute the script and to verify the results execute the following command. describe PROJECT; Step 6 How to remove a column from a relational table? Next, we remove a column TITLEfrom a relational table PROJECT. A file coldrop.sql (www.uow.edu.au/~jrg/115/howto/coldrop.sql) contains the following ALTER TABLE statement. ALTER TABLE PROJECT DROP TITLE; Execute the script and and to verify the results execute the following command. describe PROJECT; If we would like to drop a column referenced by another column, for example PNUM in table PROJECT then we have to add CASCADE CONSTRAINTS clause to ALTER TABLE statement in a way presented below (do not do it now!). ALTER TABLE PROJECT DROP (PNUM) CASCADE CONSTRAINTS; Step 7 How to drop a referential integrity constraint? In the next two actions we shall temporarily drop and recreate a referential integrity constraint. Assume, that we would like to assign a project number 777 to MI6 department. However, at the moment we do not have full information about the project, for example we do not know what are the values of compulsory attributes STARTD and ENDD. Hence we are unable to insert description of project 777 into a relational table PROJECT. To assign a project 777 to a new department MI6 without the insertion of the project into PROJECT table is impossible due to a referential integrity constraint. If we execute a statement INSERT INTO DEPARTMENT VALUES( MI6, 999, J. Bond, 777 ); then the system rejects the insertion with the following message. ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ( csit115. DEPARTMENT, CONSTRAINT DEPARTMENT_FKEY FOREIGN KEY ( PNUM ) REFERENCES PROJECT ( PNUM )) One of the solutions is to drop for a certain period of time a referential integrity constraint set up in step 3. In the nearest future, we will add a description of project 777 to PROJECT table and then we shall re-create DEPART- MENT_FKEY constraint. This step drops a referential integrity constraint DEPARTMENT_FKEY. SQL script refdrop.sql (www.uow.edu.au/ ~jrg/115/howto/refdrop.sql) contains the following ALTER TABLE statement. 5

ALTER TABLE DEPARTMENT DROP FOREIGN KEY DEPARTMENT_FKEY; Execute the script to drop a referential integrity constraint DEPARTMENT_FKEY. To verify whether a referential integrity constraint has been drop execute the following statement. SELECT CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = csit115 ; Now it is possible to insert a row INSERT INTO DEPARTMENT VALUES( MI6, 999, J. Bond, 777 ); into a relational table DEPARTMENT first and a row INSERT INTO PROJECT VALUES(777, 1000000, 2015-01-01, 2017-12-31 ); into a relational table PROJECT later on. To restore a referential integrity constraint execute a script refcreate.sql (www.uow.edu.au/~jrg/115/howto/ refcreate.sql) Step 8 How to add a row whout dropping a referential integrity constraint It is possible to insert a row into a relatiopnal table DEPARTMENT without dropping a referential integrity constraint. It is a better solution because we do not create an opportunity for corruption of a database. A quite simple solution is to set a value of attribute PNUM to NULL because a value of a foreign key can be missing (NULL). Execute the following INSERT statement. INSERT INTO DEPARTMENT( MAGIC, 666, H. Potter, NULL); Step 9 How to delete a row referenced by a value of foreign key? Assume that we would like to delete the only location in CHICAGO. A simple DELETE statement DELETE FROM DEPTLOC WHERE CITY = CHICAGO AND STREET = 34 AND BLDG = 1 AND BLEVEL = 90; included in a script delchicago.sql (www.uow.edu.au/~jrg/115/howto/delchicago.sql) unfortunately returns the following error. ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails ( csit115. EMPLOYEE, CONSTRAINT EMPLOYEE_FKEY2 FOREIGN KEY ( DNAME, CITY, STREET, BLDG, BLEVEL ) REFERENCES DEPTLOC ( DNAME, CITY, STREET, BLDG, BLEVEL )) This is because there exists an employee in the location and a value of foreign key in a table EMPLOYEE looses the respective value of primary key in a relational table DEPTLOC. 6

To solve the problem we have to first replace the values of a foreign key in a relational table EMPLOYEE with NULLs and next delete a row from a relational table DEPTLOC A script file nullchicago.sql (www.uow.edu.au/~jrg/115/howto/nullchicago.sql) contains the following UPDATE statement that sets to NULL the values of attributes DNAME, CITY, STREET, BLDG, and BLEVEL in a row of employee number 7521. In the future we shall use more advanced UPDATE statement that finds the numbers of all employees in CHICAGO as a the results of SELECT statement. Execute a script nullchicago.sql (www.uow.edu.au/~jrg/115/howto/nullchicago.sql). Next, execute a script delchicago.sql (www.uow.edu.au/~jrg/115/howto/delchicago.sql). Step 10 How to update a value of primary key? Assume that we would like to move the only location in PARIS from a level 34 to a level 99. A simple UPDATE statement UPDATE DEPTLOC SET BLEVEL = 99 WHERE CITY = PARIS AND STREET = 19 AND BLDG = 77 AND BLEVEL = 34; included in a script updparis.sql (www.uow.edu.au/~jrg/115/howto/updparis.sql) unfortunately returns the following error. ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails ( csit115. EMPLOYEE, CONSTRAINT EMPLOYEE_FKEY2 FOREIGN KEY ( DNAME, CITY, STREET, BLDG, BLEVEL ) REFERENCES DEPTLOC ( DNAME, CITY, STREET, BLDG, BLEVEL )) This is because there exists an employee in the location and a value of foreign key in a table EMPLOYEE looses the respective value of primary key in a relational table DEPTLOC. To solve the problem we have to first replace value of attribute BLEVEL of a foreign key in a relational table EM- PLOYEE with NULL, update a row in a relational table DEPTLOC, and finally set the respective value of an attribute BLEVEL in a foreign key earlier chnaged to NULL. A script file nullparis.sql (www.uow.edu.au/~jrg/115/howto/nullparis.sql) contains the following UP- DATE statement that sets to NULL the values of attribute BLEVEL in a row of employee number 7521. In the future we shall use more advanced UPDATE statement that finds the numbers of all employees in CHICAGO as a the results of SELECT statement. Execute a script nullparis.sql (www.uow.edu.au/~jrg/115/howto/nullparis.sql). Next, execute a script updparis.sql (www.uow.edu.au/~jrg/115/howto/updparis.sql). Finally, execute a script setparis.sql (www.uow.edu.au/~jrg/115/howto/setparis.sql) to set appropiate value of an attribute BLEVEL in a relational table EMPLOYEE. References MySQL 5.7 Reference Manual, ALTER TABLE statement (http://dev.mysql.com/doc/refman/5.7/en/alter-table.html) MySQL 5.7 Reference Manual, CREATE TABLE statement (http://dev.mysql.com/doc/refman/5.7/en/create-table.html) 7

MySQL 5.7 Reference Manual, DELETE statement (http://dev.mysql.com/doc/refman/5.7/en/delete.html) MySQL 5.7 Reference Manual, DROP TABLE statement (http://dev.mysql.com/doc/refman/5.7/en/drop-table.html) MySQL 5.7 Reference Manual, INSERT statement (http://dev.mysql.com/doc/refman/5.7/en/insert.html) MySQL 5.7 Reference Manual, SELECT statement (http://dev.mysql.com/doc/refman/5.7/en/select.html) MySQL 5.7 Reference Manual, UPDATE statement (http://dev.mysql.com/doc/refman/5.7/en/update.html) 8