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

Database Lab Manual

Uploaded by

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

Database Lab Manual

Uploaded by

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

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.

Configuring the environment


TASKS TO BE PERFORMED ONLY ONCE
HOW TO DOWNLOAD and INSTALL MySQL WORKBENCH

1) Click the following link:


https://dev.mysql.com/downloads/workbench
2) Select the window version 64 bit x86, zip archive.
3) Click on “Download” and save in C:\database
4) After download, right click the file and click on “Extract Here”.
5) The correct path of MySQLWorkbench is C:\ database\MySQL Workbench X.X.X CE (win64)
TASKS TO BE PERFORMED IN EVERY LAB
HOW TO SHOW FILE EXTENSION:

1) Open any folder


2) Click on top left “Organize”
3) Click on Folder and search options
4) Click on View tab
5) Uncheck option
“Hide file extension for known file types”

How TO CHANGE DOWNLOAD SETTINGS IN CHROME

1) Open chrome browser


2) Click on the three bars icon at the top right corner and click on Settings
3) In Search Settings text box, enter Download and at the bottom of the page, under downloads,
check the option: “Ask where to save each file before downloading”

RUNNING the MySQL Server

1) Click on windows Start button


2) Type xampp (of wamp if you have installed wamp in your laptop)
3) Click on Xamp Control Panel
4) Against MySQL option, click on Start button

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

Importing “pinevalley” database in MySQL

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:

CREATE SCHEMA PINEVALLEY

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

drop schema pinevalley;

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;

Show tables of a database “pinevalley”


use pinevalley;
show tables;

Show data of a table customer_t


use pinevalley;
select * from customer_t;

NOTE: Here “*” means , retrieve “all columns” from the table.

To show data of one column:

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;

To show the record for customerid=5

use pinevalley;
select * from customer_t
where customerid=5;

To show record of customers whose id is greater than or equal to 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;

To show record of customers whose id is between 5 and 8 and state is FL

use pinevalley;
select * from customer_t
where customerid >=5 and customerid <=8 and customerstate=’FL’;

To retrieve record of customer based on a given city name

use pinevalley;
select customerid, customername, customeraddress from customer_t
where customercity=’Ogden’

To output a plain string

use pinevalley;
select “Pakistan”;

To give a temporary column name (or alias) to the output data

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;

Retrieve System Time:


SELECT CURTIME();

Or

SELECT CURTIME() as mytime

Add Two Number:


SELECT 8+4;
Or
SELECT 8+4 as ans

CREATE NEW TABLE:

CREATE TABLE temp(


ID INT,
Name VARCHAR(10)
);

DESCRIBE temp;

Adding/Dropping Primary Key:


/*
NOTE: To add a primary key, the column/field to be set as primary key must not have any repeating
record. If there is any such record, first the repeating data should be changed/deleted.
*/

ALTER TABLE temp ADD CONSTRAINT pk_ID PRIMARY KEY (id);

10
ALTER TABLE temp DROP PRIMARY KEY;

Creating table and defining Primary Key:

create table temp(


ID int primary
key, NAME
varchar(10)
);
describe temp;

Adding Column and Drop Column from Table

ALTER TABLE temp


ADD COLUMN address VARCHAR(100);

ALTER TABLE temp


DROP COLUMN address;

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);

Setting Default Value for a Column:


ALTER TABLE temp
ADD COLUMN city VARCHAR(100) DEFAULT 'ABC';

Drop Table
drop table temp;

Insert data in table:


insert into temp(id,name,address) values(‘1’,’faisal’,’abbottabad’);

Insert multiple rows in table using single insert query:

insert into temp(id,name,address) values


(5,’name5’,’address5’),
(6,’name6’,’address6’),
(7,’name7’,’address7’);

13
Delete a single from table whose ID does not exist in
table:
delete from temp where id =100;

(There will be no error but 0 row affected)

Delete a single row from table:

DELETE FROM temp WHERE id=3;

‘Where’ expression can have either column of the table, but PRIMARY key column is used to
avoid unwanted deletion of data.

e.g.

DELETE FROM temp WHERE name=’Ali’;

This will delete all the rows with name Ali.

Delete all rows from table:


TRUNCATE temp

OR

DELETE FROM temp

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.

INSERT INTO child


SELECT * FROM PARENT;

Update single column single row in a table:

Update product_t set productstandardprice = 775 where productid = 7;

Update multiple columns in a single rows in a table:

Update temp set name = ‘javed’, address = ‘def’ where id = 2;

Update multiple columns in multiple rows in a table:

Update temp set name = ‘javed’,address = ‘pakistan’ where id>3;

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.

SELECT * FROM product_t WHERE productID=7;

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.

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:

CREATE TABLE PERSONS(


ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR (50) NOT NULL,
AGE INT,
PRIMARY KEY (ID)
);

Inserting rows in PERSONS:

INSERT INTO PERSONS ( ID , NAME , AGE )


VALUES ( 11 , 'Ali' , 25 );

INSERT INTO PERSONS ( NAME , AGE )


VALUES ( 'Ali' , 25);

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.

Start Auto Increment with user specified value :


ALTER TABLE PERSONS AUTO_INCREMENT = 100;

19
After the table is altered for its auto increment value, Insert another record in the table.

INSERT INTO persons ( name , age


) VALUES ( 'Ahmed' , 32 );

The ID of the next row inserted starts from 100 , as altered.

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:

To see the structure of a table we use DESCRIBE command

DESCRIBE CUSTOMER_T;

/* below command create index */

CREATE INDEX Name_IDX ON CUSTOMER_T (CUSTOMERNAME) ;

To see the structure of a table we use DESCRIBE command

DESCRIBE CUSTOMER_T;

22
Drop Indexes :
To remove index on the customer name in the table.

DROP INDEX Name_IDX ON CUSTOMER_T;

And describe table to see the index dropped.

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:

CREATE TABLE MASTER(


MID VARCHAR(5) PRIMARY KEY,
TYPE VARCHAR(10)
);

CREATE TABLE DETAIL(


DIDT VARCHAR(5) PRIMARY KEY,
DES VARCHAR(50),
MID VARCHAR(5)
);

Add foreign key:


ALTER TABLE DETAIL ADD FOREIGN KEY (MID) REFERENCES MASTER(MID);

And drop foreign key:


ALTER TABLE DETAIL DROP FOREIGN KEY your_fk_name;

Even after dropping the foreign key, the index still resides and has to be dropped manually, by

DROP INDEX MID ON DETAIL;

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.

SELECT * FROM PRODUCT_T WHERE ProductStandardPrice<275;

Two Special Keywords used in SELECT:


Two special keywords used in SELECT along with list of columns to display

1. DISTINCT
2. *

DISTINCT: If the user does not wish to see duplicate rows in the result.

Example:

First run simple query:

SELECT PRODUCTDESCRIPTION FROM PRODUCT_T;

And count how many rows are returned. (8 rows are returned).
Next, run query:

27
SELECT DISTINCT PRODUCTDESCRIPTION FROM PRODUCT_T;

And count number of rows returned (7 rows are returned).

Duplicate rows are removed from the results (that was ‘Computer Desk’).

*: Retrieves rows for all columns in the table.


e.g.

SELECT * FROM PRODUCT_T;

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.

The simple query without alias will be:

SELECT CUSTOMER_T.CUSTOMERNAME, CUSTOMER_T.CUSTOMERADDRESS

FROM CUSTOMER_T WHERE CUSTOMER_T.customerName='Home Furnishings'

Example for Alias:


What is the address of the customer named ‘Home Furnishings’? Use an alias, Name, for the
customer name.

SELECT CUST.customerName AS CNAME , CUST.CUSTOMERADDRESS AS ADDRESS


FROM CUSTOMER_T AS CUST WHERE CUST.customerName='Home Furnishings';

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).

SELECT * FROM PRODUCT_T;

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.

SELECT ProductStandardPrice, ProductDescription, ProductID FROM PRODUCT_T;

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.

SELECT ProductStandardPrice, ProductStandardPrice*1.1 AS IncreasedBy10 FROM


PRODUCT_T;

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 Product Price)

Using Functions:
Mathematical: MIN, MAX, COUNT, SUM, ROUND, MOD, AVG

String: LOWER(): To change all string characters in lower case.

UPPER(): To change all string characters in upper case.

INITCAT(): To change only an initial letter to capital

CONCAT(): To Concatenate two strings

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

Date ADDDATE() : Sum two dates


CURDATE(): Return current date
DAY() : Given date as input, this function returns the DAY on that date

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?

SELECT AVG (ProductStandardPrice) AS AveragePrice FROM PRODUCT_T;

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 where ordered number 1004?

SELECT COUNT(*) FROM ORDERLINE_T WHERE ORDERID=1004;

Query: How many different items were ordered on order number 1001, and what are they?

SELECT ProductID, COUNT(*) FROM ORDERLINE_T WHERE ORDERID=1001;

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.

Difference between COUNT(*) and


COUNT(ColumnName)

The following query will not count nulls in count.

SELECT COUNT(ProductID) FROM Product_T;

The following query will count nulls in count.

SELECT COUNT(*) FROM PRODUCT_T;

Query: Display for each product the difference between its standard price and the overall
average standard price of all the products.

SELECT ProductStandardPrice, ProductStandardPrice - (SELECT AVG(ProductStandardPrice)

37
AS PriceAvg FROM PRODUCT_T) AS Difference FROM PRODUCT_T ;

The Difference here is a derived attribute from column ProductStandardPrice.

Query: Alphabetically, what is the first product_name in the product table?

SELECT MIN(ProductDescription) 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.

SELECT ORDERID , ORDERDATE FROM ORDER_T WHERE ORDERDATE>'2010-10-24';

Query: What furniture does Pine View carry that is not made of Cherry?

SELECT ProductDescription, ProductFinish FROM PRODUCT_T WHERE ProductFinish!='Cherry';

Using NULL Values


-Columns that are defined without the ‘NOT NULL’ clause may be empty (due to space inside
cell).

-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*/

SELECT * FROM CUSTOMER_T WHERE CustomerPostalCode IS NULL;

/*below query returns all rows for which CustomerPostalCode does not contains NULL
value*/

SELECT * FROM CUSTOMER_T WHERE CustomerPostalCode IS NOT NULL;

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.

SELECT ProductDescription, ProductFinish, ProductStandardPrice FROM PRODUCT_T WHERE


(ProductDescription LIKE '%Desk%' OR ProductDescription LIKE '%Table%' ) AND
ProductStandardPrice > 300.00 ;

The LIKE operator is used to search for a specified pattern in a column.

% 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.

Expression Column Value Returns


LIKE %Desk Big Desk True

LIKE Desk% Desk Shop True

LIKE %Desk% Blue Desk Shop True

LIKE %Desk My Desk Shop False

LIKE Desk% Big Desk Shop False

Using Ranges for Qualification:


Query: Which product in the product table has a standard price between $200 and $300.

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.

SELECT ProductDescription, ProductFinish, ProductStandardPrice FROM PRODUCT_T WHERE


ProductStandardPrice BETWEEN 200.00 AND 300.00 ;

Using DISTINCT values:


Query: What Order numbers are included in the OrderLine table?

SELECT OrderID FROM OrderLine_t;

If we are interested only to see 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 orderline table?

SELECT DISTINCT OrderID FROM OrderLine_t;

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.

Query: List all customers who live in warmer states.

SELECT CustomerName, CustomerCity, CustomerState FROM Customer_t WHERE


CustomerState IN(‘FL’ , ‘CA’ , ‘HI’ ,’TX’);

Sorting Results: The ORDER BY Clause


ORDER BY: Sorts the final results rows in ascending or descending order.

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.

SELECT CustomerCity, CustomerState FROM CUSTOMER_T WHERE ADDRESS IN(‘FL’ , ‘CA’ ,


‘HI’,’TX’) ORDER BY CustomerState ,CustomerName;

Column names can also be given as its column number i.e. 3, 1.

SELECT CustomerName, CustomerCity, CustomerState FROM Customer_T WHERE


CustomerState IN ('FL' , 'TX' , 'CA', 'HI') ORDER BY 3 , 1 ;

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 5: returns 5 rows.

LIMIT 2, 3: will skip first 2 rows, and return the next 3 rows.

SELECT CustomerName, CustomerCity, CustomerState FROM Customer_T WHERE


CustomerState IN ('FL' , 'TX' , 'CA', 'HI') ORDER BY 3 , 1 LIMIT 3, 5;

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.

Query: Count the number of customers with addresses in each state.

SELECT CustomerState, COUNT(CustomerState) FROM Customer_T GROUP BY CustomerState;

The next query is ordering results by first preference to CustomerState, and second preference
to CustomerCity

SELECT CustomerState, CustomerCity, COUNT(CustomerCity) FROM Customer_T GROUP BY


CustomerState, 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.

Qualify Results by Categories:


The HAVING clause acts like a WHERE clause, but it identifies groups, rather than rows, that
meet a criterion. Before, we usually see a HAVING clause following by a GROUP BY.

49
Query: Find only states with more than one customer.

SELECT CustomerState, COUNT (CustomerState) FROM Customer_T GROUP BY CustomerState


HAVING COUNT (CustomerState) > 1;

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.

SELECT ProductFinish, AVG(ProductStandardPrice) FROM Product_t WHERE ProductFinish IN

( '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.

CREATE VIEW Invoice_v AS

SELECT Customer_T.CustomerID, CustomerAddress, Order_T.OrderID, Product_T.ProductID,


ProductStandardPrice, OrderedQuantity FROM Customer_T, Order_T, OrderLine_T,
Product_t WHERE Customer_T.CustomerID = Order_T. CustomerID AND Order_T.OrderID =
OrderLine_T.OrderID AND Product_T.ProductID = Orderline_T.ProductID;

Query: What are the data elements necessary to create an invoice for number 1004?

SELECT CustomerID, CustomerAddress, ProductID, OrderedQuantity FROM Invoice_V WHERE


OrderID=1004;

Query: What is the total values of orders placed for each furniture product ?

CREATE VIEW OrderTotals_V AS

SELECT ProductID, SUM(ProductStandardPrice * OrderedQuantity) as Total FROM Invoice_V


GROUP BY ProductID;

Query: List all furniture products that have ever had a standard price over $300.

CREATE VIEW ExpensiveStuff_V AS

SELECT ProductID, ProductDescription, ProductStandardPrice FROM Product_t WHERE


ProductStandardPrice > 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

T2ID T2Name T1ID

TABLE3

T3ID T3Name T2ID

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?

SELECT Customer_T.CustomerID , Order_T.CustomerID, CustomerName, OrderID

FROM Customer_T, Order_T

WHERE Customer_T.CustomerID = Order_T.CustomerID ORDER BY OrderID;

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?

SELECT Customer_t.customerid , order_t.customerid, CustomerName, OrderID

FROM customer_t

INNER JOIN Order_T ON

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.

Using an outer join produces this information.

Left OUTER Join


Query: List customer name, identification number, and order number for all customers listed in
the customer table. Include the customer identification number and name even if there is no
order available for that customer.

SELECT Customer_t.Customerid, Customername, Orderid

FROM Customer_t LEFT OUTER JOIN Order_t ON

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.

SELECT customer_t.CustomerID, CustomerName, OrderID FROM Customer_T

RIGHT OUTER JOIN Order_t ON

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.

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;

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,

M.EmployeeName AS Manager FROM

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?

SELECT CustomerName, CustomerAddress, CustomerCity, CustomerState,


CustomerPostalCode

FROM Customer_T, Order_T

WHERE Customer_T.CustomerID = Order_T. CustomerID

AND OrderID = 1008;

Query (Sub-query): What are the name and address of the customer who placed order number
1008?

SELECT CustomerName, CustomerAddress, CustomerCity,CustomerState,


CustomerPostalCode

FROM Customer_T

WHERE Customer_T.CustomerID =

(SELECT Order_T.CustomerID

FROM Order_T

WHERE OrderID = 1008);

Query: What are the names of customers who have placed orders?

63
SELECT CustomerName

FROM Customer_T

WHERE CustomerID IN

(SELECT DISTINCT CustomerID

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

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');

Using EXISTS and NOT EXISTS:


EXISTS will take value of true in the sub query return an intermediate result table that contains
one or more rows (i.e. a non-empty row set) and false if no rows are returned (i.e. an empty
set).

NOT EXISTS: will take a value of true if no rows are returned and false if one or more rows are
returned

EXISTS versus IN and NOT EXISTS versus NOT IN.


WE use EXISTS when we just want to check whether the sub query returns a non-empty set (i.e
we don’t care what is in the set, just whether it is empty), and we use IN when we need to
know what values are in the.

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?

SELECT DISTINCT OrderID FROM OrderLine_T

WHERE EXISTS

(SELECT * FROM Product_T Where ProductID = Orderline_t.ProductID

AND ProductFinish = 'Natural Ash'

);

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.

Example Correlated Subquery:

Query: List the details about the product with the highest standard price;

SELECT ProductDescription, ProductFinish, ProductStandardPrice

FROM Product_t PA

WHERE PA.ProductStandardPrice > ALL

(SELECT ProductStandardPrice

FROM Product_t PB WHERE PB.ProductID != PA.ProductID)

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.

Using Derived Tables:


Subquery may also be used in the FROM clause to create a temporary derived table (or SET)
that is used in the query. Creating a derived table that has an aggregate value in it, such as
MAX, AVG, or MIN, allows the aggregate to be used in the where clause.

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.

SELECT ProductDescription, ProductStandardPrice, AvgPrice

FROM

(SELECT AVG(ProductStandardPrice) AvgPrice FROM Product_t) tempTable, Product_t WHERE


ProductStandardPrice > AvgPrice;

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.

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;

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.

Data Type Conversion:


CAST operator us used to control the data type conversion.

SELECT CAST(OrderDate as CHAR) FROM Order_T;

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

WHEN ProductLineID=1 THEN ProductDescription

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.

Command to see the triggers currently in database;

show triggers;

Now to understand trigger, create a new table named: PriceUpdates_T

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;

CREATE TRIGGER StandardPriceUpdate

AFTER UPDATE ON Product_T

FOR EACH ROW

INSERT INTO PriceUpdates_T VALUES (NEW.ProductID, NEW.ProductDescription, curdate(),


NEW.ProductStandardPrice);

To see our newly created trigger use following command

show triggers;

Now the following command will automatically execute (trigger) the trigger
“StandardPriceUpdate”

update product_t set productstandardprice=210 where productid=3;

74
After the above command is run, check the data in PriceUpdates_T table

SELECT * FROM priceupdates_t;

You will see a new row is inserted in the 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.

update product_t set ProductStandardPrice=333 where productid in (5,6);

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.

The following procedure performs three tasks.

It inserts a new field in Product_T table named “SalePrice”. It

updates SalePrice for ProductStandardPrice >= 400

It updates SalePrice for ProductStandardPrice < 400

CREATE PROCEDURE `ProductLineSale` ()

BEGIN

ALTER TABLE Product_T ADD COLUMN SalePrice decimal(6,2);

UPDATE Product_T

SET SalePrice = .90 * ProductStandardPrice

WHERE ProductStandardPrice >= 400;

UPDATE Product_T

SET SalePrice = .85 * ProductStandardPrice

WHERE ProductStandardPrice < 400;

END

To execute a stored procedure we use the following command

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.

CREATE PROCEDURE `get_Records` (total INT)

BEGIN

SELECT * FROM Product_T LIMIT total;

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

CREATE PROCEDURE `get_count`(mynum INT, OUT outnum INT)

BEGIN

SELECT count(productid) into outnum from product_t where productid > mynum;

END

To call the above procedure we use code

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

SELECT ProductStandardPrice into price from product_t where productid = prodid;

SELECT ProductDescription into proddesc from product_t where productid = prodid;

END

To call the above procedure we use code:

CALL get_multiple_values(3,@proddesc, @price);

select @proddesc, @price;

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.

CREATE FUNCTION `my_function` (myinput INT)

RETURNS INTEGER

BEGIN

declare temp int;

SELECT COUNT(*) into temp from Product_T where productid>myinput;

RETURN temp;

END

To call this function we use code

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.

Follow the following steps.

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”.

Step-4: Using notepad++, write the following code in “index.php”.

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>

87
<br>

<br>

<h6> THIS IS HOME PAGE </h6>

</body>

</html>

Step-5: Write following code in “selectdata.php”.

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> <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>

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 = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

// 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)

89
?>

<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;

?>

90
</body>

</html>

Step-6: Create file “updatedata.php” and put following code in that.

updatedate.php

<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";

91
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);

echo "Connection successful";

// $sql = "update product_t set productdescription='new table' where productid=3";

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;

$sql = "insert into product_t (ProductID, ProductLineID, ProductDescription,


ProductFinish, ProductStandardPrice) values ($txt1, $txt2, '$txt3', '$txt4', $txt5)";

92
// use exec() because no results are returned

$conn->exec($sql);

echo "\nTable product_t updated successfully";

catch(PDOException $e)

echo $sql . "<br>" . $e->getMessage();

$conn = null;

?>

<title> This is test php page </title>

<form id="frm" method="post" action="">

<table border="1">

<tr>

<td>ProductID</td>

93
<td><input id="txt1" name="txt1" type="text" /></td>

</tr>

<tr>

<td>ProductLineID</td>

<td><input id="txt2" name="txt2" type="text" /></td>

</tr>

<tr>

<td>ProductDescription</td>

<td><input id="txt3" name="txt3" type="text" /></td>

</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>

94
<td>Save Record</td>

<td><input id="btn" name="btn" type="submit" value="Save Record" /></td>

</tr>

</table>

</form>

</body>

</html>

Step-7: Test your application by giving command:

http://localhost/myproject/index.php

or if your apache server is using port 8080 then,

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 = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

// 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();

?>

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>

<td><a href="selectdata.php"> Show Record </a></td>

<td><a href="updatedata.php"> Update Data</a></td>

</tr>

</table>

<?php include_once ("opendb.php"); ?>

<table border="1">

<th>ProductID</th>

<th> ProductLineID</th>

<th>ProductDescription </th>

<th>ProductFinish </th>

<th>ProductStandardPrice</th>

<?php

try

foreach($conn->query('SELECT * FROM product_t') as $row)

97
?>

<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;

?>

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.

The similar modifications can also be performed in other files.

How to import an excel sheet into database table


Suppose we have an excel sheet of the following format:

Cat Busines Enter


Cate Busi
e s E- Google Entere ed
gory nes Size Tel# City Address
gory Descript mail Map d By by
ID s
Typ ion URL ID Nam
Titl
e e
e
https://ww
w.google.c
om/maps/
It sells a Located place/34%
variety opposit C2%B011'2
Mo of e to 0.5%22N+7
Gro 0992 moo
on various Abb Army 3%C2%B01 Fa13 Shahi
cery Larg - n@e
34 Emp commo otta Burnhall 4'03.2%22E - d
Stor e 3333 mpor
oriu nly used bad , Jadoon /@34.1890 BSE- Khan
e 3333 ium
m items at plaza, 304,73.232 018
househ mandia 0283,17z/d
olds n ata=!3m1!
4b1!4m2!3
m1!1s0x0:
0x0

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.

Step 2: Create a table in database ‘test’ using the following query:

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.

How to export/import a database


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>

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.

/* The below command is used to export database in .sql file


mysqldump --opt database_name > .sql file path
*/

#Example:
A:\ wamp\bin\mysql\mysql5.6.17\bin>mysqldump --opt test > z:\\test.sql

Use below commands to import a database

/* 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 */

C:\xampp\mysql\bin>mysql -u root -p test < z:\test.sql

How to import a group of CSV files into database using


php script

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:

A:\wamp\bin\php\php5.5.12> php import.php

File Name: import.php

<?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);

echo "Connection successful";


}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$dir = "A://AAA//COMSATS//current semester - Fall 2015//Database


Systems//db_Assignments//fa15//Lab Assignment 04//csvs//";

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;
?>

------- THE END OF LAB MANUAL ----------

102
APPENDIX-A
/*

Database script for pinevalley database.

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., “

File Name: “pinevalley.sql”

*/

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));

CREATE TABLE Territory_T


(TerritoryID int NOT NULL,
TerritoryName VARCHAR(50) ,
CONSTRAINT Territory_PK PRIMARY KEY (TerritoryID));

CREATE TABLE DoesBusinessIn_T


(CustomerID int NOT NULL,
TerritoryID int NOT NULL,
CONSTRAINT DoesBusinessIn_PK PRIMARY KEY (CustomerID, TerritoryID),
CONSTRAINT DoesBusinessIn_FK1 FOREIGN KEY (CustomerID) REFERENCES Customer_T(CustomerID),
CONSTRAINT DoesBusinessIn_FK2 FOREIGN KEY (TerritoryID) REFERENCES Territory_T(TerritoryID));

CREATE TABLE Employee_T


(EmployeeID VARCHAR(10) NOT NULL,
EmployeeName VARCHAR(25) ,
EmployeeAddress VARCHAR(30) ,
EmployeeBirthDate DATE ,

103
EmployeeCity VARCHAR(20) ,
EmployeeState CHAR(2) ,
EmployeeZip VARCHAR(10) ,
EmployeeDateHired DATE ,
EmployeeSupervisor VARCHAR(10) ,
CONSTRAINT Employee_PK PRIMARY KEY (EmployeeID));

CREATE TABLE Skill_T


(SkillID VARCHAR(12) NOT NULL,
SkillDescription VARCHAR(30) ,
CONSTRAINT Skill_PK PRIMARY KEY (SkillID));

CREATE TABLE EmployeeSkills_T


(EmployeeID VARCHAR(10) NOT NULL,
SkillID VARCHAR(12) NOT NULL,
CONSTRAINT EmployeeSkills_PK PRIMARY KEY (EmployeeID, SkillID),
CONSTRAINT EmployeeSkills_FK1 FOREIGN KEY (EmployeeID) REFERENCES Employee_T(EmployeeID),
CONSTRAINT EmployeeSkills_FK2 FOREIGN KEY (SkillID) REFERENCES Skill_T(SkillID));

CREATE TABLE Order_T


(OrderID int NOT NULL,
CustomerID int ,
OrderDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
CONSTRAINT Order_PK PRIMARY KEY (OrderID),
CONSTRAINT Order_FK1 FOREIGN KEY (CustomerID) REFERENCES Customer_T(CustomerID));

CREATE TABLE WorkCenter_T


(WorkCenterID VARCHAR(12) NOT NULL,
WorkCenterLocation VARCHAR(30) ,
CONSTRAINT WorkCenter_PK PRIMARY KEY (WorkCenterID));

CREATE TABLE ProductLine_T


(ProductLineID int NOT NULL,
ProductLineName VARCHAR(50) ,
CONSTRAINT ProductLine_PK PRIMARY KEY (ProductLineID));

CREATE TABLE Product_T


(ProductID int NOT NULL,
ProductLineID int ,
ProductDescription VARCHAR(50) ,
ProductFinish VARCHAR(20) ,
ProductStandardPrice DECIMAL(6,2) ,
CONSTRAINT Product_PK PRIMARY KEY (ProductID),
CONSTRAINT Product_FK1 FOREIGN KEY (ProductLineID) REFERENCES ProductLine_T(ProductLineID));

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));

CREATE TABLE OrderLine_T


(OrderID int NOT NULL,
ProductID int NOT NULL,
OrderedQuantity int ,
CONSTRAINT OrderLine_PK PRIMARY KEY (OrderID, ProductID),
CONSTRAINT OrderLine_FK1 FOREIGN KEY (OrderID) REFERENCES Order_T(OrderID),
CONSTRAINT OrderLine_FK2 FOREIGN KEY (ProductID) REFERENCES Product_T(ProductID));

CREATE TABLE RawMaterial_T


(MaterialID VARCHAR(12) NOT NULL,
MaterialName VARCHAR(30) ,
MaterialStandardCost DECIMAL(6,2) ,
UnitOfMeasure VARCHAR(10) ,
CONSTRAINT RawMaterial_PK PRIMARY KEY (MaterialID));

CREATE TABLE Salesperson_T


(SalespersonID int NOT NULL,
SalespersonName VARCHAR(25) ,
SalespersonPhone VARCHAR(50) ,
SalespersonFax VARCHAR(50) ,
TerritoryID int ,
CONSTRAINT Salesperson_PK PRIMARY KEY (SalesPersonID),
CONSTRAINT Salesperson_FK1 FOREIGN KEY (TerritoryID) REFERENCES Territory_T(TerritoryID));

CREATE TABLE Vendor_T


(VendorID int NOT NULL,
VendorName VARCHAR(25) ,
VendorAddress VARCHAR(30) ,
VendorCity VARCHAR(20) ,
VendorState CHAR(2) ,
VendorZipcode VARCHAR(50) ,
VendorFax VARCHAR(10) ,
VendorPhone VARCHAR(10) ,
VendorContact VARCHAR(50) ,
VendorTaxID VARCHAR(50) ,
CONSTRAINT Vendor_PK PRIMARY KEY (VendorID));

CREATE TABLE Supplies_T


(VendorID int NOT NULL,
MaterialID VARCHAR(12) NOT NULL,

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));

CREATE TABLE Uses_T


(ProductID int NOT NULL,
MaterialID VARCHAR(12) NOT NULL,
GoesIntoQuantity INTEGER ,
CONSTRAINT Uses_PK PRIMARY KEY (ProductID, MaterialID),
CONSTRAINT Uses_FK1 FOREIGN KEY (ProductID) REFERENCES Product_T(ProductID),
CONSTRAINT Uses_FK2 FOREIGN KEY (MaterialID) REFERENCES RawMaterial_T(MaterialID));

CREATE TABLE WorksIn_T


(EmployeeID VARCHAR(10) NOT NULL,
WorkCenterID VARCHAR(12) NOT NULL,
CONSTRAINT WorksIn_PK PRIMARY KEY (EmployeeID, WorkCenterID),
CONSTRAINT WorksIn_FK1 FOREIGN KEY (EmployeeID) REFERENCES Employee_T(EmployeeID),
CONSTRAINT WorksIn_FK2 FOREIGN KEY (WorkCenterID) REFERENCES WorkCenter_T(WorkCenterID));

delete from Uses_T;


delete from WorksIn_T;
delete from WorkCenter_T;
delete from DoesBusinessIn_T;
delete from EmployeeSkills_T;
delete from Supplies_T;
delete from ProducedIn_T;
delete from OrderLine_T;
delete from Product_T;
delete from ProductLine_T;
delete from Order_T;
delete from Salesperson_T;
delete from Vendor_T;
delete from Skill_T;
delete from RawMaterial_T;
delete from Territory_T;
delete from Employee_T;
delete from Customer_T;

INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,


CustomerState, CustomerPostalCode)
VALUES (1, 'Contemporary Casuals', '1355 S Hines Blvd', 'Gainesville', 'FL', '32601-2871');
INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity,
CustomerState, CustomerPostalCode)
VALUES (2, 'Value Furniture', '15145 S.W. 17th St.', 'Plano', 'TX', '75094-7743');

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');

INSERT INTO Territory_T (TerritoryID, TerritoryName)


VALUES (1, 'SouthEast');
INSERT INTO Territory_T (TerritoryID, TerritoryName)
VALUES (2, 'SouthWest');
INSERT INTO Territory_T (TerritoryID, TerritoryName)
VALUES (3, 'NorthEast');
INSERT INTO Territory_T (TerritoryID, TerritoryName)
VALUES (4, 'NorthWest');

107
INSERT INTO Territory_T (TerritoryID, TerritoryName)
VALUES (5, 'Central');

INSERT INTO DoesBusinessIn_T (CustomerID, TerritoryID)


VALUES (1, 1);
INSERT INTO DoesBusinessIn_T (CustomerID, TerritoryID)
VALUES (1, 2);
INSERT INTO DoesBusinessIn_T (CustomerID, TerritoryID)
VALUES (2, 2);
INSERT INTO DoesBusinessIn_T (CustomerID, TerritoryID)
VALUES (3, 3);
INSERT INTO DoesBusinessIn_T (CustomerID, TerritoryID)
VALUES (4, 3);
INSERT INTO DoesBusinessIn_T (CustomerID, TerritoryID)
VALUES (5, 2);
INSERT INTO DoesBusinessIn_T (CustomerID, TerritoryID)
VALUES (6, 5);

INSERT INTO Employee_T (EmployeeID, EmployeeName, EmployeeAddress, EmployeeCity,


EmployeeState, EmployeeZip, EmployeeDateHired, EmployeeBirthDate, EmployeeSupervisor)
VALUES ('123-44-345', 'Jim Jason', '2134 Hilltop Rd', '', 'TN', '', '12/Jun/99', '', '454-56-768');

INSERT INTO Employee_T (EmployeeID, EmployeeName, EmployeeAddress, EmployeeCity,


EmployeeState, EmployeeZip, EmployeeDateHired, EmployeeBirthDate, EmployeeSupervisor)
VALUES ('454-56-768', 'Robert Lewis', '17834 Deerfield Ln', 'Nashville', 'TN', '', '01/Jan/99', '', '');

Insert into Employee_T


(EmployeeID,EmployeeName,EmployeeAddress,EmployeeCity,EmployeeState,EmployeeZip,EmployeeDa
teHired,EmployeeBirthDate,EmployeeSupervisor)
values ('123-44-346','Phil Morris','2134 Hilltop Rd','Knoxville','TN',null,'12-JUN-99' ,'12-JUN-99','454-56-
768');

Insert into Employee_T


(EmployeeID,EmployeeName,EmployeeAddress,EmployeeCity,EmployeeState,EmployeeZip,EmployeeDa
teHired,EmployeeBirthDate,EmployeeSupervisor)
values ('332445667','Lawrence Haley','5970 Spring Crest Rd','Nashville','TN','54545','2008-7-04','2008-7-
04','454-56-768');

Insert into Employee_T


(EmployeeID,EmployeeName,EmployeeAddress,EmployeeCity,EmployeeState,EmployeeZip,EmployeeDa
teHired,EmployeeBirthDate,EmployeeSupervisor)
values ('454-56-769','Robert Lewis','17834 Deerfield Ln','Knoxville','TN','55555','2008-7-04','2008-7-
04','123-44-345');

Insert into Employee_T


(EmployeeID,EmployeeName,EmployeeAddress,EmployeeCity,EmployeeState,EmployeeZip,EmployeeDa
teHired,EmployeeBirthDate,EmployeeSupervisor)

108
values ('555955585','Mary Smith','75 Jane Lane','Clearwater','FL','33879','2008-7-04','2008-7-
04','332445667');

Insert into Employee_T


(EmployeeID,EmployeeName,EmployeeAddress,EmployeeCity,EmployeeState,EmployeeZip,EmployeeDa
teHired,EmployeeBirthDate,EmployeeSupervisor)
values ('Laura','Laura Ellenburg','5342 Picklied Trout Lane','Nashville','TN','38010','2008-7-04',null,'454-
56-768');

INSERT INTO Skill_T (SkillID, SkillDescription)


VALUES ('BS12', '12in Band Saw');
INSERT INTO Skill_T (SkillID, SkillDescription)
VALUES ('QC1', 'Quality Control');
INSERT INTO Skill_T (SkillID, SkillDescription)
VALUES ('RT1', 'Router');
INSERT INTO Skill_T (SkillID, SkillDescription)
VALUES ('SO1', 'Sander-Orbital');
INSERT INTO Skill_T (SkillID, SkillDescription)
VALUES ('SB1', 'Sander-Belt');
INSERT INTO Skill_T (SkillID, SkillDescription)
VALUES ('TS10', '10in Table Saw');
INSERT INTO Skill_T (SkillID, SkillDescription)
VALUES ('TS12', '12in Table Saw');
INSERT INTO Skill_T (SkillID, SkillDescription)
VALUES ('UC1', 'Upholstery Cutter');
INSERT INTO Skill_T (SkillID, SkillDescription)
VALUES ('US1', 'Upholstery Sewer');
INSERT INTO Skill_T (SkillID, SkillDescription)
VALUES ('UT1', 'Upholstery Tacker');

INSERT INTO EmployeeSkills_T (EmployeeID, SkillID)


VALUES ('123-44-345', 'BS12');
INSERT INTO EmployeeSkills_T (EmployeeID, SkillID)
VALUES ('123-44-345', 'RT1');
INSERT INTO EmployeeSkills_T (EmployeeID, SkillID)
VALUES ('454-56-768', 'BS12');

INSERT INTO Order_T (OrderID, OrderDate, CustomerID)


VALUES (1001, '21/Oct/10', 1);
INSERT INTO Order_T (OrderID, OrderDate, CustomerID)
VALUES (1002, '21/Oct/10', 8);
INSERT INTO Order_T (OrderID, OrderDate, CustomerID)
VALUES (1003, '22/Oct/10', 15);
INSERT INTO Order_T (OrderID, OrderDate, CustomerID)
VALUES (1004, '22/Oct/10', 5);
INSERT INTO Order_T (OrderID, OrderDate, CustomerID)
VALUES (1005, '24/Oct/10', 3);
INSERT INTO Order_T (OrderID, OrderDate, CustomerID)

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);

INSERT INTO ProductLine_T (ProductLineID, ProductLineName)


VALUES (1, 'Cherry Tree');
INSERT INTO ProductLine_T (ProductLineID, ProductLineName)
VALUES (2, 'Scandinavia');
INSERT INTO ProductLine_T (ProductLineID, ProductLineName)
VALUES (3, 'Country Look');
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish, ProductStandardPrice,
ProductLineID)
VALUES (1, 'End Table', 'Cherry', 175, 1);
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish, ProductStandardPrice,
ProductLineID)
VALUES (2, 'Coffee Table', 'Natural Ash', 200, 2);
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish, ProductStandardPrice,
ProductLineID)
VALUES (3, 'Computer Desk', 'Natural Ash', 375, 2);
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish, ProductStandardPrice,
ProductLineID)
VALUES (4, 'Entertainment Center', 'Natural Maple', 650, 3);
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish, ProductStandardPrice,
ProductLineID)
VALUES (5, 'Writers Desk', 'Cherry', 325, 1);
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish, ProductStandardPrice,
ProductLineID)
VALUES (6, '8-Drawer Desk', 'White Ash', 750, 2);
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish, ProductStandardPrice,
ProductLineID)
VALUES (7, 'Dining Table', 'Natural Ash', 800, 2);
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish, ProductStandardPrice,
ProductLineID)
VALUES (8, 'Computer Desk', 'Walnut', 250, 3);

INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)


VALUES (1001, 1, 2);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1001, 2, 2);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)
VALUES (1001, 4, 1);
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)

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);

INSERT INTO Salesperson_T (SalesPersonID, SalesPersonName, SalesPersonPhone, SalesPersonFax,


TerritoryID)
VALUES (1, 'Doug Henny', '8134445555', '', 1);
INSERT INTO Salesperson_T (SalesPersonID, SalesPersonName, SalesPersonPhone, SalesPersonFax,
TerritoryID)
VALUES (2, 'Robert Lewis', '8139264006', '', 2);
INSERT INTO Salesperson_T (SalesPersonID, SalesPersonName, SalesPersonPhone, SalesPersonFax,
TerritoryID)
VALUES (3, 'William Strong', '5053821212', '', 3);
INSERT INTO Salesperson_T (SalesPersonID, SalesPersonName, SalesPersonPhone, SalesPersonFax,
TerritoryID)
VALUES (4, 'Julie Dawson', '4355346677', '', 4);
INSERT INTO Salesperson_T (SalesPersonID, SalesPersonName, SalesPersonPhone, SalesPersonFax,
TerritoryID)
VALUES (5, 'Jacob Winslow', '2238973498', '', 5);

INSERT INTO WorkCenter_T (WorkCenterID, WorkCenterLocation)


VALUES ('SM1', 'Main Saw Mill');

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

You might also like