0% found this document useful (0 votes)
17 views

Lab Manual 04

The document provides instructions for a database systems lab on introductory SQL and DDL commands. It explains how to create and modify databases and tables using SQL commands like CREATE, ALTER, DROP, and RENAME. The objectives are to create a test database, use DDL commands to create and modify tables, and learn basic DDL concepts and syntax.

Uploaded by

frazbhai28
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lab Manual 04

The document provides instructions for a database systems lab on introductory SQL and DDL commands. It explains how to create and modify databases and tables using SQL commands like CREATE, ALTER, DROP, and RENAME. The objectives are to create a test database, use DDL commands to create and modify tables, and learn basic DDL concepts and syntax.

Uploaded by

frazbhai28
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Lab Manual

CS130L – Database Systems Lab


Lab No: 04
Topic: Intro to SQL and DDL

Class: BSAI
Semester: II-A
Session: Spring, 2024
Lab Instructor: Asra Masood

Lab Date: 7th March, 2024


Lab Time: 8:00 - 11:00

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

Instructions

Submission: Use proper naming convention for your submission file. Name the submission
file as Lab_NO_DEGREE_ROLLNUM (e.g. Lab_01_BSAI_00000). Submit the file on Google
Classroom within the deadline. Failure to submit according to the above format would result in
deduction of 10% marks. Submissions on the email will not be accepted.

Plagiarism: Plagiarism cases will be dealt with strictly. If found plagiarized, both the involved
parties will be awarded zero marks in the assignment, all of the remaining assignments, or even
an F grade in the course. Copying from the internet is the easiest way to get caught!

Deadline: The deadlines to submit the assignment are hard. Late submission with marks
deduction will be accepted according to the course policy shared by the instructor. Correct and
timely submission of the assignment is the responsibility of every student; hence no relaxation
will be given to anyone.

Comments: Comment your code properly. Write your name and roll number (as a block
comment) at the beginning of the solution to each problem.
Objectives
InTip
this: lab,
For you
timely
willcompletion
learn: of the assignment, start as early as possible. Furthermore, work
smartly - as some of the problems can be solved using smarter logic.
o1. About
Note: Structure
Follow theADT.
given instructions to the letter, failing to do so will result in a zero.
o How to define a Structure, initialize and refer to individual members of a Structure.

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

Objectives
In this lab, you will learn to:
• Create a test database.
• Create and modify tables in SQL using DDL commands.
• Basic DDL commands.

Concepts
Introduction:
Structured Query Language (SQL) was developed at IBM San Jose Research Laboratory as a part
of System R project. It is a declarative query language for querying a relational database. It also
includes features for defining the structure of the data, for inserting and modifying data in the
database, and for specifying security constraints. It is relational complete (it supports all six core
relational algebra operations). SQL commands can be classified into three groups DDL, DML &
DCL.
SQL DDL (Data Definition Language) commands are used to create and modify the databases.
Data Manipulation Language (DML) commands are used to query the databases.

DDL:
The Data Definition Language (DDL) is used to create and destroy databases and database
objects. These commands will primarily be used by database administrators during the setup
and removal phases of a database project. Let's take a look at the structure and usage of four
basic DDL commands:
1. CREATE
2. ALTER
3. DROP
4. RENAME
-- Database-Level
DROP DATABASE databaseName -- Delete the database (irrecoverable!)
DROP DATABASE IF EXISTS databaseName -- Delete if it exists
CREATE DATABASE databaseName -- Create a new database
CREATE DATABASE IF NOT EXISTS databaseName -- Create only if it does not exists
SHOW DATABASES -- Show all the databases in this server
USE databaseName -- Set the default (current) database

-- Table-Level
DROP TABLE [IF EXISTS] tableName, ...
CREATE TABLE [IF NOT EXISTS] tableName (
columnName columnType columnAttribute, ...
PRIMARY KEY(columnName),
FOREIGN KEY (columnNmae) REFERENCES tableName (columnNmae)
)
SHOW TABLES -- Show all the tables in the default database
DESCRIBE|DESC tableName -- Describe the details for a table
Air University Islamabad
FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

ALTER TABLE tableName ... -- Modify a table, e.g., ADD COLUMN and DROP COLUMN
ALTER TABLE tableName ADD columnDefinition
ALTER TABLE tableName DROP columnName
ALTER TABLE tableName ADD FOREIGN KEY (columnNmae) REFERENCES tableName (columnNmae)
ALTER TABLE tableName DROP FOREIGN KEY constraintName

IMPORTANT: Use SQL DROP (and DELETE) commands with extreme care, as the deleted entities
are irrecoverable. THERE IS NO UNDO!!!

• Creating and Deleting a Database - CREATE DATABASE and DROP DATABASE:


We can create a new database using SQL command "CREATE DATABASE
databaseName"; and delete a database using "DROP DATABASE databaseName". We
could optionally apply condition "IF EXISTS" or "IF NOT EXISTS" to these commands.

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

• Setting the Default Database – USE:


The command "USE databaseName" sets a particular database as the default (or
current) database. You can reference a table in the default database using tableName
directly. But we need to use the fully-qualified databaseName.tableName to reference a
table NOT in the default database.
To display the current default database, issue command "SELECT DATABASE()".

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

• Creating and Deleting a Table - CREATE TABLE and DROP TABLE:


We can create a new table in the default database using command "CREATE TABLE
tableName" and "DROP TABLE tableName". We can also apply condition "IF EXISTS" or
"IF NOT EXISTS". To create a table, you need to define all its columns, by providing the
columns' name, type, and attributes.

CREATE TABLE Syntax


CREATE TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)

create_definition:
col_name column_definition
| [CONSTRAINT [symbol]] PRIMARY KEY [index_type]
(index_col_name,...)
[index_option] ...
Air University Islamabad
FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

| {INDEX|KEY} [index_name] [index_type] (index_col_name,...)


[index_option] ...
| [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY]
[index_name] [index_type] (index_col_name,...)
[index_option] ...
| [CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name,...) reference_definition
| CHECK (expr)

column_definition:
data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
[COMMENT 'string']
[COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]
[STORAGE {DISK|MEMORY|DEFAULT}]
[reference_definition]

data_type:
INT[(length)] [UNSIGNED] [ZEROFILL]
| INTEGER[(length)] [UNSIGNED] [ZEROFILL]
| REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]
| DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]
| FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]
| DECIMAL[(length[,decimals])] [UNSIGNED] [ZEROFILL]
| NUMERIC[(length[,decimals])] [UNSIGNED] [ZEROFILL]
| DATE
| TIME[(fsp)]
| TIMESTAMP[(fsp)]
| CHAR[(length)] [BINARY]
| VARCHAR(length) [BINARY]
| BINARY[(length)]
| VARBINARY(length)
| BLOB
| TEXT [BINARY]

reference_definition:
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]

reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

The show table command shows existing tables in the database as shown in the figure
below:

Let’s create a table by running the following query:

Refresh the database from navigator to see the table and also run SHOW TABLES again
to see the table:

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

To see the details of the table created run the query “Describe products (table_name)”:

Let’s delve deeper into the explanation of the table created above and it’s colums and
their properties.
Explanations:
We define 5 columns in the table products: productID, productCode, name, quantity and
price. The types are:
▪ productID is INT UNSIGNED - non-negative integers.
▪ productCode is CHAR(3) - a fixed-length alphanumeric string of 3 characters.
▪ name is VARCHAR(30) - a variable-length string of up to 30 characters. We use
fixed-length string for productCode, as we assume that the productCode

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

contains exactly 3 characters. On the other hand, we use variable-length string


for name, as its length varies - VARCHAR is more efficient than CHAR.
▪ quantity is also INT UNSIGNED (non-negative integers).
▪ price is DECIMAL(10,2) - a decimal number with 2 decimal places.DECIMAL is
precise (represented as integer with a fix decimal point). On the other hand,
FLOAT and DOUBLE (real numbers) are not precise and are approximated.
DECIMAL type is recommended for currency.
The attribute "NOT NULL" specifies that the column cannot contain the NULL value.
NULL is a special value indicating "no value", "unknown value" or "missing value". In our
case, these columns shall have a proper value. We also set the default value of the
columns. The column will take on its default value, if no value is specified during the
record creation.
We set the column productID as the so-called primary key. Values of the primary-key
column must be unique. Every table shall contain a primary key. This ensures that every
row can be distinguished from other rows. You can specify a single column or a set of
columns (e.g., firstName and lastName) as the primary key. An index is built
automatically on the primary-key column to facilitate fast search. Primary key is also
used as reference by other tables.
We set the column productID to AUTO_INCREMENT with default starting value of 1.
When you insert a row with NULL (recommended) (or 0, or a missing value) for the
AUTO_INCREMENT column, the maximum value of that column plus 1 would be
inserted. You can also insert a valid value to an AUTO_INCREMENT column, bypassing
the auto-increment.

• Modify tables - ALTER TABLE or RENAME:


This is used to add or remove some extra fields, change the width as well as data type or
name of fields of existing relations.
ALTER TABLE tbl_name
[alter_specification [, alter_specification] ...]
[partition_options]
alter_specification:
table_options
| ADD [COLUMN] col_name column_definition
[FIRST | AFTER col_name ]
| ADD [COLUMN] (col_name column_definition,...)
| ADD {INDEX|KEY} [index_name]
[index_type] (index_col_name,...) [index_option] ...
| ADD [CONSTRAINT [symbol]] PRIMARY KEY
[index_type] (index_col_name,...) [index_option] ...
| ADD [CONSTRAINT [symbol]]
UNIQUE [INDEX|KEY] [index_name]
[index_type] (index_col_name,...) [index_option] ...
| ADD [CONSTRAINT [symbol]]

Air University Islamabad


FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies
CS130L – Database Systems Lab Manual

FOREIGN KEY [index_name] (index_col_name,...)


reference_definition
| ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT}
| CHANGE [COLUMN] old_col_name new_col_name column_definition
[FIRST|AFTER col_name]
| MODIFY [COLUMN] col_name column_definition [FIRST | AFTER
col_name]
| DROP [COLUMN] col_name
| DROP PRIMARY KEY
| DROP {INDEX|KEY} index_name
| DROP FOREIGN KEY fk_symbol
| DISABLE KEYS
| ENABLE KEYS
| RENAME [TO|AS] new_tbl_name
| ORDER BY col_name [, col_name] ...

For details of alter visit:


https://dev.mysql.com/doc/refman/8.3/en/alter-table.html
Try alter commands yourself and update column names and datatypes etc. to
understand the working of Alter.

Lab Task:
Problem Statement:
Given the following database schema:
Student (snum: integer, sname: char(30), major: char(25), level: char(2))
Faculty (fid: integer, fname: char(30), deptid: integer)
Class (cname: char(40), meets_at: char(20), room: char(10), fid: integer | fid REFS Faculty.fid)
Enrolled (snum: integer, cname: char(40) | snum REFS student.snum, cname REFS class.name)

Write SQL expressions for each of the following queries and execute them:
1. Create a database for these four relations. You need to define the primary keys and
foreign keys in your statement. After creating the database, evolve it as follows.
2. Add a new attribute age in STUDENT table.
3. Modify data type of attribute: NAME (i.e. cname, sname, fname) in all tables to
varchar data type.
4. Add a new NOT NULL constraint to DEPTID in FACULTY table.
Air University Islamabad
FACULTY OF COMPUTING & ARTIFICAL INTELLIGENCE
Department of Creative Technologies

You might also like