Lesson_12__Performance_Optimization_and_Best_Practices_in_SQL
Lesson_12__Performance_Optimization_and_Best_Practices_in_SQL
Practices in SQL
Learning Objectives
Problem Scenario:
A data analyst of a company wants to check the execution plan for a query to view the performance and
cost of the query.
Objective:
View the execution plan and create an index on the query to improve efficiency of the query.
Execution Plan in SQL
Creating exe_plan
QUERY
CREATE TABLE exe_plan (
ID int,
NAME varchar(255),
DESIGNATION varchar(255),
CITY varchar(255),
);
Execution Plan in SQL
QUERY
INSERT INTO sys.exe_plan
(ID,NAME,DESIGNATION,CITY) VALUES (‘3',
‘STEVE', 'LD', ‘Paris');
QUERY
QUERY
create index idx_word on exe_plan(NAME);
• It's a data type with a set • It's a data type with a • It's a data type with a
length. changeable length. changeable length.
• Each character is given • Each character takes one • Each character takes
one byte of space. byte of memory. two bytes of memory.
Index Guidelines
Index Guidelines
Choosing the right columns and types for an index is a crucial part of building a
useful index.
4 2
Keep separate
index keys
3
Keep selective
indexes
Index Guidelines
Keep index keys as The larger an index key gets, the harder it is for a database to use it.
An integer key is smaller than a character field that can carry 100 characters.
short as possible
Keep clustered indexes as short as possible.
Index Guidelines
Keep separate Indexes with a limited percentage of duplicated values are the most
effective. With a decent index, the database will be able to ignore as
index keys
many records as possible.
Index Guidelines
Keep selective A selective index has a lot of unique values. A unique index is the most
indexes selective of all the indexes, because there are no duplicate values.
Index Guidelines
You will need to see existing indexes as well as delete or rename them, in
Keeping indexes
addition to generating new ones. As the schema or even naming standards
up-to-date
change, this is part of the database's continual maintenance cycle.
Creating a Clustered Index in SQL
Clustered Index in SQL
A covered query is a query where all the columns in the query's result set are pulled
from non-clustered indexes.
Problem Scenario:
A data analyst wants to sort a table in order, with the help of a clustered index. Create a primary
key which acts as a clustered index in that table.
Objective:
Instructions:
Refer the emp_data table created before and perform the objectives.
Table Description
EMP_ID Employee ID
ROLE Designation of the employee (Junior, Senior, Lead, and Associate Data
Scientist)
Rating for the employee (1: Not Achieving Any Goals, 2: Below
EMP_RATING Expectations, 3: Meeting Expectations, 4: Excellent Performance, 5:
Overachiever
QUERY
CREATE TABLE
emp_data( `EMP_ID` Varchar NOT NULL, `FIRST_NAME` varchar(45) DEFAULT NULL, `
LAST_NAME` varchar(3) DEFAULT NULL, `GENDER` varchar(20) DEFAULT NULL, `ROLE`
varchar(25) DEFAULT NULL, `DEPT` varchar(25) DEFAULT NULL, `EXP` varchar(25)
DEFAULT NULL, `COUNTRY` varchar(25) DEFAULT NULL, `CONTINENT` varchar(25) DEFA
ULT NULL, `SALARY` INT DEFAULT NULL, `EMP_RATING` INT
DEFAULT NULL, `MANAGER_ID` varchar(25) DEFAULT NULL, PRIMARY KEY (`EMP_ID`)//
clustered index UNIQUE KEY `SALARY` (`SALARY`) ;
Clustered Index in SQL
Output
Assisted Practice: Covering Query
Duration: 15 min
Problem Statement: You are required to create the temperature as unique, add new index
columns, and view the index of the weather table for data integrity.
Assisted Practice: Covering Query
Steps to be performed:
Step 1 : Creating the weather table and inserting values in it:
CREATE
CREATE TABLE weather ( temp INT NOT NULL, windspeed varchar(45) NOT
NULL, vapour varchar(45) NOT NULL, climate varchar(45) NOT NULL );
INSERT
QUERY
QUERY
ALTER TABLE weather ADD INDEX index_co1_col2(windspeed,vapour,climate);
Assisted Practice: Covering Query
QUERY
Output :
Common Table Expression
Common Table Expression
SYNTAX
Problem Scenario:
A data analyst wants to apply a CTE to the table with first name, last name, and the country of the
person whose salary is greater than or equal to 4000.
Objective:
Implement the CTE to obtain the required result.
Instructions:
Refer the emp_data table which was created and shown before. Perform the objectives
mentioned above.
Common Table Expression
CTE QUERY
WITH emp_in_Germany AS
(
SELECT * FROM sys . emp_data WHERE COUNTRY = 'GERMANY'
)
SELECT FIRST_NAME , SALARY , COUNTRY from emp_in_Germany WHERE SALARY >= '4000’ order
by FIRST_NAME;
Common Table Expression
Output:
Assisted Practice: Common Table Expressions
Duration: 20 mins
Problem statement: You’ve been asked to train a junior analyst on Common Table Expressions (CTE).
You’ve been given a predefined problem to use. Using the data below, you need to guide the junior
analyst to write a query using CTE to fetch the count of unique policy number for policies in India.
Steps to be performed:
Step 01: Create the CLAIM table
SQL Query
CREATE TABLE CLAIM(
CUST_ID TEXT,
POLICY_NO TEXT,
COUNTRY_ID INT,
CLAIM_AMT INT
);
Assisted Practice: Common Table Expressions
Output:
Assisted Practice: Common Table Expressions
SQL Query
CREATE TABLE COUNTRY(
COUNTRY_ID INT,
NAME TEXT);
Assisted Practice: Common Table Expressions
Output:
Assisted Practice: Common Table Expressions
SQL Query
INSERT INTO CLAIM(CUST_ID,POLICY_NO,COUNTRY_ID,CLAIM_AMT)
VALUES("C","PO21",1,1000),
("C2","PO22",1,3200),
("C3","PO33",2,5000),
("C4","PO44",3,4500),
("C5","PO55",2,1200),
("C6","PO44",3,4500),
("C7","PO55",2,1200);
Assisted Practice: Common Table Expressions
Output:
Assisted Practice: Common Table Expressions
SQL Query
INSERT INTO COUNTRY(COUNTRY_ID, NAME)
VALUES(1,"US"),
(2,"India"),
(3,"UK");
Assisted Practice: Common Table Expressions
Output:
Assisted Practice: Common Table Expressions
SQL Query
SELECT * FROM CLAIM;
SELECT * FROM COUNTRY;
Assisted Practice: Common Table Expressions
Output:
Assisted Practice: Common Table Expressions
Step 06: Write a query using CTE to fetch the count of unique policy numbers in India
SQL Query
WITH India_ID AS
(SELECT COUNTRY_ID
FROM COUNTRY
WHERE NAME = 'India')
SELECT COUNT(DISTINCT POLICY_NO)
FROM CLAIM
WHERE COUNTRY_ID IN (SELECT COUNTRY_ID FROM India_ID)
Assisted Practice: Common Table Expressions
Output:
SQL Best Practices
SQL Best Practices
String Functions
SQL Best
Practices
SQL Best
Practices
Always check for NULLS in your data. This is one of the main SQL practices.
Knowledge
Check
Which of the following stores Unicode characters?
2
A. CHAR
B. VARCHAR
C. NVARCHAR
A. CHAR
B. VARCHAR
C. NVARCHAR
Index guidelines are keeping separate index keys and making them as short as possible.
Lesson-End Project: Airline Customer Expense Analysis
Problem statement:
You are working for an airline company and this company has organized an
SQL hackathon. You have been chosen to represent the LOYALTY team in the
hackathon.
Objective:
The challenge is to overcome the constraint of utilizing CTE to assess the time
period and customers based on spend patterns.
This analysis will help the company design attractive campaigns for low- and
high-spend customers, decide in which quarter deals should be completed,
etc.
Lesson-End Project: Airline Customer Expense Analysis
Tasks to be performed:
Step 01: Create a table containing the columns CustID, CustNAME, Quarter,
and TravelSpend and name it "customer_spend"
Tasks to be performed:
Step 05: Using CTE, find the specific quarter(s) when the spend was better
than the average spend across all quarters
Step 06: Using CTE, find the list of customers who have spent less than the
average spend of all customers
Step 07: Using CTE, find the list of customers who have spent more than the
average spend of all customers
Key Takeaways
Choosing the right columns and types for an index is a crucial part
of building a useful index.