of 112
7/24/2019 Database Queries (MySql)
1/112
1
Lab Manual
(Database Systems)
Dr. Osman Khalid
COMATS Institute of Information Technology, Abbottabad,
Pakistan
http://osman.pakproject.com
ContentsLAB 01Creating Configuring the database................................................................................................. 5
Command to see the existing databases in MySql Server ........................................................................ 6
Create a database and Populate values .................................................................................................... 6
LAB 02update database structure ........................................................................................................... 25
Command to show the tables in a database .......................................................................................... 26
Retrieve System Time: ............................................................................................................................ 26
Add Two Number: ................................................................................................................................... 26
CREATE NEW TABLE: ............................................................................................................................... 26
Adding/Dropping Primary Key: ............................................................................................................... 26
Adding Column and Drop Column from Table ........................................................................................ 26
LAB 03Change table structure/data ........................................................................................................ 28
Renaming Column in Table ..................................................................................................................... 29
Setting Default Value for a Column: ....................................................................................................... 29
Drop Table ............................................................................................................................................... 29
Empty Table: ........................................................................................................................................... 29
Delete a single row from table ................................................................................................................ 29
Delete all rows from table: ..................................................................................................................... 29
LAB 04data copying/deletion .................................................................................................................. 30
Transfer/Copy Data from table1 to table2 with same table structure ................................................... 31
7/24/2019 Database Queries (MySql)
2/112
2
Delete a single row from table:............................................................................................................... 31
UPDATE a row in table: ........................................................................................................................... 31
LAB 05Auto-increment primary key ........................................................................................................ 32
Creating an AUTO INCREMENT PRIMARY KEY: ....................................................................................... 33
Start Auto Increment with user specified value : ................................................................................... 33
LAB 06database indexes .......................................................................................................................... 35
Creating Indexes : ................................................................................................................................... 36
Drop Indexes : ......................................................................................................................................... 37
LAB 07create index on foreign keys ........................................................................................................ 38
Creating index on foreign key : ............................................................................................................... 39
LAB 08select clause in detail ................................................................................................................... 40
Clauses of the SELECT Statement: .......................................................................................................... 41
Two Special Keywords used in SELECT: ................................................................................................... 41
LAB 09Creating Alias in database ............................................................................................................ 43
Using Alias in SELECT Statement: ............................................................................................................ 44
LAB 10sorting the data ............................................................................................................................ 45
Rearranging column Order in SELECT Query: ......................................................................................... 46
LAB 11using expressions and functions .................................................................................................. 47
Using Expressions:................................................................................................................................... 48
Using Functions: ...................................................................................................................................... 48
LAB 12built-in functions .......................................................................................................................... 50
COUNT : Returns single row .................................................................................................................... 51
Difference between COUNT(*) and COUNT(ColumnName) ................................................................... 51
LAB 13NULL values .................................................................................................................................. 53
Using Comparison Operators .................................................................................................................. 54
Using NULL Values .................................................................................................................................. 54
LAB 14logical operators ........................................................................................................................... 55
Using Boolean Operators (Logical Operators): ....................................................................................... 56
Using Ranges for Qualification: ............................................................................................................... 56
Using DISTINCT values: ........................................................................................................................... 57
LAB 15understanding in and not in ......................................................................................................... 58
Using IN and NOT IN Lists: ...................................................................................................................... 59
7/24/2019 Database Queries (MySql)
3/112
3
Sorting Results: The ORDER BY Clause ................................................................................................... 59
LAB 16the use of limit operator ........................................................................................................... 60
Using LIMIT :............................................................................................................................................ 61
LAB 17Group by and having clause ......................................................................................................... 62
Categorizing Results: The GROUP BY Clause: ......................................................................................... 63
Qualify Results by Categories: ................................................................................................................ 63
LAB 18defining views............................................................................................................................... 65
Using and Defining Views: ...................................................................................................................... 66
LAB 19queries involving multiple tables ................................................................................................. 67
Processing Multiple Tables: .................................................................................................................... 68
LAB 20different types of joins ................................................................................................................. 69
Outer Join: ............................................................................................................................................... 70
Left OUTER Join ....................................................................................................................................... 70
LAB 21Self join ......................................................................................................................................... 72
Sample join Involving four tables: ........................................................................................................... 73
Self Join: .................................................................................................................................................. 73
LAB 22Subqueries .................................................................................................................................... 75
Subqueries .............................................................................................................................................. 76
LAB 23in, not in, exists, not exists ........................................................................................................... 78
Using the NOT IN qualifier: ..................................................................................................................... 79
Using EXISTS and NOT EXISTS: ................................................................................................................ 79
EXISTS versus IN and NOT EXISTS versus NOT IN. ................................................................................... 79
LAB 24derived tables and sub-queries .................................................................................................... 81
Correlated Subqueries: ........................................................................................................................... 82
Using Derived Tables: .............................................................................................................................. 82
LAB 25union operator & type conversion ............................................................................................... 83
Union Operator: ...................................................................................................................................... 84
Data Type Conversion: ............................................................................................................................ 84
LAB 26conditional expression and trigger ............................................................................................... 85
Conditional Expressions: ......................................................................................................................... 86
Triggers.................................................................................................................................................... 86
LAB 27introduction to stored procedures ............................................................................................... 89
7/24/2019 Database Queries (MySql)
4/112
4
Stored Procedures: ................................................................................................................................. 90
LAB 28stored proceduresingle input ................................................................................................... 91
STORED PROCEDURE WITH A SINGLE INPUT PARAMETER ..................................................................... 92
LAB 29stored procedures input/output ............................................................................................... 93
STORED PROCEDURE WITH A SINGLE INPUT and A SINGLE OUTPUT PARAMETER................................ 94
LAB 30stored procedure returning values .............................................................................................. 95
STORED PROCEDURE WITH A SINGLE INPUT PARAMETER and TWO OUTPUT PARAMETERS ............... 96
LAB 31using mysql functions ................................................................................................................... 97
MySQL FUNCTIONS ................................................................................................................................. 98
LAB 32Connecting mysql with php .......................................................................................................... 99
CONNECTING PHP with MySQL............................................................................................................. 100
7/24/2019 Database Queries (MySql)
5/112
5
LAB 01CREATING 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.
7/24/2019 Database Queries (MySql)
6/112
6
Command to see the existing databases in MySql Server
SHOW DATABASES;
Create a database and Populate values
In this lab we will learn the following:
Creation of database Pineview
Creation of tables
Setting up of constraints
Inserting values in tables.
STEP-1
COPY - PASTE THE BELOW COMMANDS IN QUERY EDITOR
CREATE SCHEMA PINEVIEW;
STEP-2
COPY - PASTE THE BELOW COMMANDS IN QUERY EDITOR
use pineview;
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) ,
7/24/2019 Database Queries (MySql)
7/112
7
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 ,
EmployeeCity VARCHAR(20) ,
EmployeeState CHAR(2) ,
EmployeeZip VARCHAR(10) ,
EmployeeDateHired DATE ,
EmployeeSupervisor VARCHAR(10) ,
CONSTRAINT Employee_PK PRIMARY KEY (EmployeeID));
7/24/2019 Database Queries (MySql)
8/112
8
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));
7/24/2019 Database Queries (MySql)
9/112
9
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));
7/24/2019 Database Queries (MySql)
10/112
10
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));
7/24/2019 Database Queries (MySql)
11/112
11
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));
7/24/2019 Database Queries (MySql)
12/112
12
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 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));
7/24/2019 Database Queries (MySql)
13/112
13
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');
7/24/2019 Database Queries (MySql)
14/112
14
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');
7/24/2019 Database Queries (MySql)
15/112
15
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');
INSERT INTO Territory_T (TerritoryID, TerritoryName)
VALUES (5, 'Central');
7/24/2019 Database Queries (MySql)
16/112
16
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,EmployeeDateHired,E
mployeeBirthDate,EmployeeSupervisor)
values ('123-44-346','Phil Morris','2134 Hilltop Rd','Knoxville','TN',null,'12-JUN-99' ,'12-JUN-99','454-56-768');
7/24/2019 Database Queries (MySql)
17/112
17
Insert into Employee_T
(EmployeeID,EmployeeName,EmployeeAddress,EmployeeCity,EmployeeState,EmployeeZip,EmployeeDateHired,E
mployeeBirthDate,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,EmployeeDateHired,E
mployeeBirthDate,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,EmployeeDateHired,E
mployeeBirthDate,EmployeeSupervisor)
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,EmployeeDateHired,E
mployeeBirthDate,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');
7/24/2019 Database Queries (MySql)
18/112
18
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');
7/24/2019 Database Queries (MySql)
19/112
19
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)
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');
7/24/2019 Database Queries (MySql)
20/112
20
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);
7/24/2019 Database Queries (MySql)
21/112
21
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)
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);
7/24/2019 Database Queries (MySql)
22/112
22
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');
INSERT INTO WorkCenter_T (WorkCenterID, WorkCenterLocation)
7/24/2019 Database Queries (MySql)
23/112
23
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');
*/
describe Uses_T;
describe WorksIn_T;
describe WorkCenter_T;
describe DoesBusinessIn_T;
describe EmployeeSkills_T;
describe Supplies_T;
describe ProducedIn_T;
describe OrderLine_T;
describe Product_T;
describe ProductLine_T;
describe Order_T;
describe Salesperson_T;
describe Vendor_T;
describe Skill_T;
describe RawMaterial_T;
describe Territory_T;
7/24/2019 Database Queries (MySql)
24/112
24
describe Employee_T;
describe Customer_T;
select * from Uses_T;
select * from WorksIn_T;
select * from WorkCenter_T;
select * from DoesBusinessIn_T;
select * from EmployeeSkills_T;
select * from Supplies_T;
select * from ProducedIn_T;
select * from OrderLine_T;
select * from Product_T;
select * from ProductLine_T;
select * from Order_T;
select * from Salesperson_T;
select * from Vendor_T;
select * from Skill_T;
select * from RawMaterial_T;
select * from Territory_T;
select * from Employee_T;
select * from Customer_T;
COMMIT;
7/24/2019 Database Queries (MySql)
25/112
25
LAB 02UPDATE 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.
7/24/2019 Database Queries (MySql)
26/112
26
Command to show the tables in a databaseUse PineView;
SHOW TABLES;
Retrieve System Time:
SELECT CURTIME();
Add Two Number:
SELECT8+4;
CREATE NEW TABLE:
CREATE TABLE temp(
IDINT,
NameVARCHAR(10)
);
DESCRIBE temp;
Adding/Dropping Primary Key:
ALTER TABLE temp ADD CONSTRAINT pk_ID PRIMARY KEY (id);
ALTER TABLE temp DROP PRIMARY KEY;
Adding Column and Drop Column from Table
ALTER TABLEtemp
ADD COLUMN address VARCHAR(100);
ALTER TABLE temp
7/24/2019 Database Queries (MySql)
27/112
27
DROP COLUMN address;
7/24/2019 Database Queries (MySql)
28/112
28
LAB 03CHANGE 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.
7/24/2019 Database Queries (MySql)
29/112
29
Renaming Column in Table
ALTER TABLE temp
CHANGE COLUMN address
area VARCHAR(10);
Setting Default Value for a Column:
ALTER TABLEtemp
ADD COLUMNcity VARCHAR(100) DEFAULT 'ABC';
Drop Table
drop table temp;
Empty Table:
TRUNCATE child
Delete a single row from table
DELETE FROM child where id = 3;
Delete all rows from table:
TRUNCATE child
7/24/2019 Database Queries (MySql)
30/112
30
LAB 04DATA 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.
7/24/2019 Database Queries (MySql)
31/112
31
Transfer/Copy Data from table1 to table2 with same
table structure
Populating a table (CHILD) by using subset of another table (PARENT) with the same structure.
INSERT INTO child
SELECT * FROM PARENT;
Delete a single row from table:
DELETE FROM temp WHERE id=111;
Whereexpression 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.
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.
7/24/2019 Database Queries (MySql)
32/112
32
LAB 05AUTO-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.
7/24/2019 Database Queries (MySql)
33/112
33
Creating an AUTO INCREMENT PRIMARY KEY:
CREATE TABLEPERSONS(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 IDfor the first row i.e. 11
and we did not give any ID for the second row. And it automatically incremented the next row
IDbased 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;
7/24/2019 Database Queries (MySql)
34/112
34
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 IDof the next row inserted starts from 100 , as altered.
7/24/2019 Database Queries (MySql)
35/112
35
LAB 06DATABASE 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.
7/24/2019 Database Queries (MySql)
36/112
36
Creating Indexes :
Indexesare created in RDBMS to provide rapid and sequential access to base table data.
Indexesare usually be created both for primary and secondary keys and both single andconcatenated (multiple column keys).
Example:
To see the structure of a table we use DESCRIBE command
DESCRIBECUSTOMER_T;
/* below command create index */
CREATE INDEX Name_IDX ONCUSTOMER_T (CUSTOMERNAME) ;
To see the structure of a table we use DESCRIBE command
DESCRIBECUSTOMER_T;
7/24/2019 Database Queries (MySql)
37/112
37
Drop Indexes :
To remove index on the customer name in the table.
DROP INDEX Name_IDX ONCUSTOMER_T;
And describe table to see the index dropped.
7/24/2019 Database Queries (MySql)
38/112
38
LAB 07CREATE INDEX ON FOREIGN KEYS
Objectives:
Students will understand the relation of indexes with a tables foreign
keys. Students will learn how to create indexes on foreign key, and how
to drop a foreign key index
7/24/2019 Database Queries (MySql)
39/112
39
Creating index on foreign key :
Create two tables:
CREATE TABLE MASTER(
MID VARCHAR(5) PRIMARY KEY,
TYPE VARCHAR(10)
);
CREATE TABLEDETAIL(
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, andwe have to delete the index manually.
7/24/2019 Database Queries (MySql)
40/112
40
LAB 08SELECT 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.
7/24/2019 Database Queries (MySql)
41/112
41
Clauses of the SELECT Statement:
SELECT: lists the columns (including expressions involving columns i.e.age+10) from basetables, 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
7/24/2019 Database Queries (MySql)
42/112
42
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;
7/24/2019 Database Queries (MySql)
43/112
43
LAB 09CREATING ALIAS IN DATABASE
Objectives:
Student will learn how to create a table alias, and a tables field alias.
7/24/2019 Database Queries (MySql)
44/112
44
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 tables 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. Namefor CusomterNameand Addressfor
CustmerAddress.
7/24/2019 Database Queries (MySql)
45/112
45
LAB 10SORTING THE DATA
Objectives:
Students will learn how to sort table data using ORDER BY clause.
7/24/2019 Database Queries (MySql)
46/112
46
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;
7/24/2019 Database Queries (MySql)
47/112
47
LAB 11USING EXPRESSIONS AND FUNCTIONS
Objectives:
Students will learn how to use expressions and functions in select
queries.
7/24/2019 Database Queries (MySql)
48/112
48
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
7/24/2019 Database Queries (MySql)
49/112
49
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 dateDAY() : 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;
7/24/2019 Database Queries (MySql)
50/112
50
LAB 12BUILT-IN FUNCTIONS
Objectives:
Students will understand the use of some of the built-in functions, such
as COUNT, MIN, and MAX.
7/24/2019 Database Queries (MySql)
51/112
51
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)
7/24/2019 Database Queries (MySql)
52/112
52
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_namein 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)
7/24/2019 Database Queries (MySql)
53/112
53
LAB 13NULL VALUES
Objectives:
Students will learn the work of various comparison operators, and the
use of NULL keyword.
7/24/2019 Database Queries (MySql)
54/112
54
Using Comparison OperatorsQuery: 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
codethere 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 ISNULL;
/*below query returns all rows for which CustomerPostalCode does not contains NULL
value*/
SELECT * FROM CUSTOMER_T WHERE CustomerPostalCode ISNOT NULL;
7/24/2019 Database Queries (MySql)
55/112
55
LAB 14LOGICAL 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.
7/24/2019 Database Queries (MySql)
56/112
56
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%' ) ANDProductStandardPrice > 300.00 ;
The LIKEoperator 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.
7/24/2019 Database Queries (MySql)
57/112
57
SELECT ProductDescription, ProductFinish, ProductStandardPrice FROM PRODUCT_T WHERE
ProductStandardPrice >= 200.00 AND ProductStandardPrice
7/24/2019 Database Queries (MySql)
58/112
58
LAB 15UNDERSTANDING 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.
7/24/2019 Database Queries (MySql)
59/112
59
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 secondaryWHERE 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 ;
7/24/2019 Database Queries (MySql)
60/112
60
LAB 16THE USE OF LIMIT OPERATOR
Objectives:
The students will understand the benefit and use of LIMIT operator.
7/24/2019 Database Queries (MySql)
61/112
61
Using LIMIT :LIMITis used to limitto limit/constraint the number of results returned, or to give a range ofrows 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, 1LIMIT 3, 5;
This will skip the first 3rows and return next 5rows.
7/24/2019 Database Queries (MySql)
62/112
62
LAB 17GROUP BY AND HAVING CLAUSE
Objectives:
In this lab, students will learn the use of GROUP BY and HAVING clause.
7/24/2019 Database Queries (MySql)
63/112
63
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 HAVINGclause acts like a WHEREclause, but it identifies groups, rather than rows, that
meet a criterion. Before, we usually see a HAVING clause following by a GROUP BY.
7/24/2019 Database Queries (MySql)
64/112
64
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)
7/24/2019 Database Queries (MySql)
65/112
65
LAB 18DEFINING VIEWS
Objectives:
The students will understand the basics of views and how to define
views.
7/24/2019 Database Queries (MySql)
66/112
66
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 thisquery 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, OrderedQuantityFROM Invoice_VWHERE
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;
7/24/2019 Database Queries (MySql)
67/112
67
LAB 19QUERIES INVOLVING MULTIPLE TABLES
Objectives:
This lab will teach the students how to write queries on multiple tables,
how to use INNER JOIN.
7/24/2019 Database Queries (MySql)
68/112
68
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: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;
INNER JOIN.ONare 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;
7/24/2019 Database Queries (MySql)
69/112
69
LAB 20DIFFERENT TYPES OF JOINS
Objectives:
Students will learn how to use different types of joins, left outer join,
right outer join
7/24/2019 Database Queries (MySql)
70/112
70
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 JoinQuery: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;
7/24/2019 Database Queries (MySql)
71/112
71
This query will also return the rows in which the foreign key column does not exist i.e. NULL, for
any row
7/24/2019 Database Queries (MySql)
72/112
72
LAB 21SELF JOIN
Objectives:
The objective of this lab is to teach how to use SELF JOIN, and running
query involving 4 tables.
7/24/2019 Database Queries (MySql)
73/112
73
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 sametablethat 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 supervisors name with manager)?
SELECT
E.EmployeeID,
E.EmployeeName,
M.EmployeeName AS Manager FROM
Employee_T E, Employee_T M
7/24/2019 Database Queries (MySql)
74/112
74
WHERE
E.EmployeeSupervisor = M.EmployeeID;
7/24/2019 Database Queries (MySql)
75/112
75
LAB 22SUBQUERIES
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.
7/24/2019 Database Queries (MySql)
76/112
76
SubqueriesThe 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 ofthe 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?
SELECTCustomerName, CustomerAddress, CustomerCity, CustomerState,
CustomerPostalCode
FROMCustomer_T, Order_T
WHERECustomer_T.CustomerID = Order_T. CustomerID
ANDOrderID = 1008;
Query (Sub-query):What are the name and address of the customer who placed order number1008?
SELECTCustomerName, CustomerAddress, CustomerCity,CustomerState,
CustomerPostalCode
FROMCustomer_T
WHERECustomer_T.CustomerID =
(SELECTOrder_T.CustomerID
FROMOrder_T
WHEREOrderID = 1008);
Query:What are the names of customers who have placed orders?
7/24/2019 Database Queries (MySql)
77/112
77
SELECTCustomerName
FROMCustomer_T
WHERECustomerID IN
(SELECT DISTINCTCustomerID
FROM Order_T);
7/24/2019 Database Queries (MySql)
78/112
78
LAB 23IN, 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.
7/24/2019 Database Queries (MySql)
79/112
79
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:EXISTSwill 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 arereturned
EXISTS versus IN and NOT EXISTS versus NOT IN.WE use EXISTSwhen we just want to check whether the sub query returns a non-empty set (i.e
we dont care what is in the set, just whether it is empty), and we use INwhen we need to
know what values are in the.
IN and NOT INreturn a set of values from only one column which can be then compared to one
column in the outer query.
EXISTS and NOT EXISTSreturn only true or false value depending on whether there are any
rows in the answer table of the inner query or sub query.
7/24/2019 Database Queries (MySql)
80/112
80
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'
);
7/24/2019 Database Queries (MySql)
81/112
81
LAB 24DERIVED TABLES AND SUB-QUERIES
Objectives:
The purpose of this lab is to familiarize students with queries involving
derived tables, and the correlated sub queries.
7/24/2019 Database Queries (MySql)
82/112
82
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 TRUEif the comparison
is TRUEfor ALLof 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;
7/24/2019 Database Queries (MySql)
83/112
83
LAB 25UNION 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.
7/24/2019 Database Queries (MySql)
84/112
84
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;
7/24/2019 Database Queries (MySql)
85/112
85
LAB 26CONDITIONAL EXPRESSION AND TRIGGER
Objectives:
This lab will introduce students with conditional expressions, as well as
how we can define and use triggers in MySQL.
7/24/2019 Database Queries (MySql)
86/112
86
Conditional Expressions:IF-THEN-ELSE
CASE Keyword
Query:
SELECT
CASE
WHEN ProductLineID=1 THEN ProductDescription
ELSE '###'
END AS ProductDescription
FROM Product_t;
TriggersA 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 youneed 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 partsthe event, the condition, and the
actionand 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 pineview;
7/24/2019 Database Queries (MySql)
87/112
87
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 pineview;
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;
7/24/2019 Database Queries (MySql)
88/112
88
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. Thats 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);
7/24/2019 Database Queries (MySql)
89/112
89
LAB 27INTRODUCTION TO STORED PROCEDURES
Objectives:
This lab introduces the stored procedures and discuss several examples
of how effectively can we use stored procedures in MySQL.
7/24/2019 Database Queries (MySql)
90/112
90
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();
7/24/2019 Database Queries (MySql)
91/112
91
LAB 28STORED PROCEDURESINGLE INPUT
Objectives:
The purpose of this lab is to make students learn how we can pass a
single argument to stored procedures.
7/24/2019 Database Queries (MySql)
92/112
92
STORED PROCEDURE WITH A SINGLE INPUT
PARAMETERThe 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)
7/24/2019 Database Queries (MySql)
93/112
93
LAB 29STORED PROCEDURESINPUT/OUTPUT
Objectives:
In this lab students will lab, how can pass single input and output single
value from stored procedures.
7/24/2019 Database Queries (MySql)
94/112
94
STORED PROCEDURE WITH A SINGLE INPUT and A
SINGLE OUTPUT PARAMETERThe 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.
7/24/2019 Database Queries (MySql)
95/112
95
LAB 30STORED 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.
7/24/2019 Database Queries (MySql)
96/112
96
STORED PROCEDURE WITH A SINGLE INPUT
PARAMETER and TWO OUTPUT PARAMETERSCREATE 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.
7/24/2019 Database Queries (MySql)
97/112
97
LAB 31USING 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.
7/24/2019 Database Queries (MySql)
98/112
98
MySQL FUNCTIONSA 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);
7/24/2019 Database Queries (MySql)
99/112
99
LAB 32CONNECTING 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.
7/24/2019 Database Queries (MySql)
100/112
100
CONNECTING PHP with MySQLMake sure you have pineview 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
Home
Show Record
Update Data
7/24/2019 Database Queries (MySql)
101/112
101
THIS IS HOME PAGE
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
This is data selection page
Home
Show Record
Update Data
7/24/2019 Database Queries (MySql)
102/112
102
$servername = "localhost";
$username = "root";
$password = "ciit"; // set this field ""(empty quotes) if you have not set any password in mysql
$dbname = "pineview";
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";
?>
ProductID
ProductLineID
ProductDescription
ProductFinish
ProductStandardPrice
7/24/2019 Database Queries (MySql)
103/112
103
7/24/2019 Database Queries (MySql)
104/112
104
Step-6: Create file updatedata.php and put following code in that.
updatedate.php
Home
Show Record
Update Data
7/24/2019 Database Queries (MySql)
105/112
105
$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)";
7/24/2019 Database Queries (MySql)
106/112
106
// use exec() because no results are returned
$conn->exec($sql);
echo "\nTable product_t updated successfully";
}
}
catch(PDOException $e)
{
echo $sql . "
" . $e->getMessage();
}
$conn = null;
?>
This is test php page
ProductID
7/24/2019 Database Queries (MySql)
107/112
107
ProductLineID
ProductDescription
ProductFinish
ProductStandardPrice
Save Record
7/24/2019 Database Queries (MySql)
108/112
108
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
7/24/2019 Database Queries (MySql)
109/112
109
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 . "
" . $e->getMessage();
}
?>
Now, as a sample code, you can re-write the selectdata.php file as:
selectdata.php
7/24/2019 Database Queries (MySql)
110/112
110
Home
Show Record
Update Data
ProductID
ProductLineID
ProductDescription
ProductFinish
ProductStandardPrice
7/24/2019 Database Queries (MySql)
111/112
111
7/24/2019 Database Queries (MySql)
112/112
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.
------- THE END OF LAB MANUAL ----------