In the name of Allah
Islamic University of Gaza
Faculty of Engineering
Computer Engineering Department
ECOM 4113
DataBase Lab
Lab # 2
Data Definition Language
(DDL)
Eng. Haneen El-masry
2013
DataBase Lab
Eng. Haneen 2
Objective
To be familiar with SQL Language especially with Data Definition Language (DDL).
RELATIONAL DATABASE (RDB)
Relational DataBase means data stored in relations. Relation is essentially a
mathematical term for table.
Each table is a named collection of rows (tuples). Each row of a given table has the same
set of named Columns (attributes), and each column is of a specific data type.
DATA BASE KEYS
A key is a logical way to access a record in a table. There are many types of key in RDB:
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.
SQL LANGUAGE
SQL is presently expanded as Structured Query Language. Originally, SQL was called
SEQUEL. SQL is now the standard language for commercial relational DBMSs.
SQL STATEMENTS
SQL is a comprehensive database language. It has insensitive statements for data
definitions, queries, and updates. So SQL can be divided into two parts:
DataBase Lab
Eng. Haneen 3
Data Definition Language (DDL).
Data Manipulation Language (DML).
The query and update commands form the DML part of SQL are:
INSERT INTO: inserts new data into a database.
SELECT: extracts data from a database.
UPDATE: updates data in a database.
DELETE: deletes data from a database.
The DDL part of SQL permits database tables to be created or deleted. It also define
keys, specify links between tables, and impose constraints between tables. The most
important DDL statements in SQL are:
CREATE DATABASE: creates a new database.
ALTER DATABASE: modifies a database.
CREATE TABLE: creates a new table.
ALTER TABLE: modifies a table.
DROP TABLE: deletes a table.
In this Lab, we will concentrate on DDL.
DataBase Creating
Method 1:
1- Right click on Databases >> New Database.
DataBase Lab
Eng. Haneen 4
2- Enter Database name and its owner.
3- Open SQL query tool for the database.
Method 2:
1- Open SQL query for postgres database.
2- Use the following SQL statement:
CREATE DATABASE DBNAME;
DataBase Lab
Eng. Haneen 5
3- Execute the statement.
4- Command SQL Statement: Select >> press Ctrl+K.
5- Connect to SQL query tool for the new DataBase, to execute SQL statements on
it.
DataBase Lab
Eng. Haneen 6
SCHEMA CREATING
We can Create a schema to create tables inside it, instead of creating them in public
shema.
We can explicity attach the schema name to the table name , separated by a period(.).
DATABASE TABLES
TABLE CREATING
DATA TYPES
NUMERIC TYPES
Name Description Range
smallint Small-range integer -32768 to +32767
Integer Int
Typical choice for integer -2147483648 to +2147483647
bigint Large-range integer -9223372036854775808 to +9223372036854775807
Numeric(p,s) Decimal(p,s)
user-specified precision, scale.
The scale is the count of decimal digits in
up to 131072 digits before the decimal point; up to
Create Table tablename (
Col.1 DataType [Col. constraints],
Col.2 DataType [Col. constraints],
....
[Table Constraints] );
Create SCHEMA Name Authorization Owner;
DataBase Lab
Eng. Haneen 7
the fractional part, to the right of the decimal point.
The precision is the number of digits to both sides of the decimal point.
Perform calculations exactly.
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.
If the number of digits to the left of the decimal point exceeds (p-s), an error is raised.
16383 digits after the decimal point.
real variable-precision, inexact 6 decimal digits precision
Double precision variable-precision, inexact 15 decimal digits precision
Float(p) P: is the minimum acceptable precision in binary digits.
float(1) to float(24) : real type.
float(25) to float(53): double precision.
Values of p outside the allowed range draw an error.
float with no precision specified is taken to mean double precision.
Serial auto incrementing integer 1 to 2147483647
bigserial auto incrementing integer 1 to 9223372036854775807
BOOLEAN TYPE
Name Description
Boolean The Boolean type can store three possible values, true, false, and NULL, when the value is unknown.
CHARACTER TYPES
Definition Description Notes
char A single character. To specify a value to character data types, it is placed between single quotation marks (‘), and it is a case
char(n) A set of characters exactly n characters in length, padded with spaces. If you attempt to store a string that is too long, an error will be generated.
DataBase Lab
Eng. Haneen 8
varchar(n) A set of characters up to n characters in length, with no padding.
sensitive, e.g., ‘Hello’.
Use concatenation operator (||) to concatenate two strings, e.g. ‘abc’ || ‘def’ results ‘abcdef’.
text Effectively, an unlimited length character string. This is a PostgreSQL extension to the SQL standard.
MONETARY TYPES
Name Description Range Notes
Money Stores a currency amount.
-92233720368547758.08 to +92233720368547758.07
To specify a value to Money Data Type, it can be an integer, floating-point or a typical currency formatting, such as ’$1,000.00’.
BIT STRING TYPES
Name Description Notes
Bit(n) Fixed length string of 1’s and 0’s. To specify a value to Bit String data Types, strings are placed between single quotes but preceded by a B, e.g., B’1001’
Bit varying(n) Variable Length string of 1’s and 0’s., such n is the maximum number of bits.
DATE/TIME DATA TYPES
Name Description Notes Example
Date Date Only.
Date type has ten positions, and its components are YEAR, MONTH, and DAY in the form:
YYYY-MM-DD.
To specify a value to Date/Time types, SQL requires the following syntax: type [ (p) ] ’value’
Date ’2013-09-24’
DataBase Lab
Eng. Haneen 9
Time [(p)]
Time only.
TIME type has eight positions, with the components HOUR, MINUTE, and SECOND in the form:
HH:MM:SS.
P: is an optional fractional seconds precision, it can be specified for time, timestamp, and interval types.
P can be from 0 to 6.
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.
Time ’05:52:53’
Time ‘05:08:10 PM’
Time(4) ’05:52:53.1593’
time[(p)] with time zone.
It includes an additional six positions for specifying the displacement from the standard universal time zone, which is in the range:
+13:00 to –12:59 in units of HOURS:MINUTES.
Time (5) with time zone ’06:18:6.10235+02’
timestamp [(p)]
includes the DATE and TIME fields, with a blank space between two fields.
Timestamp ’2013-05-6 10:30:56’
Timestamp [(p)] with time zone
Timestamp with time zone. Timestamp with time zone ’2013-05-6 10:30:56+8:00’
timestamptz a PostgreSQL extension as an abbreviation for timestamp with time zone.
Timestamptz ’2013-05-6 10:30:56+8:00’
interval Is a relative value that can be used to increment or decrement an absolute value of a date, time, or timestamp.
The format used to specify a value to interval:
Interval‘P[years-months-days] [T hours: minutes: seconds ]’.
Interval ‘P 1-2’ 1 year, 2 months
Interval ’p 3 T 4:05:06’ 3 years, 4 hours, 5 minutes, 6 seconds.
DataBase Lab
Eng. Haneen 10
Special Values for Date/Time Data Types
Input String Valid Types Description
now date, time, timestamp current transaction's start time
today date, timestamp midnight today
tomorrow date, timestamp midnight tomorrow
yesterday date, timestamp midnight yesterday
ARRAY TYPE
- One Dimensional Array Declaration
- Two Dimensional Array Declaration
- Specifying A Value To One Dimensional Array
- Specifying A Value To Two Dimensional Array
- Accessing Any Element In The Array
ENUMERATED TYPES
Enumerated (enum) types are data types that comprise a static, ordered set of values.
Enum types are created using the CREATE TYPE command:
Elements Data type [] e.g., integer []
Elements Data type [] [] e.g. integer [] []
'{V1, V2, ….}'
'{{"R11", "R12"}, {"R21", "R22"}}'
Note: You must put double quotes around any element value.
Array name [Element index]
CREATE TYPE name AS ENUM (’V1’, ’V2’, ’V3’…..);
DataBase Lab
Eng. Haneen 11
e.g.,
CREATE TYPE mood AS ENUM (’sad’, ’ok’, ’happy’);
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.
CHECK CONSTRAINT
A check allows you to specify that the value in a certain column must satisfy a Boolean
expression, it can be as a column or a table constraint.
- As a column Constraint
- As a table constraint
You can give the constraint a separate name. This clarifies error messages and allows
you to refer to the constraint when you need to change it.
- Check As a named constraint
Create table product( price numeric CHECK (price > 0) , ….);
create table Product( price numeric, ….. Check (price >0));
create table Product( price numeric, ….. Constraint validPrice Check (price >0));
DataBase Lab
Eng. Haneen 12
NOT-NULL CONSTRAINT
A not-null constraint simply specifies that a column must not assume the null value. A
not-null constraint is always written as a column constraint and it doesn’t have a name.
UNIQUE CONSTRAINT
Unique constraints ensure that the data contained in a column or a group of columns is
unique with respect to all the rows in the table. The syntax is:
- As a Column Constraint
- As a table constraint
If a unique constraint refers to a group of columns, it must be as a table constraint and
the columns are listed separated by commas:
Create table Product( product_no integer NOT NULL, ….);
CREATE TABLE products ( product_no integer UNIQUE, …… );
CREATE TABLE products ( product_no integer, ….. UNIQUE (product_no) );
CREATE TABLE example ( a integer, b integer, c integer, UNIQUE (a, c) );
DataBase Lab
Eng. Haneen 13
- As a named Constraint
PRIMARY KEY
Technically, a primary key constraint is simply a combination of a unique constraint and
a not-null constraint.
- As a column constraint
- As a table constraint
Primary keys can also constrain more than one column; the syntax is similar to unique
constraints:
Create table products( product_no integer, ….. Constraint uniqcons UNIQUE (product_no) );
CREATE TABLE products ( product_no integer PRIMARY KEY, …. );
Create table products( product_no integer, ….. PRIMARY KEY (product_no) );
CREATE TABLE example ( a integer, b integer, c integer, PRIMARY KEY (a, c) );
DataBase Lab
Eng. Haneen 14
- As a named constraint
FOREIGN KEYS
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.
- As a column constraint
- As a table constraint
A foreign key can also constrain and reference a group of columns. As usual, it then
needs to be written in table constraint form.
Create table products( product_no integer, ….. Constraint PK PRIMARY KEY (product_no) );
CREATE TABLE orders ( product_no integer REFERENCES products (product_no), ….. );
CREATE TABLE orders ( product_no integer, ….. Forein Key (product_no) REFERENCES products (product_no) );
CREATE TABLE t1 ( a integer PRIMARY KEY, b integer, c integer, FOREIGN KEY (b, c) REFERENCES other_table (c1, c2) );
DataBase Lab
Eng. Haneen 15
- As a named constraint
When Deleting or updating a referenced row, SQL allows you to handle that as well.
There are many options:
Disallow deleting or updating a referenced row (RESTRICT or NO ACTION).
Delete or update the referencing as well (Cascade).
Do the Deleting or updating and set the referencing value to its default(SET
DEFAULT).
Do the Deleting or updating and set the referencing value to Null (SET NULL).
Note:
RESTRICT prevents deletion of a referenced row. CASCADE, if any referencing rows still
exist when the constraint is checked, an error is raised; this is the default behavior if you
do not specify anything.
Example:
CREATE TABLE orders ( product_no integer, ….. Constraint FK Forein Key (product_no) REFERENCES products (product_no) );
CREATE TABLE orders ( product_no integer, ….. Forein Key (product_no) REFERENCES products (product_no) on Delete RESTRICT | NO ACTION | SET NULL |SET DEFAULT | CASCADE on Update RESTRICT| NO ACTION | SET NULL |SET DEFAULT | CASCADE );
DataBase Lab
Eng. Haneen 16
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, e.g.,
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.
Adding a Column
To add a column, use a command like:
Removing a Column
To remove a column, use a command like:
ALTER TABLE TName ADD COLUMN ColName DataType [Constrints];
ALTER TABLE TName DROP COLUMN ColName;
CREATE TABLE Products ( price numeric DEFAULT 9.99 );
DataBase Lab
Eng. Haneen 17
You can authorize dropping everything that depends on the column by adding
CASCADE:
Adding a Constraint
To add a constraint, the table constraint syntax is used. For example:
To add a not-null constraint, which cannot be written as a table constraint, use this
syntax:
Removing a Constraint
To remove a constraint you need to know its name, then use this syntax:
Also you can use CASCADE.
To drop a not null constraint, use:
Changing a Column’s Default Value
To set a new default for a column, use a command like:
ALTER TABLE TName DROP COLUMN ColName CASCADE;
ALTER TABLE products ADD CHECK (ColName <> ”);
ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no);
ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES
product_groups;
ALTER TABLE TName ALTER COLUMN ColName SET NOT NULL;
ALTER TABLE TName DROP CONSTRAINT name;
ALTER TABLE TName DROP CONSTRAINT name CASCADE;
ALTER TABLE TName ALTER COLUMN colName DROP NOT NULL;
ALTER TABLE TName ALTER COLUMN colName SET DEFAULT Value;
DataBase Lab
Eng. Haneen 18
To remove any default value, use:
Changing a Column’s Data Type
To convert a column to a different data type, use a command like:
Renaming a Column
To rename a column:
Renaming a Table
To rename a table:
Deleting Table
ALTER TABLE TName ALTER COLUMN colName DROP DEFAULT;
ALTER TABLE TName ALTER COLUMN colName TYPE newType;
ALTER TABLE TName RENAME COLUMN oldName TO NewName;
ALTER TABLE oldName RENAME TO newName;
Drop Table TName;
Drop Table TName CASCADE;
DataBase Lab
Eng. Haneen 19
Example
Create a Company database owned by your name user then create its tables:
1- Department with a unique name, unique number (PK), and managerSSn.
2- Employee with a unique SSN (PK), FName, LNmae, Salary, Bdate, Sex, Address
and DepNo.
3- Project with a unique name, unique number (PK), location and DeptNo.
Notes:
- Choose a suitable Data Type for each Attribute, and create enumerated type if
you need it.
- Add all suitable Constraints when creating the table except Froeign Key
Constraints.
4- Alter Tables and Add Foreign Key constraints.
Solution
1- Create Company DataBase.
DataBase Lab
Eng. Haneen 20
2- Create Department, Employee and Project Tables.
3- Execute the statements.
DataBase Lab
Eng. Haneen 21
4- Comment the Statements.
5- Add a foreign Key Constraints.
6- Execute the Statements.
Note: In Employee Table the foreign key has a same name of Primary key of
Departmant Table, so I don’t need to specify the primary key attribute.
DataBase Lab
Eng. Haneen 22
Exercises
Create a University database owned by your name user then create its tables:
1- Faculty with a unique number (PK), Fphone, Foffice.
2- Department with a unique Department name (PK), Dphone, office, FacultyNo.
3- Teacher with a unique ID (PK), Fname, Lname, Sex, Salary, office, DeptName.
4- Student with a unique ID (PK), Fname, Lname, Sex, BDate, DeptName.
5- Course with a unique number (PK), CourseName, Description, TeacherID.
6- StdCourses with StdID, CourseID.
Notes:
- Choose a suitable Data Type for each Attribute, and create enumerated type if
you need it.
- Add all suitable Constraints when creating the table except Froeign Key
Constraints.
5- Alter Tables and Add Foreign Key constraints.
6- Alter StdCourses Table to make both StdID and CourseID to be its a primary key.