Query Processing and Optimization -Lab-PP
Query Processing and Optimization -Lab-PP
Part-I
Step-by-Step Lab Activity
Objective
- Understanding what database performance
- Demonstrating performance improvement techniques
General Tasks:
1|Page
Advanced Database Lab-Query Processing and Optimization
2|Page
Advanced Database Lab-Query Processing and Optimization
-- Insert Customers
INSERT INTO Customers (FirstName, LastName, Email, RegistrationD
ate)
VALUES
('John', 'Doe', 'john.doe@example.com', '2023-01-15'),
('Jane', 'Smith', 'jane.smith@example.com', '2023-02-20'),
('Alice', 'Johnson', 'alice.j@example.com', '2023-03-10');
-- Insert Products
INSERT INTO Products (ProductName, Category, Price, StockQuantit
y)
VALUES
('Laptop', 'Electronics', 999.99, 50),
('Smartphone', 'Electronics', 699.99, 100),
('Headphones', 'Accessories', 99.99, 200);
-- Insert Orders
INSERT INTO Orders (CustomerID, OrderDate, TotalAmount)
VALUES
(1, '2023-04-01', 999.99),
(2, '2023-04-02', 799.98),
(3, '2023-04-03', 99.99);
-- Insert OrderDetails
INSERT INTO OrderDetails (OrderID, ProductID, Quantity, UnitPric
e)
VALUES
(1, 1, 1, 999.99),
(2, 2, 1, 699.99),
(2, 3, 1, 99.99),
(3, 3, 1, 99.99);
3|Page
Advanced Database Lab-Query Processing and Optimization
Problem:
4|Page
Advanced Database Lab-Query Processing and Optimization
Improvements:
5|Page
Advanced Database Lab-Query Processing and Optimization
6|Page
Advanced Database Lab-Query Processing and Optimization
Part-II
o Note: The Exercises below are prepared Based on the Database
AdvanureWorks2019, you can use 2014, 2016 or earlier versions of Database.
Exercise 1: Query Rewriting: Join Reordering
• Joining smaller tables first reduces intermediate result size.
• Original (large table first)
USE AdventureWorks2019
SELECT * FROM Sales.SalesOrderHeader soh
JOIN Sales.SalesOrderDetail sod ON soh.SalesOrderID =
sod.SalesOrderID;
Original Execution Plan Result
o Check the cost of each Parse Tree-node and compare with the
optimized one, what did you observe?
o Check the time difference from the actual execution plan in second.
o You might observe different result based
7|Page
Advanced Database Lab-Query Processing and Optimization
Optimized Query
SELECT SalesOrderID, OrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate BETWEEN '2011-06-01' AND '2011-06-30';
Execution Plan Result from Optimized Query
8|Page
Advanced Database Lab-Query Processing and Optimization
9|Page
Advanced Database Lab-Query Processing and Optimization
o Please observe the result you will get by executing the two
queries and check their cost difference.
10 | P a g e