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.
SQL Tuning/SQL Optimization Techniques:
1) The sql
query becomes faster if you use the actual columns names in SELECT statement
instead of than '*'.
For Example: Write the query as
SELECT id, first_name, last_name, age,
subject FROM student_details;
Instead of:SELECT * FROM student_details;
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
WHERE subject != 'Science'
AND subject != 'Maths'
GROUP BY subject;
Instead of:
SELECT subject, count(subject)
FROM student_details
GROUP BY subject HAVING subject!= 'Vancouver' AND subject!= 'Toronto';
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
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age)
FROM employee_details)
AND dept = 'Electronics';
Instead of:
SELECT name
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee_details)
AND age = (SELECT MAX(age) FROM employee_details)
AND emp_dept = 'Electronics';
For Example: Write the query as
SELECT name
FROM employee
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age)
FROM employee_details)
AND dept = 'Electronics';
Instead of:
SELECT name
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee_details)
AND age = (SELECT MAX(age) FROM employee_details)
AND emp_dept = 'Electronics';
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.
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
where EXISTS (select * from order_items o where o.product_id = p.product_id)
Instead of:
Select * from product p
where product_id IN (select product_id from order_items )
Select * from product p
where EXISTS (select * from order_items o where o.product_id = p.product_id)
Instead of:
Select * from product p
where product_id IN (select product_id from order_items )
Src: http://beginner-sql-tutorial.com/sql-query-tuning.htm
No comments:
Post a Comment