SQL Data Definition: Table Creation ISYS 464 Spring 2002 Topic 11 Student Course Database Student (Student Number, Student Name, Major) Course (Course Number, Course Name, Day, Time) Student Course (Student Number, Course Number) Student Student Student Major Number Name 123 Joe IS 234 Fred IS 345 Mary Acct 456 Sue Mgmt 567 Lee Acct Course Course Course Name Day Time Number ISYS 365 Adv C++ MW 12:30 ISYS 464 Database TTh 9:30 ISYS 565 Data Comm TTh 14:00 IBUS 330 Int Business MW 8:00 FIN 350 Finance MW 14:00 MGMT 405 Org Behavior MW 15:30 MKTG 431 Marketing TTh 8:00 Student Course Student Number Course Number 123 ISYS 365 123 FIN 350 123 MGMT 405 234 ISYS 365 234 FIN 350 234 MGMT 405 234 MKTG 431 345 ISYS 464 567 ISYS 464 567 ISYS 565 567 MGMT 405 678 ISYS 363 678 MGMT 405 1 2 Relational Database Integrity: Entity Integrity No part of a primary key can be null Consequence: Each row has a unique primary key The primary key does not have attributes that are not needed (i.e., it is minimal) Specified when table is created 3 Relational Database Integrity: Referential Integrity A foreign key must either: Match its corresponding primary key in the parent relation, or Be null Consequence: No tuple in a child relation can exist without a matching tuple in the parent relaton, unless its foreign key value is null We cannot add a child to a database without first adding the parent, unless the child's foreign key is null Examples: Trees Networks Specified when table is created 4 CREATE TABLE Statement Basic syntax: CREATE TABLE tablename (columnname datatype {,...}) Reserves space for a table Creates meta-data for a table Does not populate the table Create simple table CREATE TABLE Student Student_Name CHAR(12), Major CHAR(6)) This form does not create a primary key Entity integrity can be violated 5 Primary Key Constraint PRIMARY KEY (columnnamelist) Unique primary key is enforced Enforces entity integrity (no NULL values allowed for any part of primary key) Example: Create table with primary key CREATE TABLE Student Student_Name CHAR(12), Major CHAR(6), PRIMARY KEY (Student_Number)) Example: Create table with composite primary key CREATE TABLE Student_Course Course_Number CHAR(14), PRIMARY KEY (Student_Number, Course_Number)) 6. Not for general distribution. 1
Datatypes SMALLINT INTEGER INT DECIMAL(p,s) DEC(p,s) NUMERIC(p,s) NUMBER(p,s) CHARACTER(n) CHAR(n) VARCHAR(n) CHAR VARYING(n) CHARACTER VARYING(n) VARCHAR2(n) DATE BLOB CLOB Oracle Datatypes Data type Description Comments Standard SMALLINT Integer data between 32768 and +32767 SQL_92 INTEGER Integer data between 2^31 and +2^31 SQL_92 INT DECIMAL(p,s) Decimal numeric data of length p Default p = 38 SQL_92 DEC(p,s) NUMERIC(p,s) (precision) with s (scale) positions to right of decimal point Default s = 0 0<=s<=p<=38 NUMBER(p,s) Synonymous with DECIMAL(p,s) Oracle CHARACTER(n) CHAR(n) VARCHAR(n) CHAR VARYING(n) CHARACTER VARYING(n) Fixed length character data of a length n. Unused characters are filled with blanks on the right. Variable length character data of a maximum length of n. If data is < n in length, no blanks are filled on the right. Default n = 1 Max n = 4096 Default n = 1 Max n = 4096 SQL_92 SQL_92 VARCHAR2(n) Synonymous with VARCHAR(n) Oracle DATE Date Default format: SQL_92 DD-MON-YY BLOB Binary large object Max size: 4 GB Oracle CLOB Character large object Max size: 4 GB Oracle 7 8 NOT NULL constraint Prevents column from containing a NULL value Syntax: NOT NULL UNIQUE constraint Prevents non-unique values in a column; allows NULL values Syntax: UNIQUE Example: CREATE TABLE Course (Course_Number CHAR (14), Course_Name CHAR(12) UNIQUE, Day CHAR (3) NOT NULL, Time CHAR (5) NOT NULL, PRIMARY KEY (Course_Number)) Note: PRIMARY KEY column(s) is automatically NOT NULL and UNIQUE 9 DEFAULT constraint; Sets default value for column if no value is inserted Syntax: DEFAULT literal literal must be same type as datatype of column Example: CREATE TABLE Student Student_Name CHAR(12), Major CHAR(6) DEFAULT 'IS', PRIMARY KEY (Student_Number)) 10 CHECK constraint; Prevents insertion into column of any value that violates of constraint Syntax: CHECK (columnname restriction) restriction can use: <, >, =, <=, >=, <> BETWEEN x AND y IN (set of values) AND, OR, NOT with other restrictions CREATE TABLE Sample_Table ( B_Col CHAR(5), C_Col DEC(10,2) NOT NULL UNIQUE, D_Col INTEGER UNIQUE CHECK (D_Col >= 0), E_Col SMALLINT DEFAULT 0 CHECK (E_Col BETWEEN 0 AND 100), F_Col CHAR(1) DEFAULT 'S' CHECK (F_Col IN ('S','M','D')), PRIMARY KEY (A_Col, B_Col)) 11 12. Not for general distribution. 2
FOREIGN KEY Constraint FOREIGN KEY (columnnamelist) REFERENCES tablename Appears in CREATE TABLE statement for table with foreign key (child) Columnnamelist can refer to single column foreign key or composite foreign key Tablename identifies table in which foreign key is primary key Foreign key does not have to have same name as corresponding primary key Must create parent before creating child with FOREIGN KEY key constraint FOREIGN KEY constraint enforces referential integrity Without FOREIGN KEY constraint referential integrity is not enforced First_Table (A_Col, B_Col, C_Col) Second_Table (X_Col, Y_Col, Z_Col, A_Col) A_Col is foreign key in Second_Table that relates Second_Table to First_Table 13 FOREIGN KEY Constraint Create parent table: CREATE First_Table ( B_Col CHAR(5), C_Col DEC (8,2), PRIMARY KEY (A_Col)) Create child table with foreign key: CREATE Second_Table (X_Col CHAR(10), Z_Col INTEGER, PRIMARY KEY (X_Col, Y_Col), ) 14 Referential Integrity Restrictions Operation Parent Child Unrestricted Rejected if inserted row has a INSERT foreign key that does not match a Rejected if deletion leaves an Unrestricted DELETE unmatched foreign key in a child Rejected if value of parent's primary Rejected if value of child's foreign key is changed in a way that leaves a key is changed in a way that leaves UPDATE foreign key of a child unmatched the foreign key unmatched with a with the primary key 15 ON DELETE CASCADE Option Syntax: ON DELETE CASCADE Causes child rows to be deleted when parent row is deleted ("cascade delete") CREATE Second_Table (X_Col CHAR(10), Z_Col INTEGER, PRIMARY KEY (X_Col, Y_Col), ON DELETE CASCADE) 16 ON DELETE CASCADE Option Referential Integrity Restrictions ON DELETE CASCADE Operation Parent Child Unrestricted Rejected if inserted row has a INSERT* foreign key that does not match a Parent deleted. All children with Unrestricted DELETE matching foreign keys are deleted Rejected if value of parent's primary Rejected if value of child's foreign key is changed in a way that leaves a key is changed in a way that leaves UPDATE* foreign key of a child unmatched the foreign key unmatched with a with the primary key * Same as without ON DELETE CASCADE 17 ON DELETE SET NULL Option Syntax: ON DELETE SET NULL Causes foreign keys of child rows to be set to NULL when parent row is deleted Used when child rows need to be kept rather than deleted CREATE Second_Table (X_Col CHAR(10), Z_Col INTEGER, PRIMARY KEY (X_Col, Y_Col), ON DELETE SET NULL) 18. Not for general distribution. 3
ON DELETE SET NULL Option Referential Integrity Restrictions ON DELETE SET NULL Operation Parent Child Unrestricted Rejected if inserted row has a INSERT* foreign key that does not match a Parent deleted. Foreign keys of all Unrestricted DELETE children with matching foreign keys are set to NULL Rejected if value of parent's primary Rejected if value of child's foreign key is changed in a way that leaves a key is changed in a way that leaves UPDATE* foreign key of a child unmatched the foreign key unmatched with a with the primary key * Same as without ON DELETE CASCADE 19 Changing Key Values How to change the primary key of a parent and all matching children: 1. Insert parent with new primary key 2. Update foreign key of all children of old parent to new primary key value 3. Delete old parent 20 Complex Example First_Table (A_Col, B_Col, C_Col) Second_Table (X_Col, Y_Col, Z_Col, A_Col) Third_Table (S_Col, T_Col, A_Col, X_Col, Y_Col) A_Col in Second_Table is a foreign key that relates Second_Table to First_Table A_Col in Third_Table is a foreign key that relates Third_Table to First_Table X_Col + Y_Col is a composite foreign key in Third_Table that relates Third_Table to Second_Table Problem: Write statement to create Third_Table 21 Complex Example Solution: CREATE TABLE Third_Table (S_Col SMALLINT, T_Col DEC(12,4), X_Col CHAR(10), PRIMARY KEY (S_Col), ON DELETE SET NULL, FOREIGN KEY (X_Col, Y_Col) REFERENCES Second_Table ON DELETE CASCADE) 22 CREATE TABLE Statement: Complete Syntax CREATE TABLE tablename (columnname datatype [NOT NULL] [UNIQUE] [DEFAULT literal] [CHECK (columnname restriction)] {,...} [, PRIMARY KEY (columnnamelist)] [, FOREIGN KEY (columnnamelist) REFERENCES tablename [ON DELETE CASCADE SET NULL]] {,...} ) Populating Tables in a Database If referential integrity is not enforced (i.e., no foreign keys are specified), tables in database can be populated in any order If referential integrity is enforced, tables in database must be populated "top down": Parent table must be populated before child table If a child table has two parent tables, both parent tables must be populated before the child table is populated 23 24. Not for general distribution. 4
Deleting Rows in Tables If referential integrity is not enforced, rows in parent and child tables can be deleted in any order If referential integrity is enforced without the ON DELETE option, rows in child table must be deleted before corresponding rows in parent table are deleted If referential integrity is enforced with the ON DELETE option, rows in parent and child tables can be deleted in any order Deleting a parent row will delete all matching child rows or set their foreign key values to NULL DROP TABLE Statement Syntax: DROP TABLE tablename Deletes table from database DROP TABLE First_Table 25 26 Dropping Tables in a Database If referential integrity is not enforced, parent and child tables can be dropped in any order If referential integrity is enforced without the ON DELETE option, tables must be dropped "bottom up": Child table must be dropped before parent table is dropped If a parent table has two child tables, both child tables must be dropped before the parent table is dropped If referential integrity is enforced with the ON DELETE option, parent and child tables can be dropped in any order Dropping a parent table will not drop a child table but will delete all matching child rows or set their foreign key values to NULL The child table must be dropped separately 27 ALTER Statement Syntax 1: ALTER TABLE tablename ADD (columnname datatype {,... }) Adds a column to a table Example: ALTER TABLE First_Table ADD D_Col CHAR(30) Syntax 2: ALTER TABLE tablename MODIFY (columnname datatype {,... }) Changes the datatype of a column in a table New datatype must not be smaller than previous datatype Example: ALTER TABLE First_Table MODIFY (X_Col CHAR(15)) Syntax 3: ALTER TABLE tablename DROP COLUMN columnname Deletes a column of table Example: ALTER TABLE First_Table DROP COLUMN Y_Col Note: It is best not to alter a table once it is create because doing so can create data problems. Better approach: Create a new table with all the alterations and then populate it with data from the old table. 28 Summary of Statements To create the tables in a database: CREATE TABLE for each table ALTER TABLE to add column, change datatype of column, delete column in existing table To populate the tables in a database: INSERT initial data into each table To access the data in the tables of a database: SELECT data from one or more tables To change the data in the tables of a database INSERT new data into a table DELETE data from a table UPDATE data in a table To delete a table: DROP TABLE Script Files Script file is a text file with a sequence of SQL statements Any SQL statement can be in a script file Each statement must end with a semicolon (;) Use a text editor such as Notepad to create a script file Do not use a word processor such as Word or WordPad Upload script file to your libra account using FTP Execute script file using the SQL*Plus start (or @) command If script file has extension.sql then no extension is needed in start command 29 30. Not for general distribution. 5
Using a Script File to Create and Populate a Database Order of steps in script file to create and populate a database: Use DROP TABLE statements to drop all tables to be created in case they already exist. Be sure to drop tables in correct order Use CREATE TABLE statements to create all new tables Use INSERT statements to populate new tables Be sure to populate tables in correct order Use COMMIT statement to make all updates permanent Example: Script File to Create and Populate Inventory-Quotation-Supplier Database See createiqs.txt file 31 32. Not for general distribution. 6