Lab 5

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Riphah International University

Islamabad

LAB MANUAL
Lab Manual for Introduction to Database Systems

FACULTY OF COMPUTING (WISH)

1
Lab Manual Development Team

Supervision and Coordination

Mam Alia Fatima


Lecturer
Faculty of Computing

Lab Designers

Mehwish Javed
Teaching Fellow

Faculty of Computing

2
Lab 5: Introduction to DDL
1. Activity Time boxing

2. Lab Manual Lecture [Expected time = 30 minutes]

1. Introduction
DDL is short name of Data Definition Language, which deals with database schemas
and descriptions, of how the data should reside in the database.

 CREATE - to create a database and its objects like (table, index, views, function)
 ALTER - alters the structure of the existing database
 DROP - delete objects from the database
 TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
 COMMENT - add comments to the data dictionary
 RENAME - rename an object

2. Activity Time boxing


Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
Lab Quiz 20 min
Lab Lecture 30
Examples 15 min
Walkthrough Tasks 15 min
Practice Tasks 60 min
Tasks Evaluation 10-20 min 160

3
3. Lab Manual Lecture [Expected time = 30 minutes]

4. Objective
 Introduction to Data Definition Language (DDL)
 Create Table
 Update Table
 Drop Table
 Constraints

5. Concept Map

6. Data Types

6.1 String Datatypes


The following are the String Datatypes in MySQL:

Data Type
Maximum Size Explanation
Syntax

Where size is the number of characters to store. Fixed-


Maximum size of
CHAR(size) length strings. Space padded on right to
255 characters.
equal size characters.

Maximum size of Where size is the number of characters to store.


VARCHAR(size)
255 characters. Variable-length string.

Maximum size of
TINYTEXT(size) Where size is the number of characters to store.
255 characters.

4
6.2 Numeric Datatypes
The following are the Numeric Datatypes in MySQL:

Data Type
Maximum Size Explanation
Syntax

Very small integer value.


TINYINT(m) Signed values range from -128 to 127.
Unsigned values range from 0 to 255.

SMALLINT(m) & Small & Medium integer value.


MEDIUMINT(m)

Standard integer value.


Signed values range from -2147483648 to
INT(m)
2147483647. Unsigned values range from 0 to
4294967295.

Unpacked fixed point number. Where m is the total digits


DECIMAL(m,d) m defaults to 10, if not specified. and d is the number of digits
d defaults to 0, if not specified. after the decimal.

Where m is the total digits


and d is the number of digits
Unpacked fixed-point number. after the decimal.
FIXED(m,d) m defaults to 10, if not specified. (Introduced in MySQL 4.1)
d defaults to 0, if not specified.
This is a synonym for the
DECIMAL datatype.

Where m is the total digits


FLOAT(m,d) Single precision floating point number. and d is the number of digits
after the decimal.

Where m is the total digits


DOUBLE(m,d) Double precision floating point number. and d is the number of digits
after the decimal.

Where m is the total digits


and d is the number of digits
after the decimal.
REAL(m,d) Double precision floating point number.
This is a synonym for the
DOUBLE datatype.

5
Data Type
Maximum Size Explanation
Syntax

FLOAT(p) Floating point number. Where p is the precision.

Treated as a boolean data


type where a value of 0 is
BOOL Synonym for TINYINT(1) considered to be FALSE and
any other value is considered
to be TRUE.

Treated as a boolean data


type where a value of 0 is
BOOLEAN Synonym for TINYINT(1) considered to be FALSE and
any other value is considered
to be TRUE.

6.3 Date/Time Datatypes


The following are the Date/Time Datatypes in MySQL:

Data Type
Maximum Size Explanation
Syntax

DATE Values range from '1000-01-01' to '9999-12-31'. Displayed as 'YYYY-MM-DD'.

Values range from '1000-01-01 00:00:00' to Displayed as 'YYYY-MM-DD


DATETIME
'9999-12-31 23:59:59'. HH:MM:SS'.

Values range from '1970-01-01 00:00:01' UTC to Displayed as 'YYYY-MM-DD


TIMESTAMP(m)
'2038-01-19 03:14:07' UTC. HH:MM:SS'.

TIME Values range from '-838:59:59' to '838:59:59'. Displayed as 'HH:MM:SS'.

YEAR [(2|4)] Year value as 2 digits or 4 digits. Default is 4 digits.

7. Create Database

CREATE DATABASE testdb;

8. Create Table
To create a new table within a database, you use the MySQL CREATE TABLE statement.
The CREATE TABLE statement is one of the most complex statements in MySQL.

6
The following illustrates the syntax of the simplified version of the CREATE
TABLE statement:

CREATE TABLE [IF NOT EXISTS] table_name (


     column_list
)
ENGINE=storage_engine

First, you specify the name of the table that you want to create after the CREATE
TABLE clause. The table name must be unique within a database. The IF NOT EXISTS is an
optional clause that allows you to check if the table that you are creating already exists in
the database. If this is the case, MySQL will ignore the whole statement and will not create
any new table. It is highly recommended that you use IF NOT EXISTS in every CREATE
TABLE statement to avoid an error of creating a new table that already exists.
Second, you specify a list of columns for the table in the column_list section, columns are
separated by commas.
Third, you can optionally specify the storage engine for the table in the ENGINE clause. You
can use any storage engine such as InnoDB and MyISAM. If you don’t explicitly declare the
storage engine, MySQL will use InnoDB by default.

A storage engine is a software module that a database management system uses to create,
read, update data from a database. 

To define a column for the table in the CREATE TABLE statement, you use the following
syntax:

column_name data_type(length) [NOT NULL] [DEFAULT value] [AUTO_INCREMENT]

 The column_name specifies the name of the column. Each column has a specific data
type and maximum length e.g., VARCHAR(255) 
 The  NOT NULL indicates that the column does not allow NULL.
 The DEFAULT value is used to specify the default value of the column.
 The AUTO_INCREMENT  indicates that the value of the column is generated by one
automatically whenever a new row is inserted into the table. Each table has one and
only one AUTO_INCREMENT column.
If you want to set a column or a set of columns as the primary key, you use the following
syntax:

PRIMARY KEY (col1,col2,...)

7
CREATE TABLE IF NOT EXISTS tasks (
    task_id INT ,
    title VARCHAR (255) NOT NULL,
    start_date DATE,
    due_date DATE,
    status TINYINT NOT NULL,
    priority TINYINT NOT NULL,
    description TEXT,
    PRIMARY KEY (task_id)
);

9. Constraints
MySQL CONSTRAINT is used to define rules to allow or restrict what values can be stored in
columns. The purpose of inducing constraints is to enforce the integrity of a database.
MySQL CONSTRAINTS are used to limit the type of data that can be inserted into a table.
MySQL CONSTRAINTS can be classified into two types - column level and table level. The
column level constraints can apply only to one column whereas table level constraints are
applied to the entire table.

MySQL CONSTRAINT is declared at the time of creating a table:

CONSTRAINT DESCRIPTION

NOT NULL In MySQL NOT NULL constraint allows to specify that a column can not
contain any NULL value. MySQL NOT NULL can be used to CREATE and
ALTER a table.

UNIQUE The UNIQUE constraint in MySQL does not allow to insert a duplicate
value in a column. The UNIQUE constraint maintains the uniqueness of a
column in a table. More than one UNIQUE column can be used in a table.

8
PRIMARY KEY A PRIMARY KEY constraint for a table enforces the table to accept unique
data for a specific column and this constraint creates a unique index for
accessing the table faster.

FOREIGN KEY A FOREIGN KEY in MySQL creates a link between two tables by one
specific column of both tables. The specified column in one table must be
a PRIMARY KEY and referred by the column of another table known as
FOREIGN KEY.

CHECK A CHECK constraint controls the values in the associated column. The
CHECK constraint determines whether the value is valid or not from a
logical expression.

DEFAULT In a MySQL table, each column must contain a value ( including a NULL).
While inserting data into a table, if no value is supplied to a column, then
the column gets the value set as DEFAULT.

10. Alter Table

The ALTER TABLE statement modifies the structure of an existing table. It allows you to add a
column, drop a column, change the data type of column, add primary key, rename table, and
many more.
The following illustrates the ALTER TABLE statement syntax:
ALTER TABLE table_name action1[, action2…]
To change the structure of an existing table:

1. First, specify the table name, which you want to change, after the ALTER TABLE clause.
2. Second, list a set of actions that you want to apply to the table. An action can be anything
such as adding a new column, adding primary key,  or renaming table. The ALTER
TABLE statement allows you to apply multiple actions in a single ALTER TABLE statement,
actions are separated by a comma (,)

9.1 Example:
 ALTER TABLE tasks CHANGE COLUMN task_id task_number INT(11) NOT NULL
AUTO_INCREMENT;

 ALTER TABLE tasks


ADD COLUMN complete DECIMAL (2,1) NULL
AFTER description;

 ALTER TABLE tasks


RENAME TO work_items;

9
 ALTER TABLE tasks
DROP COLUMN description;

 UPDATE table_name
SET
column_name1 = expr1,
column_name2 = expr2,
...
[WHERE condition];

11. Practice Tasks

11.1 Task 1:
Write a query to create a table 'newbook' if it is already not available in the database with a
PRIMARY KEY on 'book _id' column, a unique constraint on 'isbn_no' column, a publication Id
and a set the no_page in such, that it would hold values more than zero only.

11.2 Task 2: [Time Required: 10


minutes]
Vehicle: Vehicle_id (Most probably reg. no), Company, Model, Color, Joining_date, Driver
[foreign key, unique].
Driver:

1) Driver_ id, DriverName [must be in upper case], DOB[Date of Birth must be in the
future], Hire_Date [hire date must be in the future].

2) Add a table level PRIMARY KEY constraint to the Vehicle table using the Vehicle_id
column. The constraint should be enabled at creation.

3) Create a PRIMARY KEY constraint to the Driver table using the Driver_id column.
The constraint should be enabled at creation.

Now insert at least 4 records/tuples in each of the table by query.

11.3 Task 3: [Time Required: 15


minutes]
1. Create a database of the name university.
2. Create the table Department, having columns department number,
3.

4. Now populate the table with 4 records.


10
5. Create the DEPT table based on the following table instance chart, then execute the
statement in the script to create the table. Confirm that the table is created.

Column Name ID NAME


Key Type
Nulls/Unique
FK Column
Data type Number VARCHAR
Length 7 25
6. Populate the DEPT table with data from the DEPARTMENTS table. Include only
columns that you need.

11.4 Task 4: [Time Required: 10


minutes]
1. Create the EMP table based on the following table instance chart and then execute
the statement in the script to create the table. Confirm that the table is created.
Column Name ID LAST_NAME FIRST_NAME DEPT_ID
Key Type
Nulls/Unique
FK Table
FK Column
Data type Number VARCHAR VARCHAR Number
Length 7 25 25 7

2. Modify the EMP table to allow for longer employee last names. Confirm your
modification.
3. Drop the FIRST_NAME column from the EMP table. Confirm your modification
by checking the description of the table.

12. Evaluation criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the
student has finished the complete/partial task(s).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 Task 1 2
2 1 Task 2 2
3 2 Task 3 3
4 3 Task 4 3

13. Further Reading


13.1 Books*
14. The slides and reading material can be accessed from the folder of the class instructor available
at vle.

11
9.1 Out comes
The outcomes of this lab were:
 DDL

12

You might also like