You are on page 1of 19

Lab Manual for Introduction to Database Systems

Lab-01
Introduction to SQL Tools and Data Definition Language (DDL)
Contents

1. Introduction 4

2. Activity Time boxing 4

3. Objective of the experiment 4

4. Concept Map 4
4.1 Relational Data Model: 4
4.2 Database Management System (DBMS): 5
4.3 Relational Database Management System (RDBMS): 5
4.4 SQL (Structured Query Language): 5
4.4.1 Data Definition Language 5
4.4.2 Data Manipulation Language 5
4.4.3 Data Control Language 5
4.5 MySQL: 5
4.6 PHP: 6
4.7 PHPMyAdmin: 6
4.8 XAMPP: 6

5. Homework before Lab 6


5.1 Task 1 6

6. Procedure & Tools 6


6.1 Installing and Configuring XAMPP (MySQL, Apache) 6
6.1.1 Download XAMPP from http://www.apachefriends.org/en/xampp.html.
XAMPP for Windows exists in three different flavors. The “Installer” version is
“probably the most comfortable way to install XAMPP” according to the XAMPP
website. 6
6.1.2 Start the XAMPP installation. Note that Windows 7,8, and 10 will warn that
installing to the Program Files directory will keep XAMPP from being able to write to
its directory due to UAC see Figure 1. Disabling UAC is not recommended. XAMPP
can be installed to C:\XAMPP to avoid this issue or XAMPP can be given permission
to run as Administrator. 6
6.1.3 Configuring the Environment Variable 9
6.2 Walkthrough Tasks 12
6.2.1 Creating A Database Using CREATE DATABASE Statement 13
6.2.2 View Available Databases Using SHOW DATABASES Statement 13
6.2.3 Selecting A Database Using USE Statement 14
6.2.4 Creating A Table In Selected Database Using CREATE TABLE Statement 14
6.2.5 View Available Tables Using SHOW TABLES Statement 17
6.2.6 View the Details Of A Table Using DESCRIBE Statement 17
6.2.7 ALTER TABLE 18
6.2.8 Dropping A Table: 21
6.2.9 Dropping A Database: 22

7. Practice Tasks 23
7.1 Practice Task 1 [Expected time = 65mins] 23
7.1.1 Customers 23
7.1.2 Payments 23
7.1.3 Practice queries 23

8. Evaluation Task (Unseen) [Expected time = 30mins for tasks] 2

9. Evaluation criteria 2

10. Further Reading 2


10.1 Slides 2

11. REFERENCES: 2
11.1 SQL-99 Complete, Really, by Peter Gulutzan & Trudy Pelzer. 2
1. HOW TO READ SQL SYNTAX 9
1.1. < >  Angle brackets: 9
1.2. [ ]  Square brackets: 9
1.3. { }  Braces: 9
1.4. ()  Small Brackets: 9
1.5. |  The vertical: 10
1.6. ...  Elipsis: 10
1.7. Blank spaces: 10
Lab 01: Introduction to SQL and Tools
Introduction
You are learning databases, database models, and database management systems, particularly
relational data model and relational database management system (RDBMS). In this lab, you will
get familiar with the tools required for database management. You will use XAMPP application
stack that includes MySQL Database Server, Apache Web Server, PHP interpreter, MySQL CLI
(Statement Line Interface) and PHPMyAdmin as a management system for MySQL Server.

Relevant Lecture Material

a) Revise Lecture No. 3 and 4


b) Text Book: Database Systems, A practical approach to design, implementation,
and management by Thomas Connolly, Carolyn Begg, Addison Wesley, Fifth
Edition,

1. Read pages:
2. Read URL:
i. http://www.tomjewett.com/dbdesign/dbdesign.php?
page=ddldml.php
3. Revise the DDL

Activity Time boxing

Task No. Activity Name Activity time Total Time


6.2 Installing and Setting Up 15mins 15mins
XAMPP (MySQL, Apache)
6.3 Walkthrough Tasks 5mins 60mins
7 Practice tasks 10mins for each task 45mins
Table 1: Activity Time Boxing

Objective of the experiment


 To learn the installation, setup, and usage of tools required for relational database
management.
 To learn to implement a database schema in a database management system.

Concept Map
In this section, a brief overview of the concepts is presented, those will be used in this lab
afterwards.

4.1. Relational Data Model:


The relational model is centered on this idea of data organization into collections of two-
dimensional tables called “relations.” Each row of the table is called a Tuple or Record. And
each column is given a name and is called Attribute.
4.2. Database Management System (DBMS):
A database management system (DBMS) is a computer software application that interacts with
the user, other applications, and the database itself to manage data in databases. A general-
purpose DBMS is designed to allow the definition, creation, querying, update, and administration
of databases.

4.3. Relational Database Management System (RDBMS):


A relational database management system (RDBMS) is a database management system (DBMS)
that is based on the relational model.

4.4. SQL (Structured Query Language):


SQL (Structured Query Language) is the standard language used for the retrieval and
management of data in relational databases (RDBMS). It also supports database schema
definition and modification. It is supported by all modern database management systems (e.g.
Oracle, IBM DB2, Microsoft Access, Microsoft SQL Server, PostgreSQL, MySQL, etc.).

SQL is based on the relational model. The basic data structure in RDBMS is a table. SQL
provides you the features to define tables, define constraints on tables, query for data in the table,
and change the data in the table by adding, modifying, and removing data. SQL also supports
grouping of data in multiple rows, combining tables and other features.

SQL is high-level declarative language, quite easy to learn, allowing complex tasks on a database
to be specified simply. SQL has a defined syntax that specifies how standard keywords can be
combined to form valid SQL statements. SQL statements can be divided into three categories,
according to their function:

Data Definition Language


Statements that create, modify or destroy database objects (such as tables). These statements
begin with the keywords: CREATE, ALTER or DROP.

Data Manipulation Language


Statements that retrieve, insert, update, edit or delete data stored in database tables. These
statements begin with the keywords: SELECT, INSERT, UPDATE or DELETE.

Data Control Language


Statements that authorize certain users to view, change or delete data. These statements begin
with the keywords: GRANT or REVOKE. We do not consider data control in the lab exercises.

4.5. MySQL:
MySQL is a free, open-source, and the most popular relational database management system
(RDBMS).

4.6. PHP:
PHP is a server-side scripting language and a powerful tool for making dynamic and interactive
Web applications. PHP is a widely-used, free, and open source.
4.7. PHPMyAdmin:
PHPMyAdmin is a free and open source tool written in PHP intended to handle the
administration of MySQL with the use of a web browser.

4.8. XAMPP:
XAMPP is a free and open source cross-platform web server solution stack package developed
by Apache Friends. It includes MySQL, PHP, and PHPMyAdmin.

Homework before Lab


You must solve the following problems at home before the lab.

4.9. Task 1
Study Relational Data Model.

Procedure & Tools


In this section, procedure of the tasks and setup of required tools is defined.

4.10. Installing and Configuring XAMPP (MySQL, Apache)

Download XAMPP from http://www.apachefriends.org/en/xampp.html. XAMPP for


Windows exists in three different flavors. The “Installer” version is “probably the most
comfortable way to install XAMPP” according to the XAMPP website.

Start the XAMPP installation. Note that Windows 7,8, and 10 will warn that installing to the
Program Files directory will keep XAMPP from being able to write to its directory due to
UAC see Figure 1. Disabling UAC is not recommended. XAMPP can be installed to C:\
XAMPP to avoid this issue or XAMPP can be given permission to run as Administrator.

Figure 1: UAC Warning

The XAMPP installation starts with a splash screen, see Figure 2. Click “Next”.
Figure 2: XAMPP Setup Wizard

Select the tools you want to install, see Figure 3.

Figure 3: XAMPP Options


Choose which directory to install XAMPP. In Figure 4, It is being installed in a directory
xampp under drive D.

Figure 4: Xampp Startup

Click Next to complete the installation. It may take a while. After the completion, it prompts
with a dialogue box, see Figure 5. Click “Yes” Button.

Figure 5: Setup Complete Popup

The XAMPP installation completes. The XAMPP control panel can be started. Start Apache
and MySql by clicking the start button next to them, see Figure 6.
Figure 6: XAMP Control Panel

If Apache gives the error “Port 80 is in use by “Some Other Process” with PID X!”, we would
have to change the port see Appendix II.

Configuring the Environment Variable


To run MySQL CLI, the path to MySQL bin folder is required to be configured in an
environment variable named PATH. To make windows’ console aware of the MySQL tools.
Following are the steps to configure PATH variable for MySQL tools.

Go to Control Panel > System and Security > System and Click Advanced system settings, See
Figure 7.

Figure 7: Advance System Settings


Click Environment Variables, See Figure 8.

Figure 8: System Properties

Variable name PATH is available double click it, otherwise click NEW, See Figure 9.

Figure 9: Environment Variables


Copy Path to MySQL > BIN folder from inside your XAMPP installation folder, See Figure 10.

Figure 10: Path of bin folder

Paste the copied path in Variable Value field for the Variable Name PATH. See Figure 11.

Figure 11: Edit User Variable

Open Statement prompt and Write statement MySQL then press Enter key, See Figure 12.

Figure 12: Statement Prompt for starting MySQL


MySQL CLI is now running we can now start using it.

4.11. Walkthrough Tasks


These tasks are designed to guide you to use the tools, implement the basic concepts of DDL.
There are three basic statements within the DDL i.e. CREATE, DROP and ALTER. We will be
focusing on CREATE, USE, ALTER, and DROP statements in this lab.

We will use MySQL RDBMS that provides Console and GUI based tools to run or test our SQL
Queries. We will use MySQL CLI and an open source web based GUI tool called
“PHPMyAdmin” to execute our SQL queries. We will start with MySQL CLI, a statement line
interface, see Figure 12. Login to MySQL CLI with “root” user and empty string as password.
Type following statement in statement line and hit Enter, it will ask for password, as password is
empty string, simply Hit Enter again. See Figure 13.

MySQL -u root -p

Figure 13: Logging in to MySQL CLI

At MySQL CLI, as shown in Figure 13, you can enter database statements followed by Enter.

Note that:
1. Most MySQL statements end with a semicolon (;)
2. MySQL returns the total number of rows found, and the total time to execute the query.
3. Keywords may be entered in any letter case i.e. uppercase or lowercase.

Now we will start using the MySQL CLI to create and manage databases. We would learn SQL
statements in the following sections. For each statement, first its generic definition is provided
and then explained with an example, to learn the generic definition of MySQL statement read
Appendix III.

Creating A Database Using CREATE DATABASE Statement


You first need to create a database in which you will store your tables. This can be considered
analogous to opening a blank database. To create a database, we use the CREATE DATABASE
statement.
Figure 14: Creating “Shop_db” database

In Figure 14, A database named “shop_db” is created.

View Available Databases Using SHOW DATABASES Statement


To show all the databases available on MySQL server, we use the SHOW DATABASES
statement. See Figure 15.

Figure 15: Viewing all available databases

Selecting A Database Using USE Statement


Before starting to work (e.g. create tables, write queries etc.) with your database, you must select
the database you are going to use. To do this, we use the USE statement.

Figure 16: Select or Change the current database.

In Figure 16, we have selected a database “shop_db” to perform further operations.


Creating A Table In Selected Database Using CREATE TABLE Statement
To create tables, we use the CREATE TABLE statement, the generic syntax of CREATE
TABLE statement is:

CREATE TABLE [IF NOT EXISTS] <table_name> (


<column_name> <columnDataType> <columnConstraints>, ... )

For Example,

CREATE TABLE movies (


m_id int(10),
m_title varchar(255)
m_year year
);

By running the above example, a table would be created with the name “movies” which has 3
columns: m_id, m_title, and m_year. In MySQL, we must specify a data type for each field. The
following section tells about the data types in detail.

DataTypes
We can specify with each column, the data type for that column, See Appendix I for a complete
list of MySQL data types, the most commonly used data types in MySQL are given in the Table
3.

Data Type Description


TINYINT, SMALLINT, MEDIUMINT, INT, Integer values
BIGINT
FLOAT, DOUBLE Floating-point values
DECIMAL Decimal values
CHAR Fixed length strings up to 255 characters
VARCHAR Variable length strings up to 255 characters
TINYBLOB, BLOB, MEDIUMBLOB, Longer blocks of text data
LONGBLOB
DATE, TIME, YEAR Date; time or duration; year values
DATETIME Combined data and time values
TIMESTAMP Timestamps
ENUM One of a set of predefined values
SET Zero or one
Table 3: The most commonly used data types in MySQL.

Constraints
In addition to the data type of the columns, we can also specify field modifiers/constraints and
keys when creating a table:

 Is the column’s value allowed to be empty? We can specify this using the constraints
NULL and NOT NULL.

For Example,
CREATE TABLE movies (
m_id int(10) NOT NULL,
m_name varchar(255) NOT NULL
);

 Using the DEFAULT modifier we can specify a default value for the column.

For Example,
CREATE TABLE movies (
m_id int(10) NOT NULL,
m_name varchar(255) NOT NULL DEFAULT ‘No Name’,
);

 If we want the values for a column to be unique, we can use the UNIQUE modifier.

For Example,
CREATE TABLE movies (
m_id int(10),
m_name varchar(255) UNIQUE,
);

View Available Tables Using SHOW TABLES Statement


To view all the tables available in the current database, we use SHOW TABLES statement. In
Figure 17, All tables of shop_db are being viewed.

Figure 17: Viewing tables in the shop_db database.

View the Details Of A Table Using DESCRIBE Statement


To view the columns, their data types and constraints applied on the columns we use DESCRIBE
statement. The generic syntax of DESCRIBE statement is:

DESCRIBE <tablename>;
For Example, to view the details of “movies” table, the following statement would be written,
see Figure 18.
DESCRIBE movies;

Figure 18: Viewing details of movies table.

1.1. Inserting Data using INSERT INTO Statement


There are multiple ways to insert new records using the INSERT INTO statement.

1.1.1. Inserting single record


To insert single record with all column values, the syntax is:

INSERT INTO tableName VALUES (column1Value, ..., columnNValue);

You need to list the values in the same order in which the columns are defined in the CREATE
TABLE, separated by commas. For columns of string data type (CHAR, VARCHAR), enclosed
the value with a pair of single quotes (or double quotes). For columns of numeric data type (INT,
DECIMAL, FLOAT, DOUBLE), simply place the number.

For Examples,
To insert a record of an office which have values available for all the columns i.e. officeCode is
“Of123”, city is “Islamabad”, phone is “+1234567”, addressLine1 is “office 1, Street 1”,
addressLine2 is “block 1”, state is “Punjab”, country is “Pakistan”, postalCode is “47080”, and
territory is “Islamabad”, the following statement can be written:

INSERT INTO offices VALUES (‘Of123’, ‘Islamabad, ‘+1234567’, ‘office 1, street 1’, ‘block
1’, ‘Punjab’, ‘Pakistan’, 123456, ‘Islmabad’)

1.1.2. Inserting multiple records


Multiple records can also be inserted in one INSERT INTO statement:

INSERT INTO tableName VALUES


(row1FirstColumnValue, ..., row1lastColumnValue),
(row2FirstColumnValue, ..., row2lastColumnValue),
... ;

e.g. To in record of two offices:

INSERT INTO offices


VALUES
(‘Of123’, ‘Islamabad, ‘+1234567’, ‘office 1, street 1’, ‘block 1’, ‘Punjab’, ‘Pakistan’,
123456, ‘Islmabad’),
(‘Of124’, ‘Islamabad, ‘+567891’, ‘office 2, street 1’, ‘block 10’, ‘Punjab’, ‘Pakistan’,
345678, ‘Islmabad’)

1.1.3. Inserting Single Record with Specific Columns


To insert single record with some specific column values, the syntax is:

INSERT INTO tableName


(column1Name, …, columnNName)
VALUES
(column1Value, ..., columnNValue);

To insert a record of an office which have values available for some columns i.e. officeCode is
“Of123”, city is “Islamabad”, phone is “+1234567” and addressLine1 is “office 1, Street 1”,
values of other columns are not available, the following statement can be written:
e.g. INSERT INTO offices
(officeCode, city, phone, addressLine1)
VALUES
(‘Of123’, ‘Islamabad, ‘+1234567’, ‘office 1, street 1’)

1.1.4. Inserting Multiple Record with Specific Columns


Multiple records can also be inserted in one INSERT INTO statement:

INSERT INTO tableName


(column1Name, …, columnNName)
VALUES
(column1Value, ..., columnNValue),
(column1Value, ..., columnNValue)
…;

e.g. To in record of two offices:

INSERT INTO offices


(officeCode, city, phone, addressLine1)
VALUES
(‘Of123’, ‘Islamabad, ‘+1234567’, ‘office 1, street 1’)
(‘Of124’, ‘Karachi, ‘+5456789’, ‘street 1, main highway’)

Note:
 Inserting NULL to the auto_increment column results in max_previous_value + 1
 A column defined with NOT NULL constraint and no DEFAULT constraint, must have a
value i.e. it cannot be NULL.

4.12. Reading the data from database using SELECT statement.


The most common, and important task is to query a database for a subset of data that meets your
needs with the SELECT statement. The output of the select statement is a two-dimensional table,
known as the ResultSet. Please note that, to use the SELECT statement a database must be
selected first using USE statement, see section 6.3.3 of Lab 01.

The SELECT command has the following syntax:

SELECT column1Name, column2Name, ... FROM tableName

For example,
To select all rows from the table products for the columns name, and price
mysql> SELECT name, price FROM products;

+-----------+-------+
| name | price |
+-----------+-------+
| Pen Red | 1.23 |
| Pen Blue | 1.25 |
| Pen Black | 1.25 |
| Pencil 2B | 0.48 |
| Pencil 2H | 0.49 |
+-----------+-------+
5 rows in set (0.00 sec)

4.12.1. Select statement for all rows and all columns.


To select all rows and all columns of offices, execute the following query, see Figure 4.

SELECT * from offices;


Figure 3: Select all rows for all columns

4.12.2. Select command for specific column.


To select all rows and officeCode, coutry, and phone columns of offices, execute the following
query, see Figure 5.

SELECT officeCode,coutry,phone from offices;

Figure 4: Select Statement for Specific Column.

You might also like