SQL Tuning or SQL Optimization
SQL Tuning or SQL Optimization
Sql Statements are used to retrieve data from the database. We can get same
results by writing different sql queries. But use of the best query is important
when performance is considered. So you need to sql query tuning based on the
requirement. Here is the list of queries which we use reqularly and how these
sql queries can be optimized for better performance.
student_details;
Instead of:
2) HAVING clause is used to filter the rows after all the rows are selected. It is
just like a filter. Do not use HAVING clause for any other purposes.
For Example: Write the query as
SELECT subject, count(subject)
FROM student_details
GROUP BY subject;
Instead of:
FROM student_details
GROUP BY subject
3) Sometimes you may have more than one subqueries in your main query. Try
to minimize the number of subquery block in your query.
For Example: Write the query as
SELECT name
FROM employee
FROM employee_details)
Instead of:
SELECT name
FROM employee
4) Use operator EXISTS, IN and table joins appropriately in your query.
a) Usually IN has the slowest performance.
b) IN is efficient when most of the filter criteria is in the sub-query.
c) EXISTS is efficient when most of the filter criteria is in the main query.
For Example: Write the query as
Select * from product p
Instead of:
where product_id IN
5) Use EXISTS instead of DISTINCT when using joins which involves tables
having one-to-many relationship.
For Example: Write the query as
SELECT d.dept_id, d.dept
FROM dept d
d.dept);
Instead of:
6) Try to use UNION ALL in place of UNION.
For Example: Write the query as
SELECT id, first_name
FROM student_details_class10
UNION ALL
FROM sports_team;
Instead of:
FROM student_details_class10
UNION
FROM sports_team;
7) Be careful while using conditions in WHERE clause.
For Example: Write the query as
SELECT id, first_name, age FROM student_details WHERE age >
10;
Instead of:
= 10;
FROM student_details
Instead of:
FROM student_details
FROM student_details
Instead of:
FROM student_details
FROM product
WHERE unit_price BETWEEN MAX(unit_price) and
MIN(unit_price)
Instead of:
FROM product
FROM employee
Instead of:
FROM employee
FROM employee
Instead of:
SELECT id, name, salary
FROM employee
FROM student_details
Instead of:
FROM student_details
Instead of:
employee