Database Lab Manual
Database Lab Manual
(Database Systems)
Contents
LAB 01—Creating Configuring the database................................................................................................5
Configuring the environment..................................................................................................................6
Show existing databases in mysql............................................................................................................8
Show tables of a database “pinevalley”....................................................................................................8
Show data of a table customer_t.............................................................................................................8
LAB 02—update database structure..........................................................................................................10
Command to show the tables in a database..........................................................................................11
Retrieve System Time............................................................................................................................11
Add Two Number...................................................................................................................................11
CREATE NEW TABLE...............................................................................................................................11
Adding/Dropping Primary Key...............................................................................................................11
Creating table and defining Primary Key...............................................................................................12
Adding Column and Drop Column from Table.......................................................................................12
LAB 03—Change table structure/data.......................................................................................................13
Renaming Column in Table....................................................................................................................14
Setting Default Value for a Column.......................................................................................................14
Drop Table.............................................................................................................................................14
1
Insert data in table................................................................................................................................14
Insert multiple rows in table using single insert query..........................................................................14
Delete a single from table whose ID does not exist in table:.................................................................15
Delete a single row from table:.............................................................................................................15
Delete all rows from table.....................................................................................................................15
LAB 04—data copying/deletion.................................................................................................................16
Transfer/Copy Data from table1 to table2 with same table structure (SELECT INSERT QUERY)............17
Update single column single row in a table...........................................................................................17
Update multiple columns in a single rows in a table.............................................................................17
Update multiple columns in multiple rows in a table:...........................................................................17
UPDATE a row in table:..........................................................................................................................18
LAB 05—Auto-increment primary key.......................................................................................................19
Creating an AUTO INCREMENT PRIMARY KEY:......................................................................................20
Start Auto Increment with user specified value....................................................................................20
LAB 06—database indexes........................................................................................................................22
Creating Indexes....................................................................................................................................23
Drop Indexes..........................................................................................................................................24
LAB 07—create index on foreign keys.......................................................................................................25
Creating index on foreign key................................................................................................................26
LAB 08—select clause in detail..................................................................................................................27
Clauses of the SELECT Statement..........................................................................................................28
Two Special Keywords used in SELECT...................................................................................................28
LAB 09—Creating Alias in database...........................................................................................................30
Using Alias in SELECT Statement............................................................................................................31
LAB 10—sorting the data...........................................................................................................................32
Rearranging column Order in SELECT Query.........................................................................................33
LAB 11—using expressions and functions.................................................................................................34
Using Expressions:.................................................................................................................................35
Using Functions:....................................................................................................................................35
LAB 12—built-in functions.........................................................................................................................37
COUNT : Returns single row..................................................................................................................38
Difference between COUNT(*) and COUNT(ColumnName)..................................................................38
2
LAB 13—NULL values.................................................................................................................................40
Using Comparison Operators.................................................................................................................41
Using NULL Values.................................................................................................................................41
LAB 14—logical operators.........................................................................................................................42
Using Boolean Operators (Logical Operators):......................................................................................43
Using Ranges for Qualification...............................................................................................................43
Using DISTINCT values...........................................................................................................................44
LAB 15—understanding in and not in........................................................................................................45
Using IN and NOT IN Lists:.....................................................................................................................46
Sorting Results: The ORDER BY Clause..................................................................................................46
LAB 16—the use of “limit” operator............................................................................................................47
Using LIMIT............................................................................................................................................48
LAB 17—Group by and having clause........................................................................................................49
Categorizing Results: The GROUP BY Clause:.........................................................................................50
Qualify Results by Categories:...............................................................................................................50
LAB 18—defining views.............................................................................................................................52
Using and Defining Views:.....................................................................................................................53
LAB 19—queries involving multiple tables................................................................................................54
Processing Multiple Tables....................................................................................................................55
LAB 20—different types of joins................................................................................................................57
Outer Join..............................................................................................................................................58
Left OUTER Join.....................................................................................................................................58
LAB 21—Self join.......................................................................................................................................60
Sample join Involving four tables:.........................................................................................................61
Self Join..................................................................................................................................................61
LAB 22—Subqueries..................................................................................................................................63
Subqueries.............................................................................................................................................64
LAB 23—in, not in, exists, not exists..........................................................................................................66
Using the NOT IN qualifier:....................................................................................................................67
Using EXISTS and NOT EXISTS:...............................................................................................................67
EXISTS versus IN and NOT EXISTS versus NOT IN...................................................................................67
LAB 24—derived tables and sub-queries...................................................................................................69
3
Correlated Subqueries...........................................................................................................................70
Using Derived Tables.............................................................................................................................70
LAB 25—union operator & type conversion..............................................................................................71
Union Operator.....................................................................................................................................72
Data Type Conversion............................................................................................................................72
LAB 26—conditional expression and trigger..............................................................................................73
Conditional Expressions.........................................................................................................................74
Triggers..................................................................................................................................................74
LAB 27—introduction to stored procedures..............................................................................................77
Stored Procedures:................................................................................................................................78
LAB 28—stored procedure – single input..................................................................................................79
STORED PROCEDURE WITH A SINGLE INPUT PARAMETER....................................................................80
LAB 29—stored procedures – input/output..............................................................................................81
STORED PROCEDURE WITH A SINGLE INPUT and A SINGLE OUTPUT PARAMETER................................82
LAB 30—stored procedure returning values.............................................................................................83
STORED PROCEDURE WITH A SINGLE INPUT PARAMETER and TWO OUTPUT PARAMETERS...............84
LAB 31—using mysql functions..................................................................................................................85
MySQL FUNCTIONS................................................................................................................................86
LAB 32—Connecting mysql with php.........................................................................................................87
CONNECTING PHP with MySQL.............................................................................................................88
How to import an excel sheet into database table..............................................................................100
How to export/import a database.......................................................................................................101
How to import a group of CSV files into database using php script.....................................................102
APPENDIX-A.............................................................................................................................................104
4
LAB 01—CREATING CONFIGURING THE DATABASE
Objectives:
The objective of this lab is to make students learn how to show existing
databases, how to create a new database and populate the database
with data, and run simple select queries.
5
HOW to CONNECT MySQL Workbench with MySQL
1) Make sure your MySQL is already running (MySQL is highlighted green in xamp control panel)
2) Open MySQLWorkbench folder and click on blue colored MySQLWorkbench.exe file
3) If there is no connection shown, then click on Click on “plus shaped” icon to create new
connection.
4) Input a connection name “mycon”
5) User name should be ‘root’
6) Password should be blank and click save, click test to see the response. If 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
The following steps needs to be performed if pinevalley database is not present or is corrupt
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;
3) If “pinevalley” is not present in the list of databases, in the new query tab, write following query:
4) If your pinevalley database is already present but is corrupt (missing some tables), then write
the following query to delete an existing copy, if any, of pinevalley database
5) Open file “pinevalley.sql” from unzipped database_lab_manual_dr.osman folder. The script can
also be copied / pasted from Appendix A. However, just make sure you remove page numbers
copied from word document in the SQL editor window.
6) Right click on “pinevalley.sql” and open in “wordpad” or preferably in notepad++. (If you don’t
have notepad++ search in google, download, and install in your system).
7) Copy the SQL syntax, and paste in a new query tab in mysqlworkbench
8) 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.
6
Show existing databases in mysql
show databases;
NOTE: Here “*” means , retrieve “all columns” from the table.
use pinevalley;
select customername from customer_t;
To show data from customer table in following order: customercity, customername, customerid:
use pinevalley;
select CustomerName,CustomerCity,CustomerID from customer_t from customer_t;
use pinevalley;
select * from customer_t
where customerid=5;
use pinevalley;
Select * from customer_t
where customerid>=5;
7
To show record of customers whose id is between 5 and 8
use pinevalley;
select * from customer_t
where customerid >=5 and customerid <=8;
use pinevalley;
select * from customer_t
where customerid >=5 and customerid <=8 and customerstate=’FL’;
use pinevalley;
select customerid, customername, customeraddress from customer_t
where customercity=’Ogden’
use pinevalley;
select “Pakistan”;
use pinevalley;
select “Pakistan” as country;
8
LAB 02—UPDATE DATABASE STRUCTURE
Objectives:
The objective of this lab is to familiarize students with basic select
statement, how to add/drop a primary key, and how to add/drop a
column from table.
9
Command to show the tables in a database
Use Pinevalley;
SHOW TABLES;
Or
DESCRIBE temp;
10
ALTER TABLE temp DROP PRIMARY KEY;
11
LAB 03—CHANGE TABLE STRUCTURE/DATA
Objectives:
The students will learn how to rename a column in table, how to set
default value for a column, how to drop a table, how to empty table
from data, and how to delete a row from table.
12
Renaming Column in Table
ALTER TABLE temp
CHANGE COLUMN address
area VARCHAR(10);
Drop Table
drop table temp;
13
Delete a single from table whose ID does not exist in
table:
delete from temp where id =100;
‘Where’ expression can have either column of the table, but PRIMARY key column is used to
avoid unwanted deletion of data.
e.g.
OR
14
LAB 04—DATA COPYING/DELETION
Objectives:
The objective of this lab is to make students learn how to transfer/copy
data from one table to another, how to delete a data from table based
on selected criteria, and how to update a specific row in table.
15
Transfer/Copy Data from table1 to table2 with same
table structure (SELECT INSERT QUERY)
Populating a table (CHILD) by using subset of another table (PARENT) with the same structure.
16
UPDATE a row in table:
First you need to confirm the row you want to update, should exist in the table.
e.g. you want to update the row with ID 7. Check if it exists.
If this returns a row. Then the row exists, and you can run the UPDATE query.
This will update the value of the ProductStandardPrice from 800 to 775.
17
LAB 05—AUTO-INCREMENT PRIMARY KEY
Objectives:
The students will learn how to create an auto-increment primary key.
How to insert rows using insert query when auto-increment primary
key is defined, and how to initialize the auto-increment primary key for
a specified value.
18
Creating an AUTO INCREMENT PRIMARY KEY:
This will insert two rows in the table PERSONS, Note that we gave ‘ID’ for the first row i.e. 11
and we did not give any ID for the second row. And 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.
19
After the table is altered for its auto increment value, Insert another record in the table.
20
LAB 06—DATABASE INDEXES
Objectives:
Students will learn the benefits of creating indexes on database tables,
how to create indexes on table fields, and how to drop indexes.
21
Creating Indexes :
Indexes are created in RDBMS to provide rapid and sequential access to base table data.
Indexes are usually be created both for primary and secondary keys and both single and
concatenated (multiple column keys).
Example:
DESCRIBE CUSTOMER_T;
DESCRIBE CUSTOMER_T;
22
Drop Indexes :
To remove index on the customer name in the table.
23
LAB 07—CREATE INDEX ON FOREIGN KEYS
Objectives:
Students will understand the relation of indexes with a table’s foreign
keys. Students will learn how to create indexes on foreign key, and how
to drop a foreign key index
24
Creating index on foreign key :
Create two tables:
Even after dropping the foreign key, the index still resides and has to be dropped manually, by
CONCLUSION: When we create a foreign key in a table, the index is made automatically on the
foreign key attribute. When we drop a foreign key, the index does not automatically delete, and
we have to delete the index manually.
25
LAB 08—SELECT CLAUSE IN DETAIL
Objectives:
The objective of this lab is to teach student various clauses of SELECT
statement. Students will learn about the two special keywords used in
select clause.
26
Clauses of the SELECT Statement:
SELECT: lists the columns (including expressions involving columns i.e. age+10) from base
tables, derived tables, or views to be projected into the table that will be the result of
the command.
FROM: Identifies the tables, derived tables, or views from which columns will be chosen to appear in
the result table and include the tables, derived tables, or views needed to join tables to process the
query.
WHERE: Includes the conditions (Boolean expression) for row selection within the items in the FROM
clause and the conditions between tables, derived tables, or views for joining.
Example:
Which products have a standard price of less than $275.
1. DISTINCT
2. *
DISTINCT: If the user does not wish to see duplicate rows in the result.
Example:
And count how many rows are returned. (8 rows are returned).
Next, run query:
27
SELECT DISTINCT PRODUCTDESCRIPTION FROM PRODUCT_T;
Duplicate rows are removed from the results (that was ‘Computer Desk’).
28
LAB 09—CREATING ALIAS IN DATABASE
Objectives:
Student will learn how to create a table alias, and a table’s field alias.
29
Using Alias in SELECT Statement:
Advantage: Using alias make the column names more readable in a select query. Moreover, we
can rename a table column name, or a table name, to a new name of our choice in the select
query. However, using alias does not change anything in actual table’s structure, it is just used
for data reading/presentation from database.
This returns the columns with their alias names, i.e. Name for CusomterName and Address for
CustmerAddress.
30
LAB 10—SORTING THE DATA
Objectives:
Students will learn how to sort table data using ORDER BY clause.
31
Rearranging column Order in SELECT Query:
While creating new table, it is not necessary to create columns in a table in a specific order.
Because, we can select data from table in any order we like, by placing the columns in different
orders in select query.
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 table was created).
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.
32
LAB 11—USING EXPRESSIONS AND FUNCTIONS
Objectives:
Students will learn how to use expressions and functions in select
queries.
33
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.
Using Functions:
Mathematical: MIN, MAX, COUNT, SUM, ROUND, MOD, AVG
34
SUBSTR(): To isolate character. Used to find a substring in a given string.
COALESCE() : Finding the first positions of not null values in a list of columns
MONTH(): Given date as input, this function returns MONTH on that date
YEAR(): Given date as input, this function returns YEAR on that 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 MySQL website.
Query: What is the average standard price for all products in inventory?
35
LAB 12—BUILT-IN FUNCTIONS
Objectives:
Students will understand the use of some of the built-in functions, such
as COUNT, MIN, and MAX.
36
COUNT : Returns single row
Query: How many different items were ordered on order number 1001, and what are they?
This query should return error, because count returns only one row , though we are selecting multiple
rows for productID. It will return error in SQL Server or Oracle, but for MySQL query returns the 1st
productID along with 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.
37
AS PriceAvg 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 numeric value then the numeric value of the string will be used for comparison
(while to rest of the string will be truncated). If instead, we use MAX function, it will give
preference to string value, and string starting with highest alphabet position will be return
(ignoring the string starting with numeric value)
38
LAB 13—NULL VALUES
Objectives:
Students will learn the work of various comparison operators, and the
use of NULL keyword.
39
Using Comparison Operators
Query: Which orders have been placed since 10/24/2010.
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 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 value*/
/*below query returns all rows for which CustomerPostalCode does not contains NULL
value*/
40
LAB 14—LOGICAL OPERATORS
Objectives:
Students will learn different types of logical operators, and how they
are used to filter data in select queries. The use of DISTINCT operator
will be also be discussed.
41
Using Boolean Operators (Logical Operators):
- AND: Joins two or more conditions and return 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 statements, 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 wild card that anything can appear before the string, but should
end with the string. Vice versa % after the string acts as a wild card that anything can appear
after the string, but should start with the string. If % is added before and after the string, than
the string can appear as a sub-string in a string, either in start, mid, or end.
42
SELECT ProductDescription, ProductFinish, ProductStandardPrice FROM PRODUCT_T WHERE
ProductStandardPrice >= 200.00 AND ProductStandardPrice <= 300.00 ;
Query: Which product in the product table has a standard price between $200 and $300.
If we are interested only to see which order IDs are appearing rather than how many times they
are appearing we will use DISTINCT.
43
LAB 15—UNDERSTANDING IN AND NOT IN
Objectives:
The objective of this lab is to make students understand the two very
important keywords in SQL that are IN and NOT IN, and how to sort
data using ORDER BY clause.
44
Using IN and NOT IN Lists:
To match a list of values.
GROUP BY: Groups rows in an intermediate results table were the values in those rows where
same for one or more columns.
HAVING: Can only be used following a GROUP BY and acts as a secondary WHERE clause,
returning only those groups that meet a specified condition.
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 state.
45
LAB 16—THE USE OF “LIMIT” OPERATOR
Objectives:
The students will understand the benefit and use of LIMIT operator.
46
Using LIMIT :
LIMIT is used to limit to limit/constraint the number of results returned, or to give a range of
rows to return.
LIMIT 2, 3: will skip first 2 rows, and return the next 3 rows.
This will skip the first 3 rows and return next 5 rows.
47
LAB 17—GROUP BY AND HAVING CLAUSE
Objectives:
In this lab, students will learn the use of GROUP BY and HAVING clause.
48
Categorizing Results: The GROUP BY Clause:
GROUP BY is useful when paired with aggregate functions such as SUM or COUNT. GROUP BY
divides a table into subsets (by group); then aggregate function can be used to provide
summary information for that group.
The single value returned by the previous aggregate function examples is called scalar
aggregate.
When aggregate functions are used in a GROUP BY clause and several values are returned, they
are called vector aggregate.
The next query is ordering results by first preference to CustomerState, and second preference
to CustomerCity
It is also possible to nest groups within groups; the same logic is used when sorting multiple
columns.
Query: Count the number of customers with addresses in each city to which we ship. List the
cities by State.
WHERE is cannot be used with GROUP BY. HAVING is used with GROUP BY.
49
Query: Find only states with more than one customer.
To include more than one condition in the HAVING Clause, use AND, OR, and NOT.
Query: List, in alphabetical order, the product finish and the average standard price for each
finish for selected finishes having an average standard price less than 750.
( 'Cherry', 'Natural Ash', 'Natural Maple', 'White Ash') GROUP BY ProductFinish HAVING
AVG(ProductStandardPrice) <750 ORDER BY ProductFinish;
50
LAB 18—DEFINING VIEWS
Objectives:
The students will understand the basics of views and how to define
views.
51
Using and Defining Views:
The purpose of a view is to simplify query commands, but a view may also improve data security
and significantly enhance programming consistency and productivity for a database.
Query: What are the data elements necessary to create an invoice for a customer? Save this
query as a view named Invoice_v.
Query: What are the data elements necessary to create an invoice for number 1004?
Query: What is the total values of orders placed for each furniture product ?
Query: List all furniture products that have ever had a standard price over $300.
52
LAB 19—QUERIES INVOLVING MULTIPLE TABLES
Objectives:
This lab will teach the students how to write queries on multiple tables,
how to use INNER JOIN.
53
Processing Multiple Tables:
Equi-Join: A join in which the joining condition is based on equality between the values in the
common columns. Common columns appear (redundantly) in the result table.
Query: Suppose we have three tables as indicated below retrieve the values of columns
t1name, t2name, t3name
TABLE1
T1ID T1Name
TABLE2
TABLE3
Solution: Since the three tables are joined through primary key/foreign key relationships, we
need to use the equi-join in the select query:
select t1name, t2name, t3name from TABLE1, TABLE2, TABLE3 where TABLE1.T1ID=
TABLE2.T1ID and TABLE2.T2ID= TABLE3.T2ID
Query: What are the customer IDs and Names of all customers along with the order id for all
the orders that are placed?
54
INNER JOIN….ON are used to establish an equi-join in the FROM clause.
Query: What are the Customer ID and names of all customers, along with the Order IDs for all
the orders they have placed?
FROM customer_t
Customer_t.customerid = Order_T.customerid
ORDER BY OrderID;
55
LAB 20—DIFFERENT TYPES OF JOINS
Objectives:
Students will learn how to use different types of joins, left outer join,
right outer join
56
Outer Join:
A join in which rows that do not have matching value in common columns are nevertheless
included in the results table. Null values appear in columns where there is no match between
tables.
Example use: In Order_T table come customers’ orders are appearing. There are some
customers in Customer_T who have not placed any order. Due to that qui-join shown previously
do not include all the customer shown in Customer_T. The organization may be very interested
in identifying those customers who have not placed orders. It might want to contact them to
encourage new orders, or it might be interested in analyzing the customers to know why they
are not ordering.
Customer_t.CustomerID = Order_t.customerid;
Query: List customer name , identification number, and order number for all orders listed in the
order table. Include the order number, even if there is no customer name, and identification
number available.
Customer_t.CustomerID = Order_t.CustomerID;
57
This query will also return the rows in which the foreign key column does not exist i.e. NULL, for
any row
58
LAB 21—SELF JOIN
Objectives:
The objective of this lab is to teach how to use SELF JOIN, and running
query involving 4 tables.
59
Sample join Involving four tables:
Query: Assemble all information necessary to create an invoice for order number 1006.
WHERE
Order_t.OrderID = 1006;
Self Join:
There are times when a join requires matching rows in a table with other rows in that same
table – that is joining a table with itself.
Query: What are the employee ID and name of each employee, and the name of his/her
supervisor (label the name of supervisor’s name with manager)?
SELECT
E.EmployeeID,
E.EmployeeName,
Employee_T E, Employee_T M
60
WHERE
E.EmployeeSupervisor = M.EmployeeID;
61
LAB 22—SUBQUERIES
Objectives:
The purpose of this lab is to familiarize students with how to call a
query within other query to make a sub-query, and how to write
efficient sub-queries.
62
Subqueries
The preceding SQL examples illustrate one of the two basic approaches for joining two tables:
the joining technique. SQL also provides the subquery technique, which involves 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. Such queries are referred to as subqueries or nested subqueries. Subqueries
can be nested multiple times. Subqueries are prime examples of why SQL is a set-oriented
language.
Query: (Not Subquery) What are the name and address of the customer who placed order
number 1008?
Query (Sub-query): What are the name and address of the customer who placed order number
1008?
FROM Customer_T
WHERE Customer_T.CustomerID =
(SELECT Order_T.CustomerID
FROM Order_T
Query: What are the names of customers who have placed orders?
63
SELECT CustomerName
FROM Customer_T
WHERE CustomerID IN
FROM Order_T);
64
LAB 23—IN, NOT IN, EXISTS, NOT EXISTS
Objectives:
This lab is intended to introduce students with some powerful
keywords of SQL, and how to make their good use to reduce query
size.
65
Using the NOT IN qualifier:
Query: Which customers have not placed any orders for computer desks?
SELECT CustomerName
OrderLine_t.OrderID = Order_t.OrderID
NOT EXISTS: will take a value of true if no rows are returned and false if one or more rows are
returned
IN and NOT IN return a set of values from only one column which can be then compared to one
column in the outer query.
EXISTS and NOT EXISTS return only true or false value depending on whether there are any
rows in the answer table of the inner query or sub query.
66
Query: What are the order IDs for all orders that have included furniture finished in Naturals
ash?
WHERE EXISTS
);
67
LAB 24—DERIVED TABLES AND SUB-QUERIES
Objectives:
The purpose of this lab is to familiarize students with queries involving
derived tables, and the correlated sub queries.
68
Correlated Subqueries:
Correlated sub queries use the result of outer query to determine the processing of the inner
query. In this case, the inner query must be computed for each outer row.
Query: List the details about the product with the highest standard price;
FROM Product_t PA
(SELECT ProductStandardPrice
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.
Query: Show the product description , product standard price, and overall average standard
price for al products that have a standard price that is higher than average standard price.
FROM
69
LAB 25—UNION OPERATOR & TYPE CONVERSION
Objectives:
The purpose of this lab is to brief students about how to use the UNION
operator to join results from different queries, and how we can use
type conversion in MySQL.
70
Union Operator:
Combining Queries: The UNION clause is used to combine the output (i.e. union the set of
rows from multiple queries together into a single result table. To use the UNIION clause we
each query involved must output the same number of columns , and they must be of
compatible data types.
UNION
ORDER BY 3;
Query: The following query determines the customer(s) who has in a given line item purchases
the largest quantity of any Pine Valley product and the customer(s) who has in a given line item
purchased the smallest quantity and returns the results in the table.
INTERSECT: An INTERSECT is simply an inner join where we compare the tuples of one table
with those of the other, and select those that appear in both while weeding out duplicates.
MINUS: The MINUS operator takes the distinct rows of one query and returns the rows that do not appear
in a second result set.
71
LAB 26—CONDITIONAL EXPRESSION AND TRIGGER
Objectives:
This lab will introduce students with conditional expressions, as well as
how we can define and use triggers in MySQL.
72
Conditional Expressions:
IF-THEN-ELSE
CASE Keyword
Query:
SELECT
CASE
ELSE '###'
END AS ProductDescription
FROM Product_t;
Triggers
A named set of SQL statements that are triggered automatically when a data modification (i.e.,
INSERT, UPDATE, DELETE) occurs or if certain data definitions are encountered. If a condition
stated within a trigger is met, then a prescribed action is taken. Triggers are used when you
need to perform, under specified conditions, a certain action as the result of some database
event (e.g., the execution of a DML statement such as INSERT, UPDATE, or DELETE or the DDL
statement ALTER TABLE). Thus, a trigger has three parts—the event, the condition, and the
action—and these parts are reflected in the coding structure for triggers.
show triggers;
use pinevalley;
73
create table PriceUpdates_T
ProductID int,
ProductDescription varchar(50),
UpdateDate DATE,
NewPrice decimal(6,2)
Now we write the trigger code as follows, that will create a trigger with name:
StandardPriceUpdate
use pinevalley;
show triggers;
Now the following command will automatically execute (trigger) the trigger
“StandardPriceUpdate”
74
After the above command is run, check the data in PriceUpdates_T table
How it happened?
The trigger code “StandardPriceUpdate” states that whenever there is an update in Product_T
table, the updated row(s) fields will be automatically inserted into the PriceUpdates_T as new
rows. That’s why we are seeing new row inserted into PriceUpdates_T table. FOR EACH ROW
means that, the new row in PriceUpdates_T will be inserted for each updated row, e.g., the
following query updates two rows in the product_t table.
75
LAB 27—INTRODUCTION TO STORED PROCEDURES
Objectives:
This lab introduces the stored procedures and discuss several examples
of how effectively can we use stored procedures in MySQL.
76
Stored Procedures:
A collection of procedural and SQL statements that are assigned a unique name within the schema
and stored in the database. A procedure may have input parameters, output parameters, and
parameters that are both input and output parameters.
BEGIN
UPDATE Product_T
UPDATE Product_T
END
call ProductLineSale();
77
LAB 28—STORED PROCEDURE – SINGLE INPUT
Objectives:
The purpose of this lab is to make students learn how we can pass a
single argument to stored procedures.
78
STORED PROCEDURE WITH A SINGLE INPUT
PARAMETER
The following stored procedure takes a single int value as input and returns a limited set of records
based on the provided input parameter.
BEGIN
END
Use the above procedure, the following code will return just 2 records
call get_Records(2)
79
LAB 29—STORED PROCEDURES – INPUT/OUTPUT
Objectives:
In this lab students will lab, how can pass single input and output single
value from stored procedures.
80
STORED PROCEDURE WITH A SINGLE INPUT and A
SINGLE OUTPUT PARAMETER
The following stored procedure takes as input a single parameter and outputs result into a
single parameter. For the output parameter, we use OUT keyword
BEGIN
SELECT count(productid) into outnum from product_t where productid > mynum;
END
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.
81
LAB 30—STORED PROCEDURE RETURNING VALUES
Objectives:
Students will learn how we can define and use a stored procedure that
is able to return multiple values, provided with an input value.
82
STORED PROCEDURE WITH A SINGLE INPUT
PARAMETER and TWO OUTPUT PARAMETERS
CREATE PROCEDURE `get_multiple_values`(prodid INT, OUT proddesc VARCHAR(50), OUT price
decimal(6,2))
BEGIN
END
Here, the above procedure is returning values of product description and product standard
price for a provided productid=3.
83
LAB 31—USING MYSQL FUNCTIONS
Objectives:
In this lab, students will learn how to define, and use functions in
MySQL, and how to pass arguments and return values from functions.
84
MySQL FUNCTIONS
A function returns one value and has only input parameters. You have already seen the many
built-in functions included in SQL, such as MAX, MIN, CEILING, FLOOR, SQRT, etc.
The following function returns takes one value as input and returns a single value.
RETURNS INTEGER
BEGIN
RETURN temp;
END
select my_function(3);
85
LAB 32—CONNECTING MYSQL WITH PHP
Objectives:
Purpose of this lab is to create a small application connecting PHP with
MySQL. Creating PHP forms to insert data into database, delete data,
update data, and select data from database.
86
CONNECTING PHP with MySQL
Make sure you have “pinevalley” database successfully configured in your MySQL server /
wamp.
Run wampserver, and make sure that phpmyadmin is opening and running fine. If not, there
might be some port issues, change port of apache server to 8080. Or quit skype and re-return
the wampserver, as skype uses the same port as wampserver.
Step-1: In “www” folder of your wampserver, create a new folder with name: “myproject”.
Step-2: Uncheck the following option from “Folder and Search” options of your PC “hide file
extensions for known file type”, and click on apply/ok.
Step-3: In “myproject” folder create three files, namely “index.php”, “selectdata.php”, and
“updatedata.php”.
index.php
<html>
<body>
<table border="1">
<tr>
<td><a href="index.php">Home</a></td>
</tr>
</table>
87
<br>
<br>
</body>
</html>
Make sure you correctly set values shown in red font below as per your system configuration.
(Means these values may be changed in your system.)
selectdata.php
<html>
</head>
<body>
<table border="1">
<tr>
<td><a href="index.php">Home</a></td>
</tr>
</table>
88
<?php
$servername = "localhost";
$username = "root";
$password = "ciit"; // set this field "" (empty quotes) if you have not set any password in mysql
$dbname = "pinevalley";
try {
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
<table border="1">
<th>ProductID</th>
<th> ProductLineID</th>
<th>ProductDescription </th>
<th>ProductFinish </th>
<th>ProductStandardPrice</th>
<?php
89
?>
<tr>
</tr>
<?php
?>
</table>
<?php
catch(PDOException $e)
$conn = null;
?>
90
</body>
</html>
updatedate.php
<html>
<head> </head>
<body>
<table border="1">
<tr>
<td><a href="index.php">Home</a></td>
</tr>
</table>
<?php
$servername = "localhost";
$username = "root";
$password = "ciit";
$dbname = "pinevalley";
91
try {
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if( isset($_POST['btn']) )
$txt1 = $_POST['txt1'];
$txt2 = $_POST['txt2'];
$txt3 = $_POST['txt3'];
$txt4 = $_POST['txt4'];
$txt5 = $_POST['txt5'];
//echo $txt1 . " " . $txt2 . " " . $txt3 . " " . $txt4 . " " . $txt5;
92
// use exec() because no results are returned
$conn->exec($sql);
catch(PDOException $e)
$conn = null;
?>
<table border="1">
<tr>
<td>ProductID</td>
93
<td><input id="txt1" name="txt1" type="text" /></td>
</tr>
<tr>
<td>ProductLineID</td>
</tr>
<tr>
<td>ProductDescription</td>
</tr>
<tr>
<td>ProductFinish</td>
</tr>
<tr>
<td>ProductStandardPrice</td>
</tr>
<tr>
94
<td>Save Record</td>
</tr>
</table>
</form>
</body>
</html>
http://localhost/myproject/index.php
http://localhost:8080/myproject/index.php
As a final note, instead of repeating the same data connection code in each file again and again,
you can put it in one file and call that file in your remaining files.
For example, create a new file named: “opendb.php”, and add following code in that:
opendb.php
<?php
$servername = "localhost";
$username = "root";
$password = "ciit"; // set this field "" (empty quotes) if you have not set any password in mysql
95
$dbname = "pinevalley";
try {
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
catch(PDOException $e)
?>
Now, as a sample code, you can re-write the selectdata.php file as:
selectdata.php
<html>
<head> </head>
<body>
96
<table border="1">
<tr>
<td><a href="index.php">Home</a></td>
</tr>
</table>
<table border="1">
<th>ProductID</th>
<th> ProductLineID</th>
<th>ProductDescription </th>
<th>ProductFinish </th>
<th>ProductStandardPrice</th>
<?php
try
97
?>
<tr>
</tr>
<?php
?>
</table>
<?php
catch(PDOException $e)
$conn = null;
?>
98
</body>
</html>
We can see, the database connection code is removed from above file, and we are just
including the file that is maintaining the database connectivity.
To store this excel sheet in database, we need to follow the following steps:
Step 1: In excel sheet, click on File, Save As, and select the option comma delimited CSV.
99
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
Step 3: Open command prompt window, and navigate to the “bin” directory of your mysql in either
wamp or xampp server. For example, on my PC, the “bin” directory is on the following path and I will use
the following procedure:
C:\Users\osmank> A:
A:\> CD wamp\bin\mysql\mysql5.6.17\bin
A:\ wamp\bin\mysql\mysql5.6.17\bin>mysql
mysql>
Step 4: Now, write the following command. You need to change the red colored path below to the exact
path of your CSV file.
truncate Categories;
LOAD DATA LOCAL INFILE 'C:\\Users\\TEMP\\Downloads\\FA14-BSE-006f.csv' INTO TABLE exel
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\
n' IGNORE 1 LINES;
If all steps are performed as indicated, you should see that the table “categories” is populated with the
new values.
C:\Users\osmank> A:
A:\> CD wamp\bin\mysql\mysql5.6.17\bin
A:\ wamp\bin\mysql\mysql5.6.17\bin>
100
To export database to a .sql file, write the below commands. Here, the red text at the left of greater
than sign indicates the name of database of which you want to take backup. And, the red text at the
right side of greater than sign indicates the name of the output .sql file and the path at which it is going
to be stored.
#Example:
A:\ wamp\bin\mysql\mysql5.6.17\bin>mysqldump --opt test > z:\\test.sql
A csv file is created by saving excel file as “comma delimited csv”. If you have a group of csv files of
exactly similar format/data and you want to import those into database, the following are the
guidelines. First you need to have a table in database that is having the exactly matching columns to the
csv file. Use the following php script to import the csv files. Change the red color text with the proper
configuration of your system. To execute the “import.php” file, you need to run the file in command
line. In command lines, navigate to the “bin” folder of your “php” and write command:
<?php
$servername = "localhost";
$username = "root";
$password = "ciit"; // set this field "" (empty quotes) if you have not set any password in mysql
$dbname = "test";
101
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach(glob($dir."*.*") as $v)
{
$query = "LOAD DATA INFILE '".$v."' INTO TABLE catdata FIELDS TERMINATED BY ',' OPTIONALLY
ENCLOSED BY '\"' LINES TERMINATED BY '\\r\\n' IGNORE 1 LINES;";
try
{
$conn -> query( $query);
echo $v . "... success!\n";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$conn = NULL;
?>
102
APPENDIX-A
/*
NOTE: If you are copy pasting the database script from below, make sure to remove the page numbers
from the pasted text. Page numbers are also copied along with the text and will create problems.
Moreover. Make sure the quotations are of command line syntax, not of word where they are a bit
tilted. E.g., “
*/
use pinevalley;
CREATE TABLE Customer_T
(CustomerID int NOT NULL,
CustomerName VARCHAR(25) NOT NULL,
CustomerAddress VARCHAR(30) ,
CustomerCity VARCHAR(20) ,
CustomerState CHAR(2) ,
CustomerPostalCode VARCHAR(10) ,
CONSTRAINT Customer_PK PRIMARY KEY (CustomerID));
103
EmployeeCity VARCHAR(20) ,
EmployeeState CHAR(2) ,
EmployeeZip VARCHAR(10) ,
EmployeeDateHired DATE ,
EmployeeSupervisor VARCHAR(10) ,
CONSTRAINT Employee_PK PRIMARY KEY (EmployeeID));
104
CREATE TABLE ProducedIn_T
(ProductID int NOT NULL,
WorkCenterID VARCHAR(12) NOT NULL,
CONSTRAINT ProducedIn_PK PRIMARY KEY (ProductID, WorkCenterID),
CONSTRAINT ProducedIn_FK1 FOREIGN KEY (ProductID) REFERENCES Product_T(ProductID),
CONSTRAINT ProducedIn_FK2 FOREIGN KEY (WorkCenterID) REFERENCES
WorkCenter_T(WorkCenterID));
105
SuppliesUnitPrice DECIMAL(6,2) ,
CONSTRAINT Supplies_PK PRIMARY KEY (VendorID, MaterialID),
CONSTRAINT Supplies_FK1 FOREIGN KEY (MaterialId) REFERENCES RawMaterial_T(MaterialID),
CONSTRAINT Supplies_FK2 FOREIGN KEY (VendorID) REFERENCES Vendor_T(VendorID));
106
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (3, 'Home Furnishings', '1900 Allard Ave.', 'Albany', 'NY', '12209-1125');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (4, 'Eastern Furniture', '1925 Beltline Rd.', 'Carteret', 'NJ', '07008-3188');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (5, 'Impressions', '5585 Westcott Ct.', 'Sacramento', 'CA', '94206-4056');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (6, 'Furniture Gallery', '325 Flatiron Dr.', 'Boulder', 'CO', '80514-4432');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (7, 'Period Furniture', '394 Rainbow Dr.', 'Seattle', 'WA', '97954-5589');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (8, 'California Classics', '816 Peach Rd.', 'Santa Clara', 'CA', '96915-7754');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (9, 'M and H Casual Furniture', '3709 First Street', 'Clearwater', 'FL', '34620-2314');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (10, 'Seminole Interiors', '2400 Rocky Point Dr.', 'Seminole', 'FL', '34646-4423');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (11, 'American Euro Lifestyles', '2424 Missouri Ave N.', 'Prospect Park', 'NJ', '07508-5621');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (12, 'Battle Creek Furniture', '345 Capitol Ave. SW', 'Battle Creek', 'MI', '49015-3401');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (13, 'Heritage Furnishings', '66789 College Ave.', 'Carlisle', 'PA', '17013-8834');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (14, 'Kaneohe Homes', '112 Kiowai St.', 'Kaneohe', 'HI', '96744-2537');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (15, 'Mountain Scenes', '4132 Main Street', 'Ogden', 'UT', '84403-4432');
107
INSERT INTO Territory_T (TerritoryID, TerritoryName)
VALUES (5, 'Central');
108
values ('555955585','Mary Smith','75 Jane Lane','Clearwater','FL','33879','2008-7-04','2008-7-
04','332445667');
109
VALUES (1006, '24/Oct/10', 2);
INSERT INTO Order_T (OrderID, OrderDate, CustomerID)
VALUES (1007, '27/Oct/10', 11);
INSERT INTO Order_T (OrderID, OrderDate, CustomerID)
VALUES (1008, '30/Oct/10', 12);
INSERT INTO Order_T (OrderID, OrderDate, CustomerID)
VALUES (1009, '05/Nov/10', 4);
INSERT INTO Order_T (OrderID, OrderDate, CustomerID)
VALUES (1010, '05/Nov/10', 1);
110
VALUES (1002, 3, 5);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1003, 3, 3);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1004, 6, 2);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1004, 8, 2);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1005, 4, 3);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1006, 4, 1);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1006, 5, 2);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1006, 7, 2);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1007, 1, 3);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1007, 2, 2);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1008, 3, 3);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1008, 8, 3);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1009, 4, 2);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1009, 7, 3);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1010, 8, 10);
111
INSERT INTO WorkCenter_T (WorkCenterID, WorkCenterLocation)
VALUES ('WR1', 'Warehouse and Receiving');
/*
INSERT INTO WorksIn_T (EmployeeID, WorkCenterID)
VALUES ('123-44-345', 'SM1');
INSERT INTO WorksIn_T (EmployeeID, WorkCenterID)
VALUES ('454-56-768', 'Tampa1');
*/
COMMIT;
112