Sunday, November 4, 2012

SQL Tuning/SQL Optimization Techniques


            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';

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 
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

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 
WHERE EXISTS ( SELECT 'X' FROM employee e WHERE e.dept = d.dept);
Instead of:
SELECT DISTINCT d.dept_id, d.dept 
FROM dept d,employee e 
WHERE e.dept = e.dept;

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 
SELECT id, first_name 
FROM sports_team;
Instead of:
SELECT id, first_name, subject 
FROM student_details_class10 
UNION 
SELECT id, first_name 
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:
SELECT id, first_name, age FROM student_details WHERE age != 10;
Write the query as
SELECT id, first_name, age 
FROM student_details 
WHERE first_name LIKE 'Chan%';
Instead of:
SELECT id, first_name, age 
FROM student_details 
WHERE SUBSTR(first_name,1,3) = 'Cha';
Write the query as
SELECT id, first_name, age 
FROM student_details 
WHERE first_name LIKE NVL ( :name, '%');
Instead of:
SELECT id, first_name, age 
FROM student_details 
WHERE first_name = NVL ( :name, first_name);
Write the query as
SELECT product_id, product_name 
FROM product 
WHERE unit_price BETWEEN MAX(unit_price) and MIN(unit_price)
Instead of:
SELECT product_id, product_name 
FROM product 
WHERE unit_price >= MAX(unit_price) 
and unit_price <= MIN(unit_price)
Write the query as
SELECT id, name, salary 
FROM employee 
WHERE dept = 'Electronics' 
AND location = 'Bangalore';
Instead of:
SELECT id, name, salary 
FROM employee 
WHERE dept || location= 'ElectronicsBangalore';
Use non-column expression on one side of the query because it will be processed earlier.
Write the query as
SELECT id, name, salary 
FROM employee 
WHERE salary < 25000;
Instead of:
SELECT id, name, salary 
FROM employee 
WHERE salary + 10000 < 35000;
Write the query as
SELECT id, first_name, age 
FROM student_details 
WHERE age > 10;
Instead of:
SELECT id, first_name, age 
FROM student_details 
WHERE age NOT = 10;
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
SELECT id FROM employee 
WHERE name LIKE 'Ramesh%' 
and location = 'Bangalore';
Instead of:
SELECT DECODE(location,'Bangalore',id,NULL) id FROM employee 
WHERE name LIKE 'Ramesh%';
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.
a) Use single case for all SQL verbs
b) Begin all SQL verbs on a new line
c) Separate all words with a single space 
d) Right or left aligning verbs within the initial SQL verb

Sunday, September 9, 2012

SQL-Joins



Ø  The purpose of a join is to combine the data across tables.
Ø  A join is actually performed by the where clause which combines the specified rows of tables.
Ø  If a join involves in more than two tables then oracle joins first two tables based on the joins condition and then compares the result with the next table and so on.

TYPES
*       Equi join
*       Non-equi join
*       Self join
*       Natural join
*       Cross join
*       Outer join
Ø  Left outer
Ø  Right outer
Ø  Full outer
*       Inner join
*       Using clause
*       On clause

Assume that we have the following tables.
SQL> select * from dept;
    DEPTNO DNAME      LOC
     ------ ---------- ----------
        10            mkt        hyd
        20            fin        bang
        30            hr         bombay
SQL> select * from emp;
       EMPNO   ENAME      JOB       MGR     DEPTNO
      ---------- ---------- ---------- ---------- ----------
       111         saketh     analyst           444         10
       222         sudha     clerk                333         20
       333         jagan      manager         111         10
       444         madhu    engineer         222         40

EQUI JOIN

A join which contains an ‘=’ operator in the joins condition.

Ex:
     SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno=d.deptno;

          EMPNO     ENAME      JOB    DNAME      LOC
          ---------- ---------- ---------- ---------- ----------
            111           saketh    analyst    mkt        hyd
            333           jagan      manager  mkt        hyd
            222           sudha      clerk        fin        bang

USING CLAUSE

SQL> select empno,ename,job ,dname,loc from emp e join dept d using(deptno);

          EMPNO     ENAME      JOB    DNAME      LOC
          ---------- ---------- ---------- ---------- ----------
            111           saketh    analyst    mkt        hyd
            333           jagan      manager  mkt        hyd
            222           sudha      clerk        fin        bang

ON CLAUSE

SQL>  select empno,ename,job,dname,loc from emp e join dept d on(e.deptno=d.deptno);
          EMPNO     ENAME      JOB    DNAME      LOC
          ---------- ---------- ---------- ---------- ----------
            111           saketh    analyst    mkt        hyd
            333           jagan      manager  mkt        hyd
            222           sudha      clerk        fin        bang

NON-EQUI JOIN

A join which contains an operator other than ‘=’ in the joins condition.

Ex:
     SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno >
             d.deptno;

          EMPNO     ENAME    JOB      DNAME      LOC
          ---------- ---------- ---------- ---------- ----------
       222    sudha      clerk          mkt        hyd
       444    madhu     engineer   mkt        hyd
       444    madhu     engineer   fin          bang
       444    madhu     engineer   hr           bombay

SELF JOIN

Joining the table itself is called self join.

Ex:
     SQL> select e1.empno,e2.ename,e1.job,e2.deptno from emp e1,emp e2 where
             e1.empno=e2.mgr;

     EMPNO     ENAME    JOB      DEPTNO
     ---------- ---------- ---------- ----------
       111          jagan      analyst         10
       222          madhu      clerk           40
       333          sudha      manager      20
       444          saketh     engineer      10
NATURAL JOIN

Natural join compares all the common columns.

Ex:
     SQL> select empno,ename,job,dname,loc from emp natural join dept;

     EMPNO   ENAME      JOB      DNAME    LOC
    ---------- ---------- ---------- ---------- ----------
       111          saketh     analyst     mkt        hyd
       333          jagan      manager   mkt        hyd
       222          sudha      clerk         fin          bang

CROSS JOIN

This will gives the cross product.

Ex:
     SQL> select empno,ename,job,dname,loc from emp cross join dept;

 EMPNO  ENAME    JOB        DNAME      LOC
---------- ---------- ---------- ---------- ----------
       111     saketh   analyst      mkt        hyd
       222     sudha    clerk          mkt        hyd
       333     jagan     manager   mkt        hyd
       444     madhu   engineer   mkt        hyd
       111     saketh   analyst      fin          bang
       222     sudha    clerk          fin          bang
       333     jagan     manager   fin          bang
       444     madhu   engineer   fin          bang
       111     saketh   analyst      hr           bombay
       222     sudha    clerk          hr           bombay
       333     jagan     manager   hr           bombay
       444     madhu   engineer   hr           bombay

OUTER JOIN

Outer join gives the non-matching records along with matching records.

LEFT OUTER JOIN

This will display the all matching records and the records which are in left hand side table those that are not in right hand side table.

Ex:
     SQL> select empno,ename,job,dname,loc from emp e left outer join dept d
             on(e.deptno=d.deptno);
Or
      SQL> select empno,ename,job,dname,loc from emp e,dept d where
             e.deptno=d.deptno(+);

                             EMPNO     ENAME   JOB       DNAME      LOC
     ---------- ---------- ---------- ---------- ----------
       111          saketh    analyst       mkt        hyd
       333          jagan      manager    mkt        hyd
       222          sudha     clerk           fin          bang
       444          madhu    engineer

RIGHT OUTER JOIN

This will display the all matching records and the records which are in right hand side table those that are not in left hand side table.

Ex:
     SQL> select empno,ename,job,dname,loc from emp e right outer join dept d
              on(e.deptno=d.deptno);
Or
      SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno(+) =
             d.deptno;


     EMPNO    ENAME     JOB      DNAME      LOC
     ---------- ---------- ---------- ---------- ----------
       111          saketh     analyst      mkt        hyd
       333          jagan       manager   mkt        hyd
       222          sudha      clerk          fin          bang
                                                       hr           bombay

FULL OUTER JOIN

This will display the all matching records and the non-matching records from both tables.

Ex:
     SQL> select empno,ename,job,dname,loc from emp e full outer join dept d
              on(e.deptno=d.deptno);


 EMPNO   ENAME    JOB        DNAME      LOC
---------- ---------- ---------- ---------- ----------
       333     jagan     manager    mkt        hyd
       111     saketh   analyst       mkt        hyd
       222     sudha    clerk           fin        bang
       444     madhu   engineer
                                                   hr         bombay

INNER JOIN

This will display all the records that have matched.

Ex:
     SQL> select empno,ename,job,dname,loc from emp inner join dept using(deptno);

     EMPNO     ENAME   JOB        DNAME    LOC
     ---------- ---------- ---------- ---------- ----------
       111          saketh     analyst      mkt       hyd
       333          jagan       manager   mkt       hyd
       222          sudha      clerk          fin         bang

SQL Joins


SQL Joins

SQL Joins are used to relate information in different tables. A Join condition is a part of the sql query that retrieves rows from two or more tables. A SQL Join condition is used in the SQL WHERE Clause of select, update, delete statements.
                                                                 ( or)
join is used to combine rows from multiple tables. A join is performed whenever two or more tables is listed in the FROM clause of an SQL statement.

The Syntax for joining two tables is:
SELECT col1, col2, col3...
FROM table_name1, table_name2 
WHERE table_name1.col2 = table_name2.col1; 
If a sql join condition is omitted or if it is invalid the join operation will result in a Cartesian product. The Cartesian product returns a number of rows equal to the product of all rows in all the tables being joined. For example, if the first table has 20 rows and the second table has 10 rows, the result will be 20 * 10, or 200 rows. This query takes a long time to execute.
Lets use the below two tables to explain the sql join conditions.
database table "product";
product_idproduct_namesupplier_nameunit_price
100CameraNikon300
101TelevisionOnida100
102RefrigeratorVediocon150
103IpodApple75
104MobileNokia50
database table "order_items";
order_idproduct_idtotal_unitscustomer
510010430Infosys
51011025Satyam
510210325Wipro
510310110TCS
SQL Joins can be classified into Equi join and Non Equi join.
1) SQL Equi joins
It is a simple sql join condition which uses the equal sign as the comparison operator. Two types of equi joins are SQL Outer join and SQL Inner join.
For example: You can get the information about a customer who purchased a product and the quantity of product.
2) SQL Non equi joins
It is a sql join condition which makes use of some comparison operator other than the equal sign like >, <, >=, <=