0% found this document useful (0 votes)
26 views60 pages

Lab Manual - Database Systems Lab 01: Creating and Configuring The Database

The document is a lab manual for Database Systems, detailing various tasks and objectives for creating, configuring, and managing databases using MySQL Workbench. It covers topics such as connecting to MySQL, creating and populating databases, running queries, and modifying table structures. The manual is structured into multiple labs, each focusing on specific database operations and SQL commands.

Uploaded by

masabraja153
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views60 pages

Lab Manual - Database Systems Lab 01: Creating and Configuring The Database

The document is a lab manual for Database Systems, detailing various tasks and objectives for creating, configuring, and managing databases using MySQL Workbench. It covers topics such as connecting to MySQL, creating and populating databases, running queries, and modifying table structures. The manual is structured into multiple labs, each focusing on specific database operations and SQL commands.

Uploaded by

masabraja153
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Created by Turbolearn AI

Lab Manual - Database Systems


Lab 01: Creating and Configuring the
Database
Objectives:

Learn how to show existing databases.


Create a new database.
Populate the database with data.
Run simple SELECT queries.

Configuring the Environment


Tasks to be performed only once:

Page 1
Created by Turbolearn AI

How to Download and Install MySQL Workbench

1. Click the link: https://dev.mysql.com/downloads/workbench


2. Select the window version 64 bit x86, zip archive.
3. Click on “Download” and save to 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 the 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 the 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 the Windows Start button.


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

Connecting MySQL Workbench with MySQL

Page 2
Created by Turbolearn AI

1. Make sure your MySQL is already running (MySQL is highlighted green in xamp
control panel).
2. Open MySQLWorkbench folder and click on the blue-colored MySQLWorkbench.exe
file.
3. If there is no connection shown, then click on the "plus-shaped" icon to create a
new connection.
4. Input a connection name “mycon”.
5. The User name should be root.
6. The Password should be blank and click save, click test to see the response. If
the response is "connection parameters are correct" your connection is
successful.
7. Now double click on the “mycon” connection icon, MySQLWorkbench should be
connected with the MySQL, and existing databases should be shown at the left
side.
8. Go to Edit -> Preferences.
9. Click on “Sql Editor” and at the below of page uncheck option under “Safe
Updates”.
10. Click “Close” button on top right corner of MySQLWorkbench to exit program.
11. After the program is exit, re-open MySQLWorkbench.

Importing “pinevalley” database in MySQL


Steps need to be performed if the 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;

The image shows the result of executing the "show databases;" command in MySQL
Workbench, revealing a list of existing databases.

Page 3
Created by Turbolearn AI

3. If “Pharmacy” is not present in the list of databases, in the new query tab, write
following query:

CREATE SCHEMA Pharmacy;

The image shows the result of creating the "Hospital" schema in MySQL Workbench.

4. If your Hospital database is already present but is corrupt (missing some


tables), then write the following query to delete an existing copy, if any, of the
pinevalley database

DROP SCHEMA Hospital;

5. Execute the queries. If the final green message “COMMIT” appears, the
database is imported successfully, otherwise, review your all steps, as you must
have missed any of the above steps.

Show tables of a database “Hospital”

Page 4
Created by Turbolearn AI

USE Hospital;
SHOW TABLES;

The image shows the tables present in the Hospital database.

Show data of a table Media

USE Hospital;
SELECT * FROM city;

The query retrieves and displays all columns and rows from the city table in the
Hospital database, as shown in the image.

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

Examples

Page 5
Created by Turbolearn AI

From the customer table in the following order: customercity, customername,


customerid:

USE pinevalley;
SELECT CustomerName, CustomerCity, CustomerID FROM customer_t;

To show the record for customerid=5:

USE pinevalley;
SELECT * FROM customer_t WHERE customerid=5;

To show records of customers whose id is greater than or equal to 5:

USE pinevalley;
SELECT * FROM customer_t WHERE customerid>=5;

To show records 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 custo

To retrieve records of customers based on a given city name:

USE pinevalley;
SELECT customerid, customername, customeraddress FROM customer_t WHERE cus

Lab 02: Update Database Structure


Objectives:

Familiarize students with the basic SELECT statement.


Add/drop a primary key.
Add/drop a column from table.

Page 6
Created by Turbolearn AI

Commands
Command to show the tables in a database:

USE Pinevalley;
SHOW TABLES;

Retrieve System Time:

SELECT CURTIME();
-- OR
SELECT CURTIME() AS mytime;

Add Two Numbers:

SELECT 8+4;
-- OR
SELECT 8+4 AS ans;

Creating a New Table


Ground truth images are reference images used in various fields such as computer
vision, remote sensing, and medical imaging. These images are considered the
authoritative or 'true' representation of a scene or object. Ground truth images serve
as a benchmark against which the performance of algorithms or systems can be
evaluated.

CREATE TABLE places (


pID INT PRIMARY KEY,
pName VARCHAR(30) NOT NULL
);

Page 7
Created by Turbolearn AI

The image shows the successful creation of a table named "places" in MySQL
Workbench.

Adding/Dropping Primary Key


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

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

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

Page 8
Created by Turbolearn AI

ALTER TABLE temp ADD COLUMN address VARCHAR(100);


ALTER TABLE temp DROP COLUMN address;

Lab 03: Change Table Structure/Data


Objectives:

Rename a column in a table.


Set a default value for a column.
Drop a table.
Empty a table of data.
Delete a row from a table.

Renaming a Column in a Table

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

Page 9
Created by Turbolearn AI

Insert Multiple Rows in Table Using Single Insert Query

INSERT INTO temp(id, name, address) VALUES


(5, 'name5', 'address5'),
(6, 'name6', 'address6');

Delete a Single Row From Table Whose ID Does Not Exist


in Table

Delete a Single Row From Table

DELETE FROM temp WHERE id=3;

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

For example:

DELETE FROM temp WHERE name='Ali';

This will delete all the rows with the name Ali.

Delete All Rows From Table

TRUNCATE temp;
-- OR
DELETE FROM temp;

Lab 04: Data Copying/Deletion

Page 10
Created by Turbolearn AI

Objectives:

Transfer/copy data from one table to another.


Delete data from a table based on selected criteria.
Update a specific row in a table.

Transfer/Copy Data from table1 to table2 with same table


structure (SELECT INSERT QUERY)
Table (CHILD) by using a 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 Row in a Table

UPDATE temp
SET name = 'javed', address = 'def'
WHERE id = 2;

Update Multiple Columns in Multiple Rows in a Table

Page 11
Created by Turbolearn AI

UPDATE temp
SET name = 'javed', address = 'pakistan'
WHERE id>3;

Update a Row in Table


First, you need to confirm the row you want to update should exist in the table. For
example, 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.

Lab 05: Auto-Increment Primary Key


Objectives:

Create an auto-increment primary key.


Insert rows using the INSERT query when an auto-increment primary key is
defined.
Initialize the auto-increment primary key for a specified value.

Creating an AUTO INCREMENT PRIMARY KEY

Page 12
Created by Turbolearn AI

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 into the table PERSONS. Note that we gave the ID for the first
row i.e., 11, and we did not give any ID for the second row. It automatically
incremented the next row ID based on the maximum ID in the rows already inserted.
In the next row, the ID will be automatically inserted as 12.

Start Auto Increment with user specified value

ALTER TABLE PERSONS AUTO_INCREMENT = 100;

The table is altered for its auto-increment value. Insert another record into the table.

INSERT INTO persons (name, age)


VALUES ('Ahmed', 32);

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

Lab 06: Database Indexes

Page 13
Created by Turbolearn AI

Objectives:

Learn the benefits of creating indexes on database tables.


Create indexes on table fields.
Drop indexes.

Creating Indexes
Indexes are created in RDBMS to provide rapid and sequential access to base
table data.
Indexes are usually created both for primary and secondary keys and both
single and concatenated (multiple column keys).

To see the structure of a table, we use the DESCRIBE command:

DESCRIBE CUSTOMER_T;

Below command creates an index:

CREATE INDEX Name_IDX ON CUSTOMER_T (CUSTOMERNAME);

To see the structure of a table, we use the DESCRIBE command:

DESCRIBE CUSTOMER_T;

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

DROP INDEX Name_IDX ON CUSTOMER_T;

Page 14
Created by Turbolearn AI

And describe the table to see the index dropped.

Lab 07: Create Index on Foreign Keys


Objectives:

Understand the relation of indexes with a table’s foreign keys.


Create indexes on foreign keys.
Drop a foreign key index.

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

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:

Page 15
Created by Turbolearn AI

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.

Lab 08: SELECT Clause in Detail


Objectives:

Teach students various clauses of the SELECT statement.


Learn about the two special keywords used in the select clause.

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 includes 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 are used in SELECT along with the list of columns to display:

Page 16
Created by Turbolearn AI

1. DISTINCT
2. *

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

Example:

First run a simple query:

SELECT PRODUCTDESCRIPTION FROM PRODUCT_T;

SELECT DISTINCT PRODUCTDESCRIPTION FROM PRODUCT_T;

And count the number of rows returned (7 rows are returned). Duplicate rows are
removed from the results (that was ‘Computer Desk’).

SELECT * FROM PRODUCT_T;

*: Retrieves rows for all columns in the table.

Lab 09: Creating Alias in Database


Objectives:

Learn how to create a table alias and a table’s field alias.

Using Alias in SELECT Statement


Advantage: Using aliases makes 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 aliases does not change anything in
the actual table’s structure; it is just used for data reading/presentation from the
database.

Page 17
Created by Turbolearn AI

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 CustomerName and
Address for CustomerAddress.

Lab 10: Sorting the Data


Objectives:

Learn how to sort table data using the ORDER BY clause.

Rearranging column Order in SELECT Query


While creating a new table, it is not necessary to create columns in a table in a
specific order. Because we can select data from a table in any order we like, by
placing the columns in different orders in the 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 the table
was created).

SELECT * FROM PRODUCT_T;

Page 18
Created by Turbolearn AI

Now we want to change the order of columns in the retrieved record in the next
query.

Query: List the unit price, product name, and product ID for all products in the
product table, in the same order as given in this statement.

SELECT ProductStandardPrice, ProductDescription, ProductID FROM PRODUCT_T;

Lab 11: Using Expressions and Functions


Objectives:

Learn how to use expressions and functions in select queries.

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 FRO

Returns two columns, one the ProductStandardPrice and the other column with the
price increased by 10% and its alias name as IncreasedBy10.

Multiplying 1.1 is equivalent to calculating 10% and adding it to the Product Price.

Using Functions

Page 19
Created by Turbolearn AI

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
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 the
MySQL website.

Query: What is the average standard price for all products in inventory?

SELECT AVG(ProductStandardPrice) AS AveragePrice FROM PRODUCT_T;

Lab 12: Built-in Functions


Objectives:

Understand the use of some of the built-in functions, such as COUNT, MIN, and
MAX.

Page 20
Created by Turbolearn AI

COUNT : Returns single row


Query: How many different items where ordered number 1004?

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

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 an error because COUNT returns only one row, though we are
selecting multiple rows for productID. It will return an error in SQL Server or Oracle,
but for MySQL, the query returns the 1st productID along with the count as the query
result.

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.

Page 21
Created by Turbolearn AI

SELECT
ProductStandardPrice,
ProductStandardPrice - (
SELECT AVG(ProductStandardPrice)
FROM PRODUCT_T
) AS Difference
FROM PRODUCT_T;

The Difference here is a derived attribute from the 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 a numeric value then the numeric value of the string will be used
for comparison (while the rest of the string will be truncated). If instead, we use the
MAX function, it will give preference to string value, and the string starting with the
highest alphabet position will be returned (ignoring the string starting with the
numeric value).

Lab 13: NULL Values


Objectives:

Learn the work of various comparison operators and the use of the NULL
keyword.

Using Comparison Operators


Query: Which orders have been placed since 10/24/2010?

SELECT ORDERID, ORDERDATE


FROM ORDER_T
WHERE ORDERDATE>'2010-10-24';

Page 22
Created by Turbolearn AI

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

NULL value means a column is missing a value; the value is not zero, or
blank, or any special code – there is simply a NULL value.

The functions may produce different results where NULL values are present than
when a column has a value of zero.

Query: Display all customers for whom we do not know their Postal Code.

-- below query returns all rows for which CustomerPostalCode contains NULL
SELECT * FROM CUSTOMER_T
WHERE CustomerPostalCode IS NULL;

-- below query returns all rows for which CustomerPostalCode does not cont
SELECT * FROM CUSTOMER_T
WHERE CustomerPostalCode IS NOT NULL;

Lab 14: Logical Operators


Objectives:

Learn different types of logical operators and how they are used to filter data in
select queries. The use of the DISTINCT operator will also be discussed.

Boolean Operators (Logical Operators)

Page 23
Created by Turbolearn AI

AND: Joins two or more conditions and returns results only when all conditions
are true.
OR: Joins two or more conditions and returns results when at least one condition
is true.
NOT: Negates an expression.

Order of Preference:

If multiple Boolean operators are used in an SQL statement, NOT is evaluated first,
then AND, then OR.

Query: List Product Name, Finish, and Standard Price for all desks and all tables that
cost more than $300 in the product table.

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 wildcard that anything can appear before the
string, but should end with the string.
Vice versa, % after the string acts as a wildcard that anything can appear after
the string but should start with the string.
If % is added before and after the string, the string can appear as a substring in a
string, either in the start, mid, or end.
Expression Column Value Returns

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 200and300?

Page 24
Created by Turbolearn AI

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 200and300?

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 in seeing which order IDs are appearing rather than how
many times they are appearing, we will use DISTINCT.

Query: What are distinct order numbers included in the orderline table?

SELECT DISTINCT OrderID FROM OrderLine_t;

Lab 15: Understanding IN and NOT IN


Objectives:

Understand the two very important keywords in SQL that are IN and NOT IN,
and how to sort data using the ORDER BY clause.

Using IN and NOT IN Lists

Page 25
Created by Turbolearn AI

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 where the values in
those rows were the 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 the 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;

Lab 16: The Use of “limit” Operator


"LIMIT" Operator

Page 26
Created by Turbolearn AI

The LIMIT operator is used to constrain the number of results returned by a query or
to specify a range of rows to return.

LIMIT 5: Returns the first 5 rows.


LIMIT 2, 3: Skips the first 2 rows and returns the next 3 rows.

Example:

SELECT CustomerName, CustomerCity, CustomerState


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

This query skips the first 3 rows and returns the next 5 rows from the result set.

"GROUP BY" and "HAVING" Clause

Categorizing Results: The "GROUP BY" Clause


The GROUP BY clause is used with aggregate functions like SUM or COUNT to
divide a table into subsets (groups) and provide summary information for each group.

Scalar Aggregate: A single value returned by an aggregate function.

Vector Aggregate: Multiple values returned by aggregate functions used


with a GROUP BY clause.

Example: Count the number of customers in each state.

SELECT CustomerState, COUNT(CustomerState)


FROM Customer_T
GROUP BY CustomerState;

Example: Ordering results by CustomerState and CustomerCity

Page 27
Created by Turbolearn AI

SELECT CustomerState, CustomerCity, COUNT(CustomerCity)


FROM Customer_T
GROUP BY CustomerState, CustomerCity;

This query counts the number of customers in each city, listing the cities by state,
effectively nesting groups within groups.

Qualifying Results by Categories: The "HAVING" Clause


The HAVING clause is similar to a WHERE clause, but it filters groups rather than
rows based on a specified criterion. HAVING is used with GROUP BY.

Example: Find only states with more than one customer.

SELECT CustomerState, COUNT(CustomerState)


FROM Customer_T
GROUP BY CustomerState
HAVING COUNT(CustomerState) > 1;

You can include multiple conditions in the HAVING clause using AND, OR, and NOT.

Example: List the product finish and average standard price for selected finishes with
an average standard price less than 750, ordered alphabetically by finish.

SELECT ProductFinish, AVG(ProductStandardPrice)


FROM Product_t
WHERE ProductFinish IN ('Cherry', 'Natural Ash', 'Natural Maple', 'White A
GROUP BY ProductFinish
HAVING AVG(ProductStandardPrice) < 750
ORDER BY ProductFinish;

Defining Views

Using and Defining Views

Page 28
Created by Turbolearn AI

A view simplifies query commands, improves data security, and enhances


programming consistency and productivity.

Example: Create a view named Invoice_v to gather data elements necessary to create
an invoice for a customer.

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;

Example: Retrieve data elements for invoice number 1004 using the Invoice_V view.

SELECT CustomerID, CustomerAddress, ProductID, OrderedQuantity


FROM Invoice_V
WHERE OrderID = 1004;

Example: Create a view to find the total value 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;

Example: Create a view to list all furniture products that have ever had a standard
price over $300.

Page 29
Created by Turbolearn AI

CREATE VIEW ExpensiveStuff_V AS


SELECT ProductID, ProductDescription, ProductStandardPrice
FROM Product_t
WHERE ProductStandardPrice > 300;

Queries Involving Multiple Tables

Processing Multiple Tables


Equi-Join: A join based on equality between values in common columns, which
appear redundantly in the result table.

The image shows a database schema with three tables (TABLE1, TABLE2, and
TABLE3) joined through primary key/foreign key relationships. TABLE1 has columns
T1ID and T1Name, TABLE2 has T2ID, T2Name, and T1ID (foreign key), and TABLE3
has T3ID, T3Name, and T2ID (foreign key). This schema visually represents how
data can be related across multiple tables in a database.

Example: Retrieve values from three tables joined through primary key/foreign key
relationships using equi-join.

SELECT t1name, t2name, t3name


FROM TABLE1, TABLE2, TABLE3
WHERE TABLE1.T1ID = TABLE2.T1ID
AND TABLE2.T2ID = TABLE3.T2ID;

Example: Retrieve customer IDs, names, and order IDs for all orders placed.

Page 30
Created by Turbolearn AI

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


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

INNER JOIN is used to establish an equi-join in the FROM clause.

Example: Retrieve customer IDs, names, and order IDs using INNER JOIN.

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;

Different Types of Joins

Outer Join
An outer join includes rows that do not have matching values in common columns.
Null values appear in columns where there is no match between tables.

Example Use Case: Identify customers who have not placed any orders to encourage
new orders or analyze why they are not ordering.

Left Outer Join


Example: List customer name, identification number, and order number for all
customers. Include the customer information even if there is no order available.

SELECT Customer_t.Customerid, Customername, Orderid


FROM Customer_t
LEFT OUTER JOIN Order_t ON Customer_t.CustomerID = Order_t.customerid;

Page 31
Created by Turbolearn AI

Right Outer Join


Example: List customer name, identification number, and order number for all orders.
Include the order number even if there is no customer information available.

SELECT Customer_t.CustomerID, CustomerName, OrderID


FROM Customer_TRIGHT OUTER JOIN Order_t ON Customer_t.CustomerID = Order_t

This query also returns rows where the foreign key column does not exist (NULL).

Self Join
A self join involves matching rows in a table with other rows in the same table.

Sample Join Involving Four Tables


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

Page 32
Created by Turbolearn AI

Self Join Example


Example: Retrieve the employee ID and name of each employee along with the name
of his/her supervisor (labeled as manager).

SELECT
E.EmployeeID,
E.EmployeeName,
M.EmployeeName AS Manager
FROM
Employee_T E,
Employee_T M
WHERE
E.EmployeeSupervisor = M.EmployeeID;

Subqueries

Subqueries Overview
Subqueries involve placing an inner query (SELECT . . . FROM . . . WHERE) within a
WHERE or HAVING clause of another (outer) query. The inner query provides a set of
one or more values for the search condition of the outer query.

Example (Not Subquery): Retrieve the name and address of the customer who
placed order number 1008.

SELECT
CustomerName,
CustomerAddress,
CustomerCity,
CustomerState,
CustomerPostalCode
FROM
Customer_T,
Order_T
WHERE
Customer_T.CustomerID = Order_T.CustomerID
AND OrderID = 1008;

Example (Subquery): Retrieve the names of customers who have placed orders.

Page 33
Created by Turbolearn AI

SELECT
CustomerName,
CustomerAddress,
CustomerCity,
CustomerState,
CustomerPostalCode
FROM
Customer_T
WHERE
Customer_T.CustomerID = (SELECT Order_T.CustomerID FROM Order_T WHERE

SELECT CustomerName
FROM Customer_T
WHERE CustomerID IN (SELECT DISTINCT CustomerID FROM Order_T);

IN, NOT IN, EXISTS, NOT EXISTS

Using the NOT IN Qualifier


Example: Find customers who 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: Returns true if the subquery returns a non-empty row set (one or more
rows).

NOT EXISTS: Returns true if the subquery returns an empty set (no rows).

EXISTS vs. IN and NOT EXISTS vs. NOT IN:

Page 34
Created by Turbolearn AI

Use EXISTS when you only need to check if the subquery returns a non-empty
set.
Use IN when you need to know what values are in the set.
IN and NOT IN return a set of values from only one column, which can then be
compared to one column in the outer query.
EXISTS and NOT EXISTS return only true or false values based on whether
there are any rows in the answer table of the inner query.

Example: Find the order IDs for all orders that have included furniture finished in
Natural Ash.

SELECT DISTINCT OrderID


FROM OrderLine_T
WHERE EXISTS (
SELECT *
FROM Product_T
WHERE ProductID = Orderline_t.ProductID
AND ProductFinish = 'Natural Ash'
);

Derived Tables and Subqueries

Correlated Subqueries
Correlated subqueries use the result of the outer query to determine the processing
of the inner query. The inner query must be computed for each outer row.

Example: List the details about the product with the highest standard price.

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

Page 35
Created by Turbolearn AI

Using Derived Tables


A subquery can be used in the FROM clause to create a temporary derived table (or
SET) used in the query. Creating a derived table that has an aggregate value allows
the aggregate to be used in the WHERE clause.

Example: Show the product description, product standard price, and overall average
standard price for all products that have a standard price higher than the average.

SELECT ProductDescription, ProductStandardPrice, AvgPrice


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

UNION Operator & Type Conversion

Union Operator
The UNION clause combines the output from multiple queries into a single result
table. Each query must output the same number of columns, and they must be of
compatible data types.

Example: Determine the customer(s) who purchased the largest and smallest
quantity of any Pine Valley product in a given line item.

Page 36
Created by Turbolearn AI

SELECT
C1.CustomerID,
CustomerName,
OrderedQuantity,
'Largest Quantity' AS Quantity
FROM
Customer_t C1,
Order_t O1,
OrderLine_t Q1
WHERE
C1.CustomerID = O1.CustomerID
AND O1.OrderID = Q1.OrderID
AND OrderedQuantity = (SELECT MAX(OrderedQuantity) FROM OrderLine_t)
UNION
SELECT
C1.CustomerID,
CustomerName,
OrderedQuantity,
'Smallest Quantity' AS Quantity
FROM
Customer_t C1,
Order_t O1,
OrderLine_t Q1
WHERE
C1.CustomerID = O1.CustomerID
AND O1.OrderID = Q1.OrderID
AND OrderedQuantity = (SELECT MIN(OrderedQuantity) FROM OrderLine_t)
ORDER BY 3;

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


The CAST operator is used to control data type conversion.

Conditional Expressions and Triggers

Conditional Expressions

Page 37
Created by Turbolearn AI

IF-THEN-ELSE
CASE Keyword

Example:

SELECT
CASE
WHEN ProductLineID = 1 THEN ProductDescription
ELSE '###'
END AS ProductDescription
FROM
Product_t;

Triggers
A trigger is a named set of SQL statements that are triggered automatically when a
data modification (INSERT, UPDATE, DELETE) occurs or if certain data definitions are
encountered.

A trigger has three parts: the event, the condition, and the action.

Example: Create a new table named PriceUpdates_T.

create table PriceUpdates_T (


ProductID int,
ProductDescription varchar(50),
UpdateDate DATE,
NewPrice decimal(6,2)
);

Example: Create a trigger named 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.ProductStand

Page 38
Created by Turbolearn AI

Command to see triggers in the database:

show triggers;

Example: Automatically execute the trigger "StandardPriceUpdate"

update product_t set productstandardprice=210 where productid=3;

After running the above command, check the data in the PriceUpdates_T table:

SELECT * FROM priceupdates_t;

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. FOR EACH ROW means that a new row in PriceUpdates_T
will be inserted for each updated row.

Introduction to Stored Procedures

Stored Procedures Overview


A stored procedure is 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.

Example: The following procedure performs three tasks: inserts a new field in
Product_T table named "SalePrice", updates SalePrice for ProductStandardPrice >=
400, and updates SalePrice for ProductStandardPrice < 400.

Page 39
Created by Turbolearn AI

CREATE PROCEDURE `ProductLineSale` ()


BEGIN
ALTER TABLE Product_T ADD COLUMN SalePrice decimal(6,2);
UPDATE Product_T SET SalePrice = .90 * ProductStandardPrice WHERE Prod
UPDATE Product_T SET SalePrice = .85 * ProductStandardPrice WHERE Prod
END

To execute a stored procedure:

call ProductLineSale();

Stored Procedure - Single Input

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

Example Usage: Return just 2 records.

call get_Records(2)

Stored Procedures - Input/Output

Stored Procedure with a Single Input and a Single Output


Parameter

Page 40
Created by Turbolearn AI

The following stored procedure takes as input a single parameter and outputs result
into a single parameter. For the output parameter, we use the OUT keyword.

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


BEGIN
SELECT count(productid) into outnum from product_t where productid > m
END

Example Usage:

CALL get_count(3,@outnum);
select @outnum;

The above procedure is returning count of records into outnum, and only those
records’ count is returned whose productid is greater than 3.

Stored Procedure Returning Values

Stored Procedure with a Single Input Parameter and Two


Output Parameters
Example:

CREATE PROCEDURE `get_multiple_values`(prodid INT, OUT proddesc VARCHAR(50


BEGIN
SELECT ProductStandardPrice into price from product_t where productid
SELECT ProductDescription into proddesc from product_t where productid
END

Example Usage:

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


select @proddesc, @price;

Page 41
Created by Turbolearn AI

Here, the above procedure is returning values of product description and product
standard price for a provided productid=3.

Using MySQL Functions

MySQL Functions Overview


A function returns one value and has only input parameters. You have already seen
many built-in functions included in SQL, such as MAX, MIN, CEILING, FLOOR, SQRT,
etc.

The following function 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

Example Usage:

select my_function(3);

Connecting MySQL with PHP

Connecting PHP with MySQL


Make sure you have "pinevalley" database successfully configured in your MySQL
server / wamp.

Steps:

Page 42
Created by Turbolearn AI

1. Run wampserver and ensure phpmyadmin is running fine.


2. In the "www" folder of your wampserver, create a new folder named
"myproject".
3. Uncheck "hide file extensions for known file type" in Folder Options.
4. In "myproject" folder, create three files: "index.php", "selectdata.php", and
"updatedata.php".

Example: index.php

<html>
<body>
<table border="1">
<tr>
<td><a href="index.php">Home</a></td>
<td><a href="selectdata.php"> Show Record </a></td>
<td><a href="updatedata.php"> Update Data</a></td>
</tr>
</table>

<br>
<br>
<h6> THIS IS HOME PAGE </h6>
</body>
</html>

Example: selectdata.php

Page 43
Created by Turbolearn AI

<html>
<head>
<title> This is data selection page </title>
</head>
<body>
<table border="1">
<tr>
<td><a href="index.php">Home</a></td>
<td><a href="selectdata.php"> Show Record </a></td>
<td><a href="updatedata.php"> Update Data</a></td>
</tr>
</table>

<?php
$servername = "localhost";
$username = "root";
$password = "ciit"; // set this field "" (empty quotes) if you have not se
$dbname = "pinevalley";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $p
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection successful";
?>
<table border="1">
<th>ProductID</th>
<th>ProductLineID</th>
<th>ProductDescription</th>
<th>ProductFinish</th>
<th>ProductStandardPrice</th>
<?php
foreach($conn->query('SELECT * FROM product_t') as $row) {
?>
<tr>
<td><?php echo $row[0]; ?></td>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
<td><?php echo $row[3]; ?></td>
<td><?php echo $row[4]; ?></td>
</tr>
<?php } ?>
</table>
<?php
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

</body>
</html>

Page 44
Created by Turbolearn AI

Example: updatedata.php

Page 45
Created by Turbolearn AI

<html>
<head>
</head>
<body>
<table border="1">
<tr>
<td><a href="index.php">Home</a></td>
<td><a href="selectdata.php"> Show Record </a></td>
<td><a href="updatedata.php"> Update Data</a></td>
</tr>
</table>
<?php
$servername = "localhost";
$username = "root";
$password = "ciit";
$dbname = "pinevalley";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $p
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection successful";

if( isset($_POST['btn']) ) {
$txt1 = $_POST['txt1'];
$txt2 = $_POST['txt2'];
$txt3 = $_POST['txt3'];
$txt4 = $_POST['txt4'];
$txt5 = $_POST['txt5'];

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

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

Page 46
Created by Turbolearn AI

</tr>
<tr>
<td>ProductFinish</td>
<td><input id="txt4" name="txt4" type="text" /></td>
</tr>
<tr>
<td>ProductStandardPrice</td>
<td><input id="txt5" name="txt5" type="text" /></td>
</tr>
<tr>
<td>Save Record</td>
<td><input id="btn" name="btn" type="submit" value="Save Record" /></t
</tr>
</table>
</form>
</body>
</html>

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

To avoid repeating data connection code, put it in one file (e.g., "opendb.php"):

<?php
$servername = "localhost";
$username = "root";
$password = "ciit"; // set this field "" (empty quotes) if you have not se
$dbname = "pinevalley";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $p
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection successful";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
?>

Then include this file in your other PHP files:

Page 47
Created by Turbolearn AI

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

How to Import an Excel Sheet into Database Table


1. Save the Excel file as a "Comma delimited CSV" file.

2. Create a table in the database with matching columns to the CSV file.

use test;
create table Categories(
Category_ID text,
Category_Type text,
Business_Title text,
Business_Description text,
Size text,
Tel text,
Email text,
City text,
Address text,
Google_Map_URL text,
Entered_by_ID text,
Entered_By_Name text
);

3. Open the command prompt window, navigate to the "bin" directory of your
MySQL in either wamp or xampp server. Example:

C:\\Users\\osmank> A:
A:\\> CD wamp\\bin\\mysql\\mysql5.6.17\\bin
A:\\ wamp\\bin\\mysql\\mysql5.6.17\\bin>mysql mysql>

4. Write the following command. Change the red colored path below to the exact
path of your CSV file.

Page 48
Created by Turbolearn AI

truncate Categories;
LOAD DATA LOCAL INFILE 'C:\\\\Users\\\\TEMP\\\\Downloads\\\\FA14-BSE-006f.
INTO TABLE exel
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\\r\\n'
IGNORE 1 LINES;

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.

To export database to a .sql file:

mysqldump --opt database_name > .sql file path

Example:

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

To import a database:

create schema test;

Then,

/ The below command is used to import a .sql database file in mysql. First create a
database named: test using command: create schema test; Then write the below
command */

Database Script for PineValley Database

Page 49
Created by Turbolearn AI

Database Script Notes


This section contains the database script for the PineValley database. Ensure you
remove any page numbers when copy-pasting this script to avoid errors. Also, verify
that the quotations used are of command-line syntax, as tilted quotations from word
processors can cause issues.

SQL Statements

Creating Tables

Page 50
Created by Turbolearn AI

Customer_T Table

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

Territory_T Table

CREATE TABLE Territory_T (


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

DoesBusinessIn_T Table

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
CONSTRAINT DoesBusinessIn_FK2 FOREIGN KEY (TerritoryID) REFERENCE
);

Employee_T Table

Page 51
Created by Turbolearn AI

CREATE TABLE Employee_T (


EmployeeID VARCHAR(10) NOT NULL,
EmployeeName VARCHAR(25),
EmployeeAddress VARCHAR(30),
EmployeeBirthDate DATE,
EmployeeCity VARCHAR(20),
EmployeeState CHAR(2),
EmployeeZip VARCHAR(10),
EmployeeDateHired DATE,
EmployeeSupervisor VARCHAR(10),
CONSTRAINT Employee_PK PRIMARY KEY (EmployeeID)
);

Skill_T Table

CREATE TABLE Skill_T (


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

EmployeeSkills_T Table

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
CONSTRAINT EmployeeSkills_FK2 FOREIGN KEY (SkillID) REFERENCES Sk
);

Order_T Table

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

WorkCenter_T Table

Page 52
Created by Turbolearn AI

CREATE TABLE WorkCenter_T (


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

ProductLine_T Table

CREATE TABLE ProductLine_T (


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

Product_T Table

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

ProducedIn_T Table

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 Prod
CONSTRAINT ProducedIn_FK2 FOREIGN KEY (WorkCenterID) REFERENCES W
);

OrderLine_T Table

Page 53
Created by Turbolearn AI

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
CONSTRAINT OrderLine_FK2 FOREIGN KEY (ProductID) REFERENCES Produ
);

RawMaterial_T Table

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

Salesperson_T Table

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

Vendor_T Table

Page 54
Created by Turbolearn AI

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

Supplies_T Table

CREATE TABLE Supplies_T (


VendorID int NOT NULL,
MaterialID VARCHAR(12) NOT NULL,
SuppliesUnitPrice DECIMAL(6,2),
CONSTRAINT Supplies_PK PRIMARY KEY (VendorID, MaterialID),
CONSTRAINT Supplies_FK1 FOREIGN KEY (MaterialId) REFERENCES RawMa
CONSTRAINT Supplies_FK2 FOREIGN KEY (VendorID) REFERENCES Vendor_
);

Uses_T Table

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(
CONSTRAINT Uses_FK2 FOREIGN KEY (MaterialID) REFERENCES RawMateri
);

WorksIn_T Table

Page 55
Created by Turbolearn AI

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 Employ
CONSTRAINT WorksIn_FK2 FOREIGN KEY (WorkCenterID) REFERENCES Work
);

Deleting Data
Deleting data from tables:

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;

Inserting Data

Page 56
Created by Turbolearn AI

Customer_T Table

INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, Cu


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

Territory_T Table

INSERT INTO Territory_T (TerritoryID, TerritoryName) VALUES (1, 'Sout


INSERT INTO Territory_T (TerritoryID, TerritoryName) VALUES (2, 'Sout
INSERT INTO Territory_T (TerritoryID, TerritoryName) VALUES (3, 'Nort
INSERT INTO Territory_T (TerritoryID, TerritoryName) VALUES (4, 'Nort
INSERT INTO Territory_T (TerritoryID, TerritoryName) VALUES (5, 'Cent

DoesBusinessIn_T Table

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

Employee_T Table

Page 57
Created by Turbolearn AI

INSERT INTO Employee_T (EmployeeID, EmployeeName, EmployeeAddress, Em


INSERT INTO Employee_T (EmployeeID, EmployeeName, EmployeeAddress, Em
Insert into Employee_T (EmployeeID,EmployeeName,EmployeeAddress,Emplo
Insert into Employee_T (EmployeeID,EmployeeName,EmployeeAddress,Emplo
Insert into Employee_T (EmployeeID,EmployeeName,EmployeeAddress,Emplo
Insert into Employee_T (EmployeeID,EmployeeName,EmployeeAddress,Emplo
Insert into Employee_T (EmployeeID,EmployeeName,EmployeeAddress,Emplo

Skill_T Table

INSERT INTO Skill_T (SkillID, SkillDescription) VALUES ('BS12', '12in


INSERT INTO Skill_T (SkillID, SkillDescription) VALUES ('QC1', 'Quali
INSERT INTO Skill_T (SkillID, SkillDescription) VALUES ('RT1', 'Route
INSERT INTO Skill_T (SkillID, SkillDescription) VALUES ('SO1', 'Sande
INSERT INTO Skill_T (SkillID, SkillDescription) VALUES ('SB1', 'Sande
INSERT INTO Skill_T (SkillID, SkillDescription) VALUES ('TS10', '10in
INSERT INTO Skill_T (SkillID, SkillDescription) VALUES ('TS12', '12in
INSERT INTO Skill_T (SkillID, SkillDescription) VALUES ('UC1', 'Uphol
INSERT INTO Skill_T (SkillID, SkillDescription) VALUES ('US1', 'Uphol
INSERT INTO Skill_T (SkillID, SkillDescription) VALUES ('UT1', 'Uphol

EmployeeSkills_T Table

INSERT INTO EmployeeSkills_T (EmployeeID, SkillID) VALUES ('123-44-34


INSERT INTO EmployeeSkills_T (EmployeeID, SkillID) VALUES ('123-44-34
INSERT INTO EmployeeSkills_T (EmployeeID, SkillID) VALUES ('454-56-76

Order_T Table

INSERT INTO Order_T (OrderID, OrderDate, CustomerID) VALUES (1001, '2


INSERT INTO Order_T (OrderID, OrderDate, CustomerID) VALUES (1002, '2
INSERT INTO Order_T (OrderID, OrderDate, CustomerID) VALUES (1003, '2
INSERT INTO Order_T (OrderID, OrderDate, CustomerID) VALUES (1004, '2
INSERT INTO Order_T (OrderID, OrderDate, CustomerID) VALUES (1005, '2
INSERT INTO Order_T (OrderID, OrderDate, CustomerID)VALUES (1006, '24
INSERT INTO Order_T (OrderID, OrderDate, CustomerID) VALUES (1007, '2
INSERT INTO Order_T (OrderID, OrderDate, CustomerID) VALUES (1008, '3
INSERT INTO Order_T (OrderID, OrderDate, CustomerID) VALUES (1009, '0
INSERT INTO Order_T (OrderID, OrderDate, CustomerID) VALUES (1010, '0

ProductLine_T Table

Page 58
Created by Turbolearn AI

INSERT INTO ProductLine_T (ProductLineID, ProductLineName) VALUES (1,


INSERT INTO ProductLine_T (ProductLineID, ProductLineName) VALUES (2,
INSERT INTO ProductLine_T (ProductLineID, ProductLineName) VALUES (3,

Product_T Table

INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish,


INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish,
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish,
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish,
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish,
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish,
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish,
INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish,

OrderLine_T Table

INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity) VALUES


INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity) VALUES
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity) VALUES
INSERT INTO OrderLine_T (OrderID, ProductID, OrderedQuantity)

Salesperson Table

INSERT INTO Salesperson_T (SalesPersonID, SalesPersonName, SalesPerso


INSERT INTO Salesperson_T (SalesPersonID, SalesPersonName, SalesPerso
INSERT INTO Salesperson_T (SalesPersonID, SalesPersonName, SalesPerso
INSERT INTO Salesperson_T (SalesPersonID, SalesPersonName, SalesPerso
INSERT INTO Salesperson_T (SalesPersonID, SalesPersonName, SalesPerso

WorkCenter_T Table

INSERT INTO WorkCenter_T (WorkCenterID, WorkCenterLocation) VALUES (


COMMIT;

Committing Transactions

Page 59
Created by Turbolearn AI

Committing the transactions to save all the changes:

COMMIT;

Page 60

You might also like