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