Lab 7 Aim: Creating Simple tables in SQL Basic Syntax for create table command is given below: CREATE TABLE <table_name> ( <column_name> <data_type> [DEFAULT <expression>] [<column_constraint>], {<column_name> <data_type> [DEFAULT <expression>] [column_constraint>],} [<table_constraints>] ); The parts enclosed in square brackets ([ ]) are optional. Curly braces ({ } )indicate that the enclosed expression can be repeated zero or many times. Angle brackets (< >) indicate that these are meta symbols that would be replaced by actual symbols of the language. Underlined paranthesis are part of the command. (Of course you do not underline them when you write the actual command in SQL*Plus J ) <column_name> should be replaced by actual column (attribute) names of the table. <data_type> can be one of the following: VARCHAR2(size): Variable length character string up to maximum length size CHAR(size): Fixed length character string of length size NUMBER: Floating point number with a precision of 38 significant digits NUMBER(p,s): Number with a maximum precision p and maximum scale s. Scale is the number of digits to the right of the decimal point. DATE: Date and time values between January 1, 4712 B.C. and December 31, 4712 A.C. LONG: Variable Length charcater values up to 2GB. Only one LONG column is allowed per table RAW or LONG RAW: Equivalent to VARCHAR2 and LONG, respectively, but used to store byte oriented or binary data Table and column constraints are formed using one of the following constraint keywords. <constraint_type> NOT NULL: Specifies that a given column cannot contain any NULL values UNIQUE: Specifies that values in a column or a combination of columns must be all unique. A unique index (that has the same name as the unique constraint) is automatically created for UNIQUE column(s). PRIMARY KEY: Specifies that a column or a combination of columns must be all UNIQUE and NOT NULL. There can be only one PRIMARY KEY in each table. A UNIQUE index (whose name is the same as the constraint name) is created for the PRIMARY KEY. FOREIGN KEY REFERENCES: Establishes and enforces foreign key relationship between the specified column(s) and the referenced column(s) CHECK: Specifies that the given condition should always hold. A <column constraint> is a constraint that applies to a single column. <column_constraint> for PRIMARY KEY, UNIQUE and NOT NULL constraints is of the following form: [CONSTRAINT <constraint_name>] <constraint_type>
You do not have to give a name to each constraint. But it is a good practice to name all constraints, because constraint names are used the error messages and giving rational names to constraints makes it easier to understand the messages. <constraint_name> can be any name you choose. ORACLE suggests using the following combination tablename_columnname_abbreviation where abbreviation is pk for PRIMARY KEY, uk for UNIQUE KEY, fk for FOREIGN KEY, ck for CHECK CONSTRAINT and nn for NOT NULL CONSTRAINT. The form of a Foreign Key constraint that applies to a single column is [CONSTRAINT <constraint_name> ] REFERENCES < referenced_table> ( <referenced_attribute>) <referenced_table> is the parent table and the <referenced_attribute> is the primary or unique key of the parent table. CHECK constraint has the following form [CONSTRAINT <constraint_name> ] CHECK (<condition>) where, <condition> is a condition that should be satisfied for the column. Table constraints are the constraints that apply to more than one column. Table constraints are more general than the column constraints, therefore column constraints can be specified as table constraints. The form of PRIMARY KEY, UNIQUE and NOT NULL table constraints is given below: [CONSTRAINT <constraint_name>] <constraint> (<column_list>) The form for FOREIGN KEY table constraint is : [CONSTRAINT <constraint_name> ] FOREIGN KEY (<foreign_key_columns>) REFERENCES <referenced_table> ( <referenced_attribute>) The form for CHECK constraint at table level is the same as the column level CHECK constraint. Example 1: Create a table for keeping information about your friends. SQL> CREATE TABLE friend 2 (friendno NUMBER(2) CONSTRAINT friend_friendno_pk PRIMARY KEY, 3 name VARCHAR2(25) CONSTRAINT friend_name_nn NOT NULL, 4 phone VARCHAR2(15), 5 city VARCHAR2(10) DEFAULT 'GIRNE'); Table created. Column declarations are separated by a comma. If constraint names (shown in italic in the example) are not specified, ORACLE will assign an alphanumeric identifier (like SYS_C0026055) for each one of such constraints and use this identifier when it generates error messages: An example error message is given below:
ORA-00001: unique constraint (USER50.SYS_C0026055) violated In line 5 of the above command a default value is specified for the city. This means that if the city value is omitted in an insert statement by default it will be 'GIRNE'. If you want to assign NOT NULL to city, you have to do this explicitly! Example 2 : Consider the following command that creates the s_dept table SQL>CREATE TABLE s_dept 2 ( id NUMBER(7) 6 CONSTRAINT s_dept_id_pk PRIMARY KEY (id), 3 name VARCHAR2(25) CONSTRAINT s_dept_name_nn NOT NULL, 4 region_id NUMBER(7) 5 CONSTRAINT s_dept_region_id_fk REFERENCES s_region(id), 6 CONSTRAINT s_dept_name_region_id_uk UNIQUE (name, region_id)); In the above command, on line 5, you see a foreign key constraint declaration. This constraint forces the region_id column to take only the values that are stored in the id column of the s_region. The table that contains the foreign key is called the child table and the table that contains the referenced column is called the parent table. In this case s_dept is the child and s_region is the parent. You have to make sure that the referenced column (or columns) in the parent table have UNIQUE constraint. (Remember: PRIMARY KEY is UNIQUE and NOT NULL!!!) The table constraint on line 6, ensures that the combination of the values for name and region_id of a department will be unique in the whole table. ALTERING AN EXISTING TABLE Another command that you might find useful when creating a table is the ALTER TABLE command. Modifications allowed without any restrictions include: --Adding a new column to the table. --Deleting a foreign key constraint from a table. --Deleting a primary key constraint from a table, which also removes any references to it from other tables in the database with CASCADE clause. --Increasing the size of a column. For example, VARCHAR2(15) can be changes to VARCHAR2(20). --Renaming columns. --Renaming constraints. Modifications allowed with restrictions include: --Adding a foreign key constraint is allowed only if the current values are null or exist in the references table's primary key. --Adding a primary key constraint is allowed if the current values are not null and are unique. --Column size may be decreased if existing data can be stored with the new column width. --Adding a unique constraint is possible if the current data values are unique. --Adding a check constraint is possible if the current data values comply with the new constraint. --Adding a default value is possible if there is no data in the column. Modifications not allowed include:
--Changing a column's name. --Changing a constraint's name. The format for the ALTER TABLE command to add a new column is given below ADD columnname datatpe; To modify a column, you use the ALTER TABLE command with the modify clause. Column modification includes changes to columns data type, size, default value and NOT NULL column constraint. The format is given below: MODIFY ( <column_name> <datatype> [DEFAULT <expression> ] [NOT NULL] {, <column_name> <datatype> [DEFAULT <expression> ] [NOT NULL]} ); You can increase the width or precision of a column. You can decrease width of columns or change data type of a column only if the column contains no data. A change in the default value affects only the subsequent changes. You can add a NOT NULL constraint only if the column contains no NULL values. Example 3: Add a new column to the friend table SQL> ALTER TABLE friend 2 ADD ( bday date); Example 4: Increase the size of the name field of the friend table to 5o characters. SQL> ALTER TABLE friend 2 MODIFY ( name VARCHAR2(50) ); The format for the ALTER TABLE command to add a new constraint is given below ADD [CONSTRAINT <constraint_name> ] <constraint_type> (<column_list>); where column_list is replaced by the list f the columns that the constraints applies to. Any constraint except for NOT NULL CONSTRAINT can be added using this command. NOT NULL constraint is added using the MODIFY clause of the ALTER TABLE command. Example 5: Add a UNIQUE constraint on the combination of the city and name attributes of the friend table of example 1. SQL > ALTER TABLE friend 2 ADD CONSTRAINT friend_name_city_uk UNIQUE(city,name); To drop a column of a given table the ALTER TABLE command is used as given below: DROP COLUMN column_name; To drop a constraint of a given table the ALTER TABLE command is used as given below:
DROP CONSTRAINT <constraint_name> [CASCADE] ; constraint_name is the name given in the CREATE TABLE command. If you do not remember the <constraint_name>, you can check the data dictionary views called USER_CONSTRAINTS and USER_CONS_COLUMNS. CASCADE keyword causes all dependent constraints to be dropped as well. If there are any other constraints that depend on the constraint that you are trying to drop, DBMS engine does not let you drop the constraint. For example you cannot drop a primary key constraint if there are any foreign key constraints referring to it, unless you use the keyword CASCADE. The primary key constraint and unique constraints can also be dropped using the following drop constraint clause: DROP PRIMARY KEY UNIQUE(<column_list>) CONSTRAINT constraintname [CASCADE] ; Example 6: a) SQL > ALTER TABLE friend 2 DROP PRIMARY KEY CASCADE; b) Drop the constraint you added in example 3. SQL > ALTER TABLE friend 2 DROP CONSTRAINT friend_name_city_uk; You can also enable or disable a constraint without dropping or recreating them. The format is: DISABLE ENABLE CONSTRAINT <constraint_name> [CASCADE]; A constraint is NOT enabled if there are any values in the table that violate it. If you need to add a new column to a table you can use the ALTER TABLE command with the ADD clause as follows ADD (<column_name> <data_type> [DEAFULT <expression>][<column_constraint>] {,<column_name> <data_type> [DEAFULT <expression>] [ <column_constraint>] }); You can add as many columns as you like in one ALTER TABLE statement. In SQL, if you want to delete a table, you DROP it. This is true for all schema objects. Anything created by the CREATE command is deleted by the DROP command. The format of the DROP table command is given below: DROP TABLE <table_name> [CASCADE CONSTRAINTS];
This will cause the table to be dropped. The CASCADE CONSTRAINTS clause is important if the table, you are trying to drop, is referenced by other tables. If you do NOT supply this clause in the DROP TABLE statement and if the table is referenced by other tables, DBMS engine will NOT drop the table. Example 7 : Drop the friend table. SQL > DROP TABLE friend; You can rename a table provided you are the owner of the table. The general syntax is: RENAME oldtablename TO newtablename; Example 8: Change the name of the friend table to myfriends. RENAME friend to myfriends; Truncating a table is removing all records/rows from the table. The structure of the table, however, stays intact. You must be the owner of the table with the DELETE TABLE privilege to truncate a table. The SQL language has a DELETE statement that can be used to remove one or more (or all) rows from a table, and it is reversible as long as it is not committed. The TRUNCATE statement, on the other hand, is not reversible. The syntax is: TRUNCATE TABLE tablename; Exercise Movies(movieid, title, director_name, rating, producing_studio, format) Rented(customerid, movieid) Customer(customerid, name, address, age, balance) These tables have obvious meanings. Movies is the set of movies owned by the video store. Each tuple contains the title of the movie, the name of the director, the rating (e.g., "PG" or "PG-13"), the studio that produced the movie (e.g., "Miramax"), and the format of the movie (e.g., "Video Cassette" or "DVD"). The attribute "movieid" is meant to be the key (presumably assigned by the store). Notice that a given movie that is available in many formats will have different movieids, one for each format. An alternate key for this relation are the two attributes (title, format). In other words, the title and format functionally determine all the other attributes in Movies, such as the movieid, director's name, rating, and studio. Do not worry about the fact that "year" is not a part of the key or the relation. Customer is a table that identifies the customers of the store, their name, dob, address (e.g., "123 Main Street, Blacksburg"), and balance (e.g., "$30" or "-$15"). Rented is a history of who has rented what in the past