CSIS 3300 W11 QueryOptimization
CSIS 3300 W11 QueryOptimization
6,7
11,
12,13
Full Join (Cross Join in MySQL)
All the rows from the left table which are not in right table are
included.
Example: SELECT * FROM Province LEFT OUTER JOIN City ON
City.provinceId = Province.provinceId Where City.provinceId
IS NULL;
Right Join
All the rows from the left table which are not in right table are
included.
SELECT * FROM City RIGHT OUTER JOIN Province ON City.provinceId =
Province.provinceId Where City.provinceId IS NULL;
Outer Join
Ref: http://www.mysqltutorial.org/mysql-self-join/
Lab
Can you do the similar exercise with Province and
Country tables?
Since we can’t use limit of 3 in the subquery after where clause, we can modify our query to
Query with a sub query
Explain
Selecting queries
Tips
Explain Statement
mysql> explain SELECT first_name, last_name FROM employees.employees where first_name like
'S%';
+----+-------------+-----------+-------+---------------+--------------+---------+------+-------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
+----+-------------+-----------+-------+---------------+--------------+---------+------+-------+--------------------------+
| 1 | SIMPLE | employees | range | fullname_ind | fullname_ind | 16 | NULL | 70858 | Using
where; Using index |
+----+-------------+-----------+-------+---------------+--------------+---------+------+-------+--------------------------+
Where clause
Use minimum number for conditions to get the specific result set you want
Remove unnecessary parentheses
((a AND b) AND c OR (((a AND b) AND (c AND d))))
(a AND b AND c) OR (a AND b AND c AND d)
(a AND b AND c)
Are all the conditions same? Yes, think why?
Constant folding
(a<b AND b=c) AND a=5
Use Limit 1 (or another limit) when you only need a subset.
Index columns which are used in where clause.
Indexing works best in text search if you are providing at least the first
character such as “where first_name like 'S%'”. A search like “where
first_name like ‘%S%'” might miss out on using index unless a fulltext search
is used.
Avoid Select *, its almost always better to specify column names.
Use Not NULL if you can (during schema design)
Fixed length (static) tables are faster to query
A fixed length table is one which does not use any of VARCHAR, TEXT, BLOB
for column types.
Tips
Storage engine
MyISAM
Good for read heavy (analytics kind of applications)
Doesn’t scale well for write heavy apps
Doesn’t support referential integrity and transactions
InnoDB
Slower than MyISAM but has more feature and can handle writes more efficiently
Has improved a lot lately so we should use InnoDB most of the times.
References
Graphics from:
http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/