SQL Tuning
SQL Tuning
1) The sql query becomes faster if you use the actual columns names in SELECT statement
instead of than '*'.
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
Instead of:
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';
Instead of:
5) Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-
many relationship.
For Example: Write the query as
Instead of:
Instead of:
SELECT id, first_name, subject
FROM student_details_class10
UNION
SELECT id, first_name
FROM sports_team;
SELECT id, first_name, age FROM student_details WHERE age > 10;
Instead of:
Instead of:
Instead of:
Instead of:
SELECT product_id, product_name
FROM product
WHERE unit_price >= MAX(unit_price)
and unit_price <= MIN(unit_price)
Instead of:
Use non-column expression on one side of the query because it will be processed earlier.
Instead of:
Instead of:
8) Use DECODE to avoid the scanning of same rows or joining the same table repetitively.
DECODE can also be made used in place of GROUP BY or ORDER BY clause.
For Example: Write the query as
9) To store large binary objects, first place them in the file system and add the file path in the
database.
10) To write queries which provide efficient performance follow the general SQL standard rules.