Faculty of Engineering. Computer Engineering Dept. Database Lab (ECOM 4113). Lab 6. Data Definition Language. (DDL). Eng
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Database Lab (ECOM 4113)
Lab 6
Data Definition Language (DDL)
Eng. Mohammed Alokshiya
November 11, 2014
Database Keys A key is a logical way to access a record in a table. There are many types of key in Relational Databases like Oracle: Candidate Key A candidate key is any field, or combination of fields, that uniquely identifies a record. The field/s of the candidate key must contain unique values, and cannot contain a null value. Primary Key (PK) A primary key is the candidate key that has been chosen to identify unique records in a particular table. Foreign Key (FK) A relationship between two tables is created by creating a common field to the two tables. The common field must be a primary key to the one table.
Database Schemas A database is a collection of logical structures of data, or schema objects. A schema is owned by a database user and has the same name as that user. Each user owns a single schema. Schema objects can be created and manipulated with SQL and include the following types of objects: Tables – Views – Synonyms – Functions – Procedures – Sequences – Packages – Indexes – etc.
Schema Creating To create a new schema in default XE database, we have to create a new user and Oracle creates a schema for that user with the same name.
2
To create a new user, connect to XE database by SYSTEM user (or any user with sufficient privileges), and issue the following command:
CREATE USER CREATE USER USER_NAME IDENTIFIED BY USER_PASSWORD DEFAULT TABLESPACE USERS QUOTA 10M ON USERS;
In general, the syntax of CREATE USER statement is:
3
Granted Privileges: If you try to connect to database with the new user, you will get a message “ORA-01045: user USER_NAME lacks CREATE SESSION privilige; logon denied”
The reason for that error is: we are trying to connect to our database using a user that do not have any privileges. So, before you leave SYSTEM connection, you have to grant some needed privileges for our new user.
Grant Privileges and Roles GRANT CREATE SESSION, RESOURCE, CREATE VIEW, CREATE SYNONYM, CREATE MATERIALIZED VIEW, ALTER SESSION TO USER_NAME;
Create session: to be able to connect to XE database by the new user. Connect: CONNECT is a pre-defined ROLE in Oracle. A role is a set of privileges that can be granted to users or to other roles. To know which privileges are granted to CONNECT role, then execute the following statement:
4
Display Privileges Granted to a Role SELECT PRIVILEGE FROM DBA_SYS_PRIVS WHERE GRANTEE = 'RESOURCE';
Alter session: to set or modify any of the conditions or parameters that affect your connection to the database.
Table Creating CREATE TABLE Syntax CREATE TABLE TABLE_NAME ( COL_1 DATATYPE [COL. DEFAULT] [INLINE CONSTRAINTS], COL_1 DATATYPE [COL. DEFAULT] [INLINE CONSTRAINTS], .... [OUT OF LINE CONSTRAINTS] );
5
Data Types CHARACTER TYPES Data Type CHAR [(n[BYTE|CHAR])]
NCHAR[(n)]
VARCHAR2(n [byte|char])
NVARCHAR2(n)
Description Notes A set of characters exactly n characters in length, padded with spaces. To specify a value to If you attempt to store a string that is too character data types, long, an error will be generated. it is placed between single quotation A fixed length Unicode character string marks ('), and it is a having maximum length n characters. case sensitive, e.g., Default and minimum n is 1 character. 'Hello'. A Variable length character string having maximum length n bytes or characters. Use concatenation You must specify size for VARCHAR2. operator (||) to Minimum size is 1 byte or 1 character. concatenate two A Variable length Unicode character string strings, e.g. 'abc' || having maximum length n characters. 'def' results 'abcdef'. You must specify size for NVARCHAR2.
NUMERIC TYPES Data Type Description Number [(p[, s])] User-specified precision, scale. The precision is the number of digits to both sides of the decimal point. The positive scale is the count of decimal digits in the fractional part, to the right of the decimal point. If the scale of a value to be stored is greater than the declared scale of the column, the system will round the value to the specified number of fractional digits. When the scale is positive and the number of digits to the left of the decimal point exceeds (p-s), an error is raised. Number(p) = Number(p,0) s=0.
6
Range
The precision p can range from 1 to 38. The scale s can range from -84 to 127. A NUMBER value requires from 1 to 22 bytes.
Float [(p)]
BINARY_FLOAT
Binary_Double
A subtype of the NUMBER data type having precision p. A FLOAT value is represented internally as NUMBER. The precision p can range from 1 to 126 binary digits. To convert from binary to decimal precision, multiply p by 0.30103. BINARY_FLOAT is a 32-bit, single-precision floating-point number data type. BINARY_DOUBLE is a 64-bit, double-precision floating-point number data type.
A FLOAT value requires from 1 to 22 bytes.
15 decimal digit. Each BINARY_FLOAT value requires 4 bytes. Each BINARY_DOUBLE value requires 8 bytes.
BINARY DATA TYPES Data Type RAW(n) LONG RAW
Description Raw binary data of max length n bytes. You must specify size for a RAW value. Raw binary data of variable length up to 2 gigabytes.
DATE/TIME DATA TYPES Data Type Date
Description
Notes
Date and Time.
Example
To specify a value to Date types, you can: Its components are YEAR, Place the value between MONTH, DAY, HOUR, single quotation marks MINUTE and SECOND. in DD-MON-YY format. '31-MAY-02' The default format is: '31-MAY-2002' DD-MON-YY. SYSDATE: special value that is current system date.
To specify a value for Timestamps DataType, you can:
7
timestamp [(p)]
Includes the DATE and TIME fields. The Default format is: DD-MON-YY HH.MM.SS.p AM/PM
Timestamp Timestamp with time [(p)] with zone displacement value. time zone The Default format is: DD-MON-YY HH.MM.SS.p AM/PM +/- HH:MM/time zone
Place the value in (') marks in DD-MON-YY HH:MM:SS.p [AM/PM] [+/-HH:MM/time zone] Format. Hour from (1-12). +/-HH:MM/time zone for timestamp with time zone data type. AM/PM required for timestamp with time zone data type. If you don’t specify AM/PM for timestamp and timestamp with local time zone data types the default is AM.
'31-MAY-02 10:30:56' '31-MAY-02 10:30:56 PM' Timestamp '200205-02 10:30:56.25' ’31-MAY-03 10:30:56 AM +08:00’ '04-Jul-05 4:5:6 PM ASIA/JERUSALEM' Timestamp '200205-02 15:30:56.36 -07:00' Timestamp ‘200205-02 15:30:56.36 ASIA/JERUSALEM'
Timestamp Timestamp with the local [(p)] with time zone. local time zone The Default format is: DD-MON-YY HH.MM.SS.p AM/PM
Use Timestamp literal and YYYY-MM-DD HH:MM:SS.p [+/- HH:MM/time zone] format Hour from (0-23) ’31-MAY-14 +/- HH:MM/time zone 10:30:56’ for timestamp with time ’31-MAY-14 zone data type. 10:30:56 PM’ P: is an optional fractional seconds precision, it can be specified timestamp, and interval types. P can be from 0 to 9. The default p is 6.
8
Timestamp ’201305-06 10:30:56’
INTERVAL YEAR [(p)] TO MONTH
If the number of digits of a value to be stored is greater than the declared P, the system will round the value to the specified P.
Stores a period of time in years and months.
To specify a value for this data type:
P: is the number of digits in the YEAR field.
Interval ‘YY-MM’ year to month.
Interval ‘1-2’ year to month.
P can from 0 to 9. The default p is 2. INTERVAL DAY [(D)] TO SECOND [(p)]
Stores a period of time in days, hours, minutes, and seconds. D: is the maximum number of digits in the DAY field.
To specify a value for this data type: Interval ‘D HH:MM:SS.p’ Day to second
D range: 0 to 9. The default D is 2. P: is the number of digits in the fractional part of the SECOND field. P can from 0 to 9. The default p is 2.
9
Interval ‘3 12:4:5’ Day to Second
Default Values A column can be assigned a default value. When a new row is created and no values are specified for some of the columns, those columns will be filled with their respective default values. If no default value is declared explicitly, the default value is the null value. In a table definition, default values are listed after the column data type.
SQL CREATE TABLE EMPLOYEE ( .. SALARY NUMBER (6,2) DEFAULT 2000, .. );
Constraints SQL allows you to define constraints on columns and tables. Constraints give you as much control over the data in your tables as you wish. If a user attempts to store data in a column that would violate a constraint, an error is raised.
Constraints Types: NOT NULL: prohibits a database value from being null. Unique: prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null. Primary key: combines a NOT NULL constraint and a unique constraint in a single declaration. It prohibits multiple rows from having the same value in the same column or combination of columns and prohibits values from being null. Check: requires a value in the database to comply with a specified condition. Foreign key: requires values in one table to match values in another table.
You can define constraints syntactically in two ways: As a part of the definition of an individual column or attribute. This is called inline specification.
10
As a part of the table definition. This is called out-of-line specification.
Notes: NOT NULL constraints must be declared inline. All other constraints can be declared either inline or out of line. The constraint on a combination of columns must be declared out of line. You cannot designate the same column or combination of columns as both a primary key and a unique key.
In Line Constraint [CONSTRAINT CONST_NAME] CONST_TYPE [CONST_SPECIFICATIONS]
Out of Line Constraint [CONSTRAINT CONST_NAME] CONST_TYPE (COLUMN[S]) [CONST_SPECIFICATIONS]
Constraint const_name specifies a name for the constraint. If you omit this identifier, then Oracle Database generates a name. Constraint name clarifies error messages and allows you to refer to the constraint when you need to change it. Not Null Constraint It must be declared in line.
Not Null Constraint [CONSTRAINT CONST_NAME] NOT NULL
Unique Constraint
UNIQUE Constraint [In Line] [CONSTRAINT CONST_NAME] UNIQUE
UNIQUE Constraint [Out of Line] [CONSTRAINT CONST_NAME] UNIQUE (COLUMN[S])
11
Primary Key Constraint
PRIMARY KEY Constraint [In Line] [CONSTRAINT CONST_NAME] PRIMARY KEY
PRIMARY KEY Constraint [Out of Line] [CONSTRAINT CONST_NAME] PRIMARY KEY (COLUMN[S])
Check Constraint
CHECK Constraint [In and Out of Line] [CONSTRAINT CONST_NAME] CHECK (Boolean Expression)
Foreign Key Constraint A foreign key constraint specifies that the values in a column (or a group of columns) must match the values appearing in some row of another table. This maintains the referential integrity between two related tables. When Deleting or updating a referenced row, Oracle allows you to handle that as well. There are two options: CASCADE if you want Oracle to remove/update dependent foreign key values. SET NULL if you want Oracle to convert dependent foreign key values to NULL.
Foreign Key Constraint [In Line] [CONSTRAINT CONST_NAME] REFERENCES REFERENCED_TABLE (REFERENCED_COL) [ON {DELETE | UPDATE} SET NULL | CASCADE]
Foreign Key Constraint [Out of Line] [CONSTRAINT CONST_NAME] FOREIGN KEY (COLUMN_NAME) REFERENCES REFERENCED_TABLE (REFERENCED_COL) [ON {DELETE | UPDATE} SET NULL | CASCADE]
12
If you omit ON DELETE or ON UPDATE clause, then Oracle does not allow you to delete or update referenced key values in the parent table that have dependent rows in the child table. Note: Foreign key column data type must be as same as referenced column.
Modifying Tables Alter Table command allow you to alter the definition, or structure, of the table, such you can:
Add columns. Remove columns. Add constraints. Remove constraints. Change default values. Change column data types. Rename columns. Rename tables.
Add Column ALTER TABLE TABLE_NAME ADD COLUMN_NAME DATATYPE [COL. DEFAULT] [INLINE CONSTRAINTS]
Modify Column Data Type ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME NEW_DATATYPE
Note: You can change the data type of any column if all rows of the column contain nulls.
Specifying Column Default Value ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME DEFAULT DEFAULT_VALUE;
13
To discontinue previously specified default values, so that they are no longer automatically inserted into newly added rows, replace the values with NULL.
Remove Default Value ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME DEFAULT NULL;
Rename Column ALTER TABLE TABLE_NAME RENAME COLUMN COLUMN_NAME TO NEW_OLUMN_NAME;
Remove Column ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME [CASCADE];
CASCADE: if you want to drop everything that depends on the column.
Add Out of Line Constraint ALTER TABLE TABLE_NAME ADD OUT_OF_LINE_CONSTRAINT;
To add a not-null constraint, which cannot be written as out of line constraint, use this syntax:
Add Not Null Constraint ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME NOT NULL;
Rename Constraint ALTER TABLE TABLE_NAME RENAME CONSTRAINT CONSTRAINT_NAME TO NEW_CONSTRAINT_NAME;
Remove Constraint ALTER TABLE TABLE_NAME DROP CONSTRAINT CONSTRAINT_NAME [CASCADE];
14
Remove Not Null Constraint ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME NULL;
Rename Table ALTER TABLE TABLE_NAME RENAME TO NEW_NAME;
Remove Table DROP TABLE TABLE_NAME [CASCADE];
15
Example:
Solution: 1. Create First Table (Least dependent table):
Create Table EMPLOYEE CREATE TABLE EMPLOYEE ( Fname VARCHAR2 (20) NOT NULL, Minit VARCHAR2(1), Lname VARCHAR2 (20) NOT NULL, Ssn NUMBER(9) PRIMARY KEY, Bdate DATE, Address VARCHAR2(100), Sex NUMBER (1) CHECK (Sex BETWEEN 0 AND 1), Salary NUMBER(6) DEFAULT 2000 NOT NULL, Super_ssn NUMBER(9) REFERENCES EMPLOYEE(Ssn), Dno NUMBER(6) );
16
Note: Dno is a foreign key references the Department table but we haven’t created DEPARTMENT table yet, so we can’t add foreign constraint here, and we need to alter EMPLOYEE table to add the foreign constraint after DEPARTMENT creating. To view the tables in the schema, R-Click on Tables >> Refresh.
2. Second Table: Department
Create Table DEPARTMENT CREATE TABLE DEPARTMENT ( Dname VARCHAR2(20) NOT NULL UNIQUE, Dno NUMBER(6) PRIMARY KEY, Mgr_ssn NUMBER(9) REFERENCES EMPLOYEE(Ssn), Mgr_start_date DATE );
Now you can alter the first table (Employee) to add foreign key constraint
Alter Table EMPLOYEE ALTER TABLE EMPLOYEE ADD ( CONSTRAINT FK FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dno) );
17
3. Create other tables
Create Other Tables CREATE TABLE DEPT_LOCATIONS ( Dnumber NUMBER(6) REFERENCES DEPARTMENT(Dnumber), Dlocation VARCHAR2 (20), CONSTRAINT PK PRIMARY KEY (Dnumber, Dlocation) ); CREATE TABLE PROJECT ( Pname VARCHAR2(20) NOT NULL UNIQUE, Pnumber NUMBER(6) PRIMARY KEY, Plocation VARCHAR2(20), Dnum NUMBER(6) REFERENCES DEPARTMENT(Dnumber) ); CREATE TABLE WORKS_ON ( Essn NUMBER(9) REFERENCES EMPLOYEE(Ssn), Pno NUMBER(6) REFERENCES DEPARTMENT(Dnumber), Hours NUMBER(3), PRIMARY KEY (Essn, Pno) ); CREATE TABLE DEPENDENT ( Essn NUMBER(9) REFERENCES EMPLOYEE(Ssn), Dependent_name VARCHAR2(20) NOT NULL, Sex NUMBER (1) CHECK (Sex BETWEEN 0 AND 1), Bdate DATE, Relationship NUMBER (2), PRIMARY KEY (Essn, Dependent_name) );
Note that Oracle DMBS generates names for constraints If you omit this the name. To display the auto-generated names for a table constraints, use the following command:
Display Table Constraints SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAME, SEARCH_CONDITION FROM USER_CONSTRAINTS;
18
Example: Display constrains for EMPLOYEE table columns
19
Exercise: Given the following relations, create a new user in your Oracle database; grant sufficient privileges then create all the tables with appropriate constraints.
20