Lab Manual - Database Systems Lab 01: Creating and Configuring The Database
Lab Manual - Database Systems Lab 01: Creating and Configuring The Database
Page 1
Created by Turbolearn AI
Page 2
Created by Turbolearn AI
1. Make sure your MySQL is already running (MySQL is highlighted green in xamp
control panel).
2. Open MySQLWorkbench folder and click on the blue-colored MySQLWorkbench.exe
file.
3. If there is no connection shown, then click on the "plus-shaped" icon to create a
new connection.
4. Input a connection name “mycon”.
5. The User name should be root.
6. The Password should be blank and click save, click test to see the response. If
the response is "connection parameters are correct" your connection is
successful.
7. Now double click on the “mycon” connection icon, MySQLWorkbench should be
connected with the MySQL, and existing databases should be shown at the left
side.
8. Go to Edit -> Preferences.
9. Click on “Sql Editor” and at the below of page uncheck option under “Safe
Updates”.
10. Click “Close” button on top right corner of MySQLWorkbench to exit program.
11. After the program is exit, re-open MySQLWorkbench.
1. Open MySQLWorkbench folder and click on File -> New query tab. Or click on plus
file icon just below the File, this will open a new query window.
2. Write the following query to see the existing databases:
SHOW DATABASES;
The image shows the result of executing the "show databases;" command in MySQL
Workbench, revealing a list of existing databases.
Page 3
Created by Turbolearn AI
3. If “Pharmacy” is not present in the list of databases, in the new query tab, write
following query:
The image shows the result of creating the "Hospital" schema in MySQL Workbench.
5. Execute the queries. If the final green message “COMMIT” appears, the
database is imported successfully, otherwise, review your all steps, as you must
have missed any of the above steps.
Page 4
Created by Turbolearn AI
USE Hospital;
SHOW TABLES;
USE Hospital;
SELECT * FROM city;
The query retrieves and displays all columns and rows from the city table in the
Hospital database, as shown in the image.
NOTE: Here “*” means, retrieve “all columns” from the table.
Examples
Page 5
Created by Turbolearn AI
USE pinevalley;
SELECT CustomerName, CustomerCity, CustomerID FROM customer_t;
USE pinevalley;
SELECT * FROM customer_t WHERE customerid=5;
USE pinevalley;
SELECT * FROM customer_t WHERE customerid>=5;
USE pinevalley;
SELECT * FROM customer_t WHERE customerid >=5 AND customerid <=8 AND custo
USE pinevalley;
SELECT customerid, customername, customeraddress FROM customer_t WHERE cus
Page 6
Created by Turbolearn AI
Commands
Command to show the tables in a database:
USE Pinevalley;
SHOW TABLES;
SELECT CURTIME();
-- OR
SELECT CURTIME() AS mytime;
SELECT 8+4;
-- OR
SELECT 8+4 AS ans;
Page 7
Created by Turbolearn AI
The image shows the successful creation of a table named "places" in MySQL
Workbench.
Page 8
Created by Turbolearn AI
Drop Table
Page 9
Created by Turbolearn AI
The WHERE expression can have either column of the table, but the PRIMARY key column
is used to avoid unwanted deletion of data.
For example:
This will delete all the rows with the name Ali.
TRUNCATE temp;
-- OR
DELETE FROM temp;
Page 10
Created by Turbolearn AI
Objectives:
UPDATE product_t
SET productstandardprice = 775
WHERE productid = 7;
UPDATE temp
SET name = 'javed', address = 'def'
WHERE id = 2;
Page 11
Created by Turbolearn AI
UPDATE temp
SET name = 'javed', address = 'pakistan'
WHERE id>3;
If this returns a row, then the row exists, and you can run the UPDATE query.
UPDATE product_t
SET ProductStandardPrice = 775
WHERE ProductID = 7;
This will update the value of the ProductStandardPrice from 800 to 775.
Page 12
Created by Turbolearn AI
This will insert two rows into the table PERSONS. Note that we gave the ID for the first
row i.e., 11, and we did not give any ID for the second row. It automatically
incremented the next row ID based on the maximum ID in the rows already inserted.
In the next row, the ID will be automatically inserted as 12.
The table is altered for its auto-increment value. Insert another record into the table.
Page 13
Created by Turbolearn AI
Objectives:
Creating Indexes
Indexes are created in RDBMS to provide rapid and sequential access to base
table data.
Indexes are usually created both for primary and secondary keys and both
single and concatenated (multiple column keys).
DESCRIBE CUSTOMER_T;
DESCRIBE CUSTOMER_T;
Drop Indexes
To remove the index on the customer name in the table:
Page 14
Created by Turbolearn AI
Even after dropping the foreign key, the index still resides and has to be dropped
manually, by:
Page 15
Created by Turbolearn AI
Example:
Page 16
Created by Turbolearn AI
1. DISTINCT
2. *
DISTINCT: If the user does not wish to see duplicate rows in the result.
Example:
And count the number of rows returned (7 rows are returned). Duplicate rows are
removed from the results (that was ‘Computer Desk’).
Page 17
Created by Turbolearn AI
What is the address of the customer named ‘Home Furnishings’? Use an alias, Name,
for the customer name.
This returns the columns with their alias names, i.e., Name for CustomerName and
Address for CustomerAddress.
The below query will return the data in the original order of columns as they were
appearing in the actual table (the order in which they were appearing when the table
was created).
Page 18
Created by Turbolearn AI
Now we want to change the order of columns in the retrieved record in the next
query.
Query: List the unit price, product name, and product ID for all products in the
product table, in the same order as given in this statement.
Using Expressions
Query: What are the standard price and standard price if increased by 10% for every
product?
Returns two columns, one the ProductStandardPrice and the other column with the
price increased by 10% and its alias name as IncreasedBy10.
Multiplying 1.1 is equivalent to calculating 10% and adding it to the Product Price.
Using Functions
Page 19
Created by Turbolearn AI
String:
Date
Analytical
TOP(): find the top n values in a set, e.g. top 5 customers by total annual
sales
These are only basic functions, search more functions regarding your need on the
MySQL website.
Query: What is the average standard price for all products in inventory?
Understand the use of some of the built-in functions, such as COUNT, MIN, and
MAX.
Page 20
Created by Turbolearn AI
How many different items were ordered on order number 1001, and what are they?
This query should return an error because COUNT returns only one row, though we are
selecting multiple rows for productID. It will return an error in SQL Server or Oracle,
but for MySQL, the query returns the 1st productID along with the count as the query
result.
Query: Display for each product the difference between its standard price and the
overall average standard price of all the products.
Page 21
Created by Turbolearn AI
SELECT
ProductStandardPrice,
ProductStandardPrice - (
SELECT AVG(ProductStandardPrice)
FROM PRODUCT_T
) AS Difference
FROM PRODUCT_T;
The MIN() function is used for numeric values as well as string values, but if there is a
string starting with a numeric value then the numeric value of the string will be used
for comparison (while the rest of the string will be truncated). If instead, we use the
MAX function, it will give preference to string value, and the string starting with the
highest alphabet position will be returned (ignoring the string starting with the
numeric value).
Learn the work of various comparison operators and the use of the NULL
keyword.
Page 22
Created by Turbolearn AI
Query: What furniture does Pine View carry that is not made of Cherry?
NULL value means a column is missing a value; the value is not zero, or
blank, or any special code – there is simply a NULL value.
The functions may produce different results where NULL values are present than
when a column has a value of zero.
Query: Display all customers for whom we do not know their Postal Code.
-- below query returns all rows for which CustomerPostalCode contains NULL
SELECT * FROM CUSTOMER_T
WHERE CustomerPostalCode IS NULL;
-- below query returns all rows for which CustomerPostalCode does not cont
SELECT * FROM CUSTOMER_T
WHERE CustomerPostalCode IS NOT NULL;
Learn different types of logical operators and how they are used to filter data in
select queries. The use of the DISTINCT operator will also be discussed.
Page 23
Created by Turbolearn AI
AND: Joins two or more conditions and returns results only when all conditions
are true.
OR: Joins two or more conditions and returns results when at least one condition
is true.
NOT: Negates an expression.
Order of Preference:
If multiple Boolean operators are used in an SQL statement, NOT is evaluated first,
then AND, then OR.
Query: List Product Name, Finish, and Standard Price for all desks and all tables that
cost more than $300 in the product table.
% before the string acts as a wildcard that anything can appear before the
string, but should end with the string.
Vice versa, % after the string acts as a wildcard that anything can appear after
the string but should start with the string.
If % is added before and after the string, the string can appear as a substring in a
string, either in the start, mid, or end.
Expression Column Value Returns
Page 24
Created by Turbolearn AI
Query: Which product in the product table has a standard price between 200and300?
If we are interested only in seeing which order IDs are appearing rather than how
many times they are appearing, we will use DISTINCT.
Query: What are distinct order numbers included in the orderline table?
Understand the two very important keywords in SQL that are IN and NOT IN,
and how to sort data using the ORDER BY clause.
Page 25
Created by Turbolearn AI
Query: List Customer, City, and State for all customers in the Customer table whose
address is Florida, Texas, California, or Hawaii. List the customers alphabetically by
state and alphabetically by customer within the state.
Page 26
Created by Turbolearn AI
The LIMIT operator is used to constrain the number of results returned by a query or
to specify a range of rows to return.
Example:
This query skips the first 3 rows and returns the next 5 rows from the result set.
Page 27
Created by Turbolearn AI
This query counts the number of customers in each city, listing the cities by state,
effectively nesting groups within groups.
You can include multiple conditions in the HAVING clause using AND, OR, and NOT.
Example: List the product finish and average standard price for selected finishes with
an average standard price less than 750, ordered alphabetically by finish.
Defining Views
Page 28
Created by Turbolearn AI
Example: Create a view named Invoice_v to gather data elements necessary to create
an invoice for a customer.
Example: Retrieve data elements for invoice number 1004 using the Invoice_V view.
Example: Create a view to find the total value of orders placed for each furniture
product.
Example: Create a view to list all furniture products that have ever had a standard
price over $300.
Page 29
Created by Turbolearn AI
The image shows a database schema with three tables (TABLE1, TABLE2, and
TABLE3) joined through primary key/foreign key relationships. TABLE1 has columns
T1ID and T1Name, TABLE2 has T2ID, T2Name, and T1ID (foreign key), and TABLE3
has T3ID, T3Name, and T2ID (foreign key). This schema visually represents how
data can be related across multiple tables in a database.
Example: Retrieve values from three tables joined through primary key/foreign key
relationships using equi-join.
Example: Retrieve customer IDs, names, and order IDs for all orders placed.
Page 30
Created by Turbolearn AI
Example: Retrieve customer IDs, names, and order IDs using INNER JOIN.
Outer Join
An outer join includes rows that do not have matching values in common columns.
Null values appear in columns where there is no match between tables.
Example Use Case: Identify customers who have not placed any orders to encourage
new orders or analyze why they are not ordering.
Page 31
Created by Turbolearn AI
This query also returns rows where the foreign key column does not exist (NULL).
Self Join
A self join involves matching rows in a table with other rows in the same table.
SELECT
Customer_t.CustomerID,
CustomerName,
CustomerAddress,
CustomerCity,
CustomerState,
CustomerPostalCode,
Order_t.OrderID,
OrderedQuantity,
ProductDescription,
ProductStandardPrice,
(OrderedQuantity * ProductStandardPrice) AS price
FROM
Order_t,
Customer_t,
Orderline_t,
Product_t
WHERE
Customer_t.Customerid = Order_t.CustomerID
AND Orderline_T.orderID = order_t.orderid
AND orderline_t.ProductID = product_t.productid
AND Order_t.OrderID = 1006;
Page 32
Created by Turbolearn AI
SELECT
E.EmployeeID,
E.EmployeeName,
M.EmployeeName AS Manager
FROM
Employee_T E,
Employee_T M
WHERE
E.EmployeeSupervisor = M.EmployeeID;
Subqueries
Subqueries Overview
Subqueries involve placing an inner query (SELECT . . . FROM . . . WHERE) within a
WHERE or HAVING clause of another (outer) query. The inner query provides a set of
one or more values for the search condition of the outer query.
Example (Not Subquery): Retrieve the name and address of the customer who
placed order number 1008.
SELECT
CustomerName,
CustomerAddress,
CustomerCity,
CustomerState,
CustomerPostalCode
FROM
Customer_T,
Order_T
WHERE
Customer_T.CustomerID = Order_T.CustomerID
AND OrderID = 1008;
Example (Subquery): Retrieve the names of customers who have placed orders.
Page 33
Created by Turbolearn AI
SELECT
CustomerName,
CustomerAddress,
CustomerCity,
CustomerState,
CustomerPostalCode
FROM
Customer_T
WHERE
Customer_T.CustomerID = (SELECT Order_T.CustomerID FROM Order_T WHERE
SELECT CustomerName
FROM Customer_T
WHERE CustomerID IN (SELECT DISTINCT CustomerID FROM Order_T);
SELECT CustomerName
FROM Customer_T
WHERE CustomerID NOT IN (
SELECT CustomerID
FROM Order_T, OrderLine_t, Product_T
WHERE OrderLine_t.OrderID = Order_t.OrderID
AND OrderLine_T.ProductID = Product_t.ProductID
AND ProductDescription = 'Computer Desk'
);
NOT EXISTS: Returns true if the subquery returns an empty set (no rows).
Page 34
Created by Turbolearn AI
Use EXISTS when you only need to check if the subquery returns a non-empty
set.
Use IN when you need to know what values are in the set.
IN and NOT IN return a set of values from only one column, which can then be
compared to one column in the outer query.
EXISTS and NOT EXISTS return only true or false values based on whether
there are any rows in the answer table of the inner query.
Example: Find the order IDs for all orders that have included furniture finished in
Natural Ash.
Correlated Subqueries
Correlated subqueries use the result of the outer query to determine the processing
of the inner query. The inner query must be computed for each outer row.
Example: List the details about the product with the highest standard price.
The word ALL, which must follow a comparison operator, means "return TRUE if the
comparison is TRUE for ALL of the values in the column that the subquery returns."
Page 35
Created by Turbolearn AI
Example: Show the product description, product standard price, and overall average
standard price for all products that have a standard price higher than the average.
Union Operator
The UNION clause combines the output from multiple queries into a single result
table. Each query must output the same number of columns, and they must be of
compatible data types.
Example: Determine the customer(s) who purchased the largest and smallest
quantity of any Pine Valley product in a given line item.
Page 36
Created by Turbolearn AI
SELECT
C1.CustomerID,
CustomerName,
OrderedQuantity,
'Largest Quantity' AS Quantity
FROM
Customer_t C1,
Order_t O1,
OrderLine_t Q1
WHERE
C1.CustomerID = O1.CustomerID
AND O1.OrderID = Q1.OrderID
AND OrderedQuantity = (SELECT MAX(OrderedQuantity) FROM OrderLine_t)
UNION
SELECT
C1.CustomerID,
CustomerName,
OrderedQuantity,
'Smallest Quantity' AS Quantity
FROM
Customer_t C1,
Order_t O1,
OrderLine_t Q1
WHERE
C1.CustomerID = O1.CustomerID
AND O1.OrderID = Q1.OrderID
AND OrderedQuantity = (SELECT MIN(OrderedQuantity) FROM OrderLine_t)
ORDER BY 3;
MINUS: The MINUS operator takes the distinct rows of one query and returns the
rows that do not appear in a second result set.
Conditional Expressions
Page 37
Created by Turbolearn AI
IF-THEN-ELSE
CASE Keyword
Example:
SELECT
CASE
WHEN ProductLineID = 1 THEN ProductDescription
ELSE '###'
END AS ProductDescription
FROM
Product_t;
Triggers
A trigger is a named set of SQL statements that are triggered automatically when a
data modification (INSERT, UPDATE, DELETE) occurs or if certain data definitions are
encountered.
A trigger has three parts: the event, the condition, and the action.
use pinevalley;
CREATE TRIGGER StandardPriceUpdate
AFTER UPDATE ON Product_T
FOR EACH ROW
INSERT INTO PriceUpdates_T
VALUES (NEW.ProductID, NEW.ProductDescription, curdate(), NEW.ProductStand
Page 38
Created by Turbolearn AI
show triggers;
After running the above command, check the data in the PriceUpdates_T table:
A procedure may have input parameters, output parameters, and parameters that are
both input and output parameters.
Example: The following procedure performs three tasks: inserts a new field in
Product_T table named "SalePrice", updates SalePrice for ProductStandardPrice >=
400, and updates SalePrice for ProductStandardPrice < 400.
Page 39
Created by Turbolearn AI
call ProductLineSale();
call get_Records(2)
Page 40
Created by Turbolearn AI
The following stored procedure takes as input a single parameter and outputs result
into a single parameter. For the output parameter, we use the OUT keyword.
Example Usage:
CALL get_count(3,@outnum);
select @outnum;
The above procedure is returning count of records into outnum, and only those
records’ count is returned whose productid is greater than 3.
Example Usage:
Page 41
Created by Turbolearn AI
Here, the above procedure is returning values of product description and product
standard price for a provided productid=3.
The following function takes one value as input and returns a single value.
Example Usage:
select my_function(3);
Steps:
Page 42
Created by Turbolearn AI
Example: index.php
<html>
<body>
<table border="1">
<tr>
<td><a href="index.php">Home</a></td>
<td><a href="selectdata.php"> Show Record </a></td>
<td><a href="updatedata.php"> Update Data</a></td>
</tr>
</table>
<br>
<br>
<h6> THIS IS HOME PAGE </h6>
</body>
</html>
Example: selectdata.php
Page 43
Created by Turbolearn AI
<html>
<head>
<title> This is data selection page </title>
</head>
<body>
<table border="1">
<tr>
<td><a href="index.php">Home</a></td>
<td><a href="selectdata.php"> Show Record </a></td>
<td><a href="updatedata.php"> Update Data</a></td>
</tr>
</table>
<?php
$servername = "localhost";
$username = "root";
$password = "ciit"; // set this field "" (empty quotes) if you have not se
$dbname = "pinevalley";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $p
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection successful";
?>
<table border="1">
<th>ProductID</th>
<th>ProductLineID</th>
<th>ProductDescription</th>
<th>ProductFinish</th>
<th>ProductStandardPrice</th>
<?php
foreach($conn->query('SELECT * FROM product_t') as $row) {
?>
<tr>
<td><?php echo $row[0]; ?></td>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
<td><?php echo $row[3]; ?></td>
<td><?php echo $row[4]; ?></td>
</tr>
<?php } ?>
</table>
<?php
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
</body>
</html>
Page 44
Created by Turbolearn AI
Example: updatedata.php
Page 45
Created by Turbolearn AI
<html>
<head>
</head>
<body>
<table border="1">
<tr>
<td><a href="index.php">Home</a></td>
<td><a href="selectdata.php"> Show Record </a></td>
<td><a href="updatedata.php"> Update Data</a></td>
</tr>
</table>
<?php
$servername = "localhost";
$username = "root";
$password = "ciit";
$dbname = "pinevalley";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $p
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection successful";
if( isset($_POST['btn']) ) {
$txt1 = $_POST['txt1'];
$txt2 = $_POST['txt2'];
$txt3 = $_POST['txt3'];
$txt4 = $_POST['txt4'];
$txt5 = $_POST['txt5'];
Page 46
Created by Turbolearn AI
</tr>
<tr>
<td>ProductFinish</td>
<td><input id="txt4" name="txt4" type="text" /></td>
</tr>
<tr>
<td>ProductStandardPrice</td>
<td><input id="txt5" name="txt5" type="text" /></td>
</tr>
<tr>
<td>Save Record</td>
<td><input id="btn" name="btn" type="submit" value="Save Record" /></t
</tr>
</table>
</form>
</body>
</html>
http://localhost/myproject/index.php
http://localhost:8080/myproject/index.php
To avoid repeating data connection code, put it in one file (e.g., "opendb.php"):
<?php
$servername = "localhost";
$username = "root";
$password = "ciit"; // set this field "" (empty quotes) if you have not se
$dbname = "pinevalley";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $p
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection successful";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
?>
Page 47
Created by Turbolearn AI
2. Create a table in the database with matching columns to the CSV file.
use test;
create table Categories(
Category_ID text,
Category_Type text,
Business_Title text,
Business_Description text,
Size text,
Tel text,
Email text,
City text,
Address text,
Google_Map_URL text,
Entered_by_ID text,
Entered_By_Name text
);
3. Open the command prompt window, navigate to the "bin" directory of your
MySQL in either wamp or xampp server. Example:
C:\\Users\\osmank> A:
A:\\> CD wamp\\bin\\mysql\\mysql5.6.17\\bin
A:\\ wamp\\bin\\mysql\\mysql5.6.17\\bin>mysql mysql>
4. Write the following command. Change the red colored path below to the exact
path of your CSV file.
Page 48
Created by Turbolearn AI
truncate Categories;
LOAD DATA LOCAL INFILE 'C:\\\\Users\\\\TEMP\\\\Downloads\\\\FA14-BSE-006f.
INTO TABLE exel
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\\r\\n'
IGNORE 1 LINES;
Example:
To import a database:
Then,
/ The below command is used to import a .sql database file in mysql. First create a
database named: test using command: create schema test; Then write the below
command */
Page 49
Created by Turbolearn AI
SQL Statements
Creating Tables
Page 50
Created by Turbolearn AI
Customer_T Table
Territory_T Table
DoesBusinessIn_T Table
Employee_T Table
Page 51
Created by Turbolearn AI
Skill_T Table
EmployeeSkills_T Table
Order_T Table
WorkCenter_T Table
Page 52
Created by Turbolearn AI
ProductLine_T Table
Product_T Table
ProducedIn_T Table
OrderLine_T Table
Page 53
Created by Turbolearn AI
RawMaterial_T Table
Salesperson_T Table
Vendor_T Table
Page 54
Created by Turbolearn AI
Supplies_T Table
Uses_T Table
WorksIn_T Table
Page 55
Created by Turbolearn AI
Deleting Data
Deleting data from tables:
Inserting Data
Page 56
Created by Turbolearn AI
Customer_T Table
Territory_T Table
DoesBusinessIn_T Table
Employee_T Table
Page 57
Created by Turbolearn AI
Skill_T Table
EmployeeSkills_T Table
Order_T Table
ProductLine_T Table
Page 58
Created by Turbolearn AI
Product_T Table
OrderLine_T Table
Salesperson Table
WorkCenter_T Table
Committing Transactions
Page 59
Created by Turbolearn AI
COMMIT;
Page 60