Lecture 3 - Query Optimization
Lecture 3 - Query Optimization
Technologies
Lecture 3: Query Optimization
Dr. Lupiana, D
FCIM, InsEtute of Finance Management
Semester 1
Agenda:
• EXPLAIN
• OpEmizaEon Techniques
EXPLAIN
• The EXPLAIN statement provides informaEon
about how MySQL executes statements
• When used, MySQL displays informaEon from
the opEmizer about the execuEon plan
– It explains how it would process the statement,
including informaEon about how tables are joined
and in which order
1
EXPLAIN
• EXPLAIN works with SELECT, DELETE, INSERT,
REPLACE, and UPDATE statements
• EXPLAIN returns a row of informaEon for each
table used in the SELECT statement
– Tables are listed in the output in the order they
were read while processing the statement
– This means that MySQL reads a row from the first
table, then finds a matching row in the second
table, and then in the third table, and so on
4
EXPLAIN
• When all tables are processed, MySQL outputs
the selected columns and backtracks through
the table list unEl a table is found for which
there are more matching rows
• . The next row is read from this table and the
process conEnues with the next table.
2
EXPLAIN
• MySQL Workbench has a Visual Explain
capability that provides a visual
representaEon of EXPLAIN output
• The next row is read from this table and the
process conEnues with the next table.
EXPLAIN
• With the help of EXPLAIN, you can see where
you should add indexes to tables so that the
statement executes faster by using indexes to
find rows
3
OpEmizaEon Techniques: Specific Columns
• Database uses resources to retrieve data from
a table and therefore the more columns are
retrieved the more resources are used
• Therefore, specify only columns that you real
want to use its data
10
11
12
4
… Using Index: Create Index
• An index can be created using the following
syntax;
CREATE INDEX index_name ON
table_name(column_name)
13
14
15
5
OpEmizaEon Techniques: Leading Wildcards
• LIKE clause in SQL is used to provide more
flexibility when your condiEon is searching for
a keyword or sequence of characters
• LIKE clause uses wildcards (i.e. ‘%’ symbol) to
imply ‘any character’
– For example names LIKE ‘%;n’ means searching for
names that starts with combinaEon of any le`ers
but ends with ‘En’
16
17
18
6
OpEmizaEon Techniques: Leading Wildcards
• Thus to opEmize a query avoid using LIKE
clause and if it is necessary DO NOT use
leading wildcards
19
20
21
7
OpEmizaEon Techniques: ‘UNION’ Over ‘OR’
• With UNION, a query is separated to two or
more queries depending on condiEons
– Thus indexes of columns used in the condiEons
will all be used thus increasing performance
22
23