<<

The Islamic University of Gaza

Faculty of Engineering

Department of Computer Engineering

ECOM 4113: Lab

Lab # 2

Data Definition Language (DDL)

Eng. Alaa O Shama

October, 2015

Objective

 To be familiar with SQL Language especially with Definition Language(DDL).

Relational Database (RDB)

Relational Database means data stored in relations. is esse- ntially a mathematical term for .

Each table is a named collection of rows (). Each of a given table has the same of named Columns (attributes), and each is of a sp- ecific data type.

Database Keys

A key is a logical way to access a record in a table. There are many types of key in RDB:

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 can't contain a value.

(PK)

A primary key is the candidate key that has been chosen to identify unique records in a particular table.

(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.

SQL Language

SQL is presently expanded as Structured . Originally, SQL was called SEQUEL. SQL is now the standard language for commercial relational DBMSs.

SQL Statements

SQL has insensitive statements for data definitions, queries, and updates. SQL commands are grouped into major categories depending on their functionality:

(DDL): These SQL commands are used for creating,modifying, and dropping the structure of database objects. It also defines keys, specify links between tables, and impose constraints between tables. The commands are ALTER, ANALYZE, AUDIT, COMMENT, CREATE ,DROP,FLASHBACK, GRANT, PURGE, RENAME, REVOKE and TRUNCATE.

 Data Manipulation Language (DML): These SQL commands are used for storing, retrieving, modifying, and deleting data. These Data Manipulation Language commands are CALL, DELETE, EXPLAIN,INSERT, LOCK TABLE, MERGE, SELECT and UPDATE.

 Transaction Control Language (TCL): These SQL commands are used for managing changes affecting the data. These commands are , ROLLBACK, and .

In this lab, we will concentrate on DDL.

Schema Creating

To create a new schema in default XE database, we have to create a new user and the Oracle creates a schema for that user with the same name.

To create a new user, you have to follow the next steps: 1- Connect to XE database by SYSTEM user.

2- Expand the connection and -click on other users >> Create User.

3- User tab >> enter user name and password and choose the default

and temporary table spaces.

4- System Privileges tab >> Grant the necessary privileges for the user.

Granted Privileges:

 Create session: to be able to connect to XE database by the new user  Create table/ / procedure/ / sequence/ trigger/ type/: to be able to create tables, views, procedure ,synonyms, sequences, user defined data types and materialized views respectively inside the new schema.  Unlimited tablespace: to permit a user to use an unlimited amount of any tablespace in the database.  Alter session: to set or modify any of the conditions or parameters that affect your connection to the database. 5- Apply

6- You can create a new user by SQL commands.

Create User Create User user_name identified by password

Default tablespace “tablespace”

Temporary tablespace “tablespace”;

Privileges

Grant Privilige To user_name ;

On the worksheet of SYSTEM connection, write the following statements and execute them.

7- After user creation, Connect to XE database by the new user.

8- Now you can issue SQL statements for the new schema.

Table Creating

DATA TYPES   NUMERIC TYPES Name Description Range 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 The precision p can range digits in the fractional part, to the right of 1 to 38. the decimal point.  If the scale of a value to be stored is greater The scale s can range from than the declared scale of the column, the -84 to 127. system will round the value to the specified number of fractional digits. A NUMBER value requires  When the scale is positive and the number from 1 to 22 bytes. of digits to the left of the decimal point exceeds (p-s), an error is raised.  Number(p) = Number(p,0) s=0.  Number: specifies the maximum range and precision for an Oracle number. Integer Number (32) -2 ^31 – (2 ^31)-1 INT

 CHARACTER TYPES

Definition Description Notes char A single character. Char A set of characters exactly n characters in  To specify a value to (n[byte|char]) length, padded with spaces. character data types, If you attempt to store a string that is too it is placed between long, an error will be generated. single quotation NCHAR[(n)] A fixed length Unicode character string marks (‘), and it is a maximum length n characters. case sensitive, e.g., Default and minimum n is 1 character. ‘Hello’.

VARCHAR2(n A Variable length character string having [byte|char]) 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 NVARCHAR2(n) A Variable length Unicode character string strings, e.g. ‘abc’ || having maximum length n characters. ‘def’ results ‘abcdef’. You must specify size for NVARCHAR2.

 DATE/TIME DATA TYPES

Name Description Notes Example

Date Date Only.  To specify a value to Date

types, you can: Its components are YEAR,  Place the value between

MONTH, and DAY. ‘31-MAY-02’ single quotation marks ’31-MAY-2002’ The default format is: in DD-MON-YY/YYYY format. Date ‘2002-05-31’ DD-MON-YY.  Use Date keyword and Date ’02-05-31’ YY/YYYY-MM-DD SYSDATE: special value Format. that is current system date. Includes the DATE and timestamp TIME fields, with a blank  To specify a value for ’31-MAY-02 [(p)] space between two fields. Timestamps DataType, you 10:30:56’

can: ’31-MAY-02 The Default format is:  Place the value in (‘) mark 10:30:56 PM’

DD-MON-YY HH.MM.SS.p In AM/PM DD-MON-YY Timestamp ‘2002- HH:MM:SS.p [AM/PM] 05-02 10:30:56.25’

[+/-HH:MM/time zone] Timestamp Timestamp with time Format. ’31-MAY-03 [(p)] with zone displacement value. . Hour from (1-12). 10:30:56 AM

time zone . +/-HH:MM/time zone +08:00’

The Default format is: for timestamp with time '04-Jul-05 4:5:6 PM DD-MON-YY HH.MM.SS.p zone data type. ASIA/JERUSALEM' AM/PM +/- HH:MM/time . AM/PM required for zone timestamp with time Timestamp ‘2002- zone data type. 05-02 15:30:56.36 -

07:00’ . If you don’t specify AM/PM for timestamp Timestamp ‘2002- and timestamp with 05-02 15:30:56.36 local time zone data ASIA/JERUSALEM' types the default is AM.

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.

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 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 si ngle 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 .  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 in-line specification.  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 .

In Line Specification [Constraint const_name] const_type [const_specifications]

Note: In this specification const_type doesn’t specified for foreign key constraint.

Out Of Line Specification [Constraint const_name] const_type (column[s]) [const_specifications]

Constraint const_name specifies a name for the constraint. If you omit this identifier, then 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.

In Line Specification [Constraint const_name] Not Null

Unique Constraint In Line Specification [Constraint const_name] Unique

Out of Line Specification [Constraint const_name] Unique (Column[s])

Primary Key Constraint

In Line Specification [Constraint const_name] Primary Key

Out of Line Specification [Constraint const_name] Primary Key (Column[s])

Check Constraint

In Line & Out Of Line Specifications [Constraint const_name] ckeck (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 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/ dependent foreign key values.  SET NULL if you want Oracle to convert dependent foreign key values to NULL.

In Line Specification [Constraint const_name] references ReferencedTable (ReferencedCol) [ON Delete set Null | CASCADE] [ON UPDATE set NULL | CASCADE]

Out Of Line Specification [Constraint const_name] foreign key (Column[s]) references ReferencedTable (ReferencedCol[s]) [ON Delete set Null | CASCADE] [ON UPDATE set NULL | CASCADE]

If you omit ON DELETE or ON UPDATE clause, then Oracle does not allow you to 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.

Example:

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 Columns ALTER TABLE TName

ADD(

Col1Name DataType [Default value] [Constraints],

Col2Name DataType [Default value] [Constraints]

… );

Change Column Data Type ALTER TABLE TName

MODIFY ColName newDataType;

Note: You can change the data type of any column if all rows of the column contain nulls.

Specify Column Default Value ALTER TABLE TName

MODIFY ColName DEFAULT DefValue;

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 TName

MODIFY ColName DEFAULT NULL;

Rename Column ALTER TABLE TName

Rename Column oldName to newName;

Remove Column ALTER TABLE TName

Drop Column ColName [CASCADE];

CASCADE: if you want to drop everything that depends on the column.

Add Out Of Line Constraint ALTER TABLE TName

Add OutOfLineConstraint ;

To add a not null constraint, which cannot be written as out of line constraint use this syntax:

Add Not Null Constraint ALTER TABLE TName

Modify ColName Not Null;

Rename Constraint ALTER TABLE TName

RENAME CONSTRAINT OldName TO NewName;

Remove Constraint ALTER TABLE TName

DROP CONSTRAINT name [CASCADE];

Remove Not Null Constraint ALTER TABLE TName

MODIFY ColName NULL;

ReName Table ALTER TABLE TName

RENAME TO NewName;

Remove Table DROP TABLE TName [CASCADE];

Notes:

 SQL Statements are executed sequentially.  To run a statement,put the on the statement and press Ctrl+Enter or click

 To run more than one statement sequentially, them then click on

icon.  You can run all statements in the worksheet, put the cursor on the first statement and press F5. Or click on icon .

Example:

You have the following COMPANY Schema, create it on Oracle.

Solution:

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.

Exercise: 1. Create the following Library schema.

Homework : Create Mail Order Schema.