Sunday 6 September 2015

TRAINING (SQL-8) - Data Query Language (DQL) - SQL Joins - Understandding SELF JOIN

SELF JOIN
  • Joining one table with the same tables is called SELF JOIN.
  • The self join can be viewed as a join of two copies of the same table ( though tables are not actually copied).
  • Since both the tables have same name, to distinguish the columns, table aliases are used.
  • To achieve the the self join from a single table there should be a logical primary & foreign key mapping must exist i.e. for one column value there should have many column values. (No need to have realy primary/foreign key defined at physical level)
  • For example in our exercise we have used emp table that came bundled with an Oracle database in scott schema where:
    • From Worker to Manager relationship
      • 1 worker (employee) can have 0 or 1 Manager
    • From Manager to Worker relationship
      • Manager can have 0, 1 or Many Worker (employee)
  • First in SQL we create virtual copies of table emp named workermanager and using alias in FROM clause using aliases and also select the columns from both workermanager tables prefixing column names with Aliases. Thereafter in WHERE clause we specify to select only those rows where in worker table mgr column value is equal to manager table empno column using WHERE worker.mgr= manager.empno.
  • SELECT
    worker.empno as WorkerID, worker.ename as WorkerName, worker.job as JobTitle, 

    manager.ename as ManagerName

    FROM emp
    worker, emp manager
    WHERE
    worker.mgr= manager.empno;
  • Once the SQL query executed its only display the result which matches the criteria.

  • In the result you could see that empno=7839 ename=KING job=PRESIDENT never comes in final result. That is due to the fact that when inner join condition WHERE worker.mgr= manager.empno is executed empno in LEFT table (worker.mgr) never becomes equal to RIGHT table ( manager.empno) as the value for empno 7839 in MGR column in LEFT table (worker) is null.
  • However if you also want to include empno=7839 ename=KING in the end result of the SQL, then you have to use LEFT JOIN to include all the matching column of LEFT & RIGHT table plus all the non-matching column of LEFT table using SQL below.
  • SELECT
    worker.empno as WorkerID, worker.ename as WorkerName, worker.job as JobTitle, 
    manager.ename as ManagerName
    FROM emp worker, emp manager
    WHERE worker.mgr= manager.empno (+);

TRAINING (SQL-7) - Data Query Language (DQL) - SQL Joins between two or more tables

SQL JOINS (How to Join Tables): 
  • As soon as more then one table is mentioned in FROM clause of SQL, joins comes in picture.
  • Usually JOINS will be performed between two tables based on the key column (Primary & Foreign key) between two or more tables.
    • 1) CARTESIAN JOIN
    • 2.) INNER JOIN
    • 3.) LEFT JOIN
    • 4.) RIGHT JOIN
    • 5.) OUTER JOIN
    • 6.) LEFT JOIN EXCLUDING INNER JOIN
    • 7.) RIGHT JOIN EXCLUDING  INEER JOIN
    • 8.) OUTER JOIN EXCLUDING INNER JOIN
    • 9.) SELF JOIN

Understand SQL Joins with practical examples:

As part of this training session we will try to understand these Joins practically and to achieve this execute below SQL script to create the necessary tables and data for this exercise. For simplicity purpose for this demonstration we have not created any primary or foreign key.

CREATE TABLE Table_A( ID numeric(2, 0) NULL, SampleColumn1 nchar(10));
CREATE TABLE Table_B(ID numeric(2, 0) NULL, SampleCol2 nchar(10));
CREATE TABLE Table_Trans( IDD numeric(2, 0) NULL, SomeTransCol nchar(20) );
Insert into Table_A values(1,'AAA');
Insert into Table_A values(2,'BBB');
Insert into Table_B values(1,'RRR');
Insert into Table_B values(2,'SSS');
Insert into Table_B Values(3,'PPP');
Insert into Table_Trans Values(1, 'Transaction 1');
Insert into Table_Trans Values(3, 'Transaction 2');
Insert into Table_Trans Values(3, 'Transaction 3');
Insert into Table_Trans Values(3, 'Transaction 4');
Insert into Table_Trans Values(1, 'Transaction 5');
commit;

Once the above  script executed table_a,  table_b &  table_trans created with below data.

SELECT * FROM table_a;

SELECT * FROM table_b;

SELECT * FROM table_trans;


1.) CARTESIAN JOIN
  • When two or more tables are joined without any condition the resultset will be the multiplication of first table row X Second table row X .......N table row.
  • Easiest but rarest in use.
  • Cartesian product will take a single record in first table and attach with all the records in second table...third table and so on. Then takes the second record in first table and attach with all the records in second table...third table and so on. This continues till the end of records of first table.
  • For Example: SELECT * FROM table_a, table_b;
  • Same way if we add table_trans in SQL i.e. SELECT * FROM table_a, table_b, table_trans the total result will be 30 rows i.e. 2x3x5.

Why Cartesian join is not practical and why to use other joins by joining the tables with conditions:
Since the result without a condition is too big and not of great usage, having a condition (one column value in first table = one columns value in first table) could eliminate/filter the number of records from the search results, which are not useful and related by common column.

For Example:

SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2 
FROM table_a a, table_b b
WHERE a.id=b.id;

OR

SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2 
FROM table_a a
INNER JOIN 
table_b b
ON a.id=b.id;


2.) INNER JOIN
  • Simplest & most commonly used join.
  • Query using INNER JOIN will return all of the records in the left table (A) that have a matching record in the right table (B).
For Example:
SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2
FROM table_a a, table_b b
WHERE a.id=b.id;

OR

SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2
FROM table_a a
INNER JOIN 
table_b b
ON a.id=b.id;

3.) LEFT JOIN
  • Query using LEFT JOIN will return all of the records in the left table (A) regardless if any of those records have a match in the right table (B) or not PLUS It will also return all the matching record from right table (B).

  • LEFT Join is achieved using (+) operator.
  • To achieve LEFT Join we need to place (+) at the end of right side table/column in where clause.
  • For the rows of table A, which does not have corresponding matching row for table B, (null) is displayed (marked in red rectangle in screenshot below).
NOTE: To complete the next exercise for other joins we need to perform below two statements.
insert into table_a values (4,'CCC'); 
commit;

For Example:
SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2
FROM table_a a, table_b b
WHERE a.id=b.id (+);

OR

SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2
FROM table_a a
LEFT JOIN 
table_b b
ON a.id=b.id;



4.) RIGHT JOIN
  • Query using RIGHT JOIN will return all of the records in the right table (B) regardless if any of those records have a match in the left table (A) or not PLUS It will also return all the matching record from left table (B).

  • RIGHT Join is also achieved using (+) operator.
  • To achieve RIGHT Join we need to place (+) at the end of left side table/column in where clause.
  • For the rows of table B, which does not have corresponding matching row for table A, (null) is displayed (marked in red rectangle in screenshot below).
For Example:
SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2
FROM table_a a, table_b b
WHERE a.id (+)=b.id;

OR

SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2
FROM table_a a
RIGHT JOIN 
table_b b
ON a.id=b.id;



5.) FULL OUTER JOIN or OUTER JOIN or FULL JOIN
  • Query using FULL OUTER JOIN or OUTER JOIN will return all of the records of both the tables (matching or not matching result both ).
  • For the rows of table A or B, which does not have corresponding matching row (null) is displayed.


For Example:
SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2
FROM table_a a
FULL OUTER JOIN 
table_b b
ON a.id=b.id;



6.) LEFT EXCLUDING JOIN
  • Query using LEFT EXCLUDING JOIN will return all of the records of left table (A) that do not match any records in right table (B).
  • In order to return all of the records of left table (A) that do not match any records in right table, first you need to LEFT JOIN table A with B, this will give all the record from table A plus all the matching record from right table (B). Thereafter when WHERE b.id IS NULL is applied it display final result which is nothing but, all of the records of left table (A) that do not match any records in right table (B).
  • For the rows of table A or B, which does not have corresponding matching row (null) is displayed.

For Example:
SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2
FROM table_a a
LEFT JOIN 
table_b b
ON a.id=b.id
WHERE b.id IS NULL;



7.) RIGHT EXCLUDING JOIN
  • Query using RIGHT EXCLUDING JOIN will return all of the records of RIGHT table (B) that do not match any records in left table (A).

  • In order to return all of the records of right table (B) that do not match any records in left table, first you need to RIGHT JOIN table A with B, this will give all the record from table B plus all the matching record from right table (A). Thereafter when WHERE a.id IS NULL is applied, it display final result which is nothing but, all of the records of right table (B) that do not match any records in left table (A).
  • For the rows of table A or B, which does not have corresponding matching row (null) is displayed.

For Example:
SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2
FROM table_a a
RIGHT JOIN 
table_b b
ON a.id=b.id
WHERE a.id IS NULL;



8.) OUTER EXCLUDING JOIN
  • Query using OUTER EXCLUDING JOIN will return all of the records of LEFT table (A) and all of the records of RIGHT table (B) that do not match.

  • In order to return all of the records of LEFT table (A) and all of the records of RIGHT table (B) that do not match, first you need to FULL OUTER JOIN table A with B, this will give all the record from left table (A) plus all the record from right table (B). Thereafter when WHERE a.id IS NULL OR b.id IS NULL is applied, it display final result which is nothing but; all of the records of right table (B) that do not match any records in left table (A).
  • For the rows of table A or B, which does not have corresponding matching row (null) is displayed.

For Example:
SELECT a.id AS A_id, a.samplecolumn1, b.id AS B_id, b.samplecol2
FROM table_a a
FULL OUTER JOIN 
table_b b
ON a.id=b.id
WHERE a.id IS NULL OR b.id IS NULL;




9.) SELF JOIN
  • Joining one table with the same tables is called SELF JOIN. (I will explain the  SELF JOIN in my next post in detail).


JOINING MULTIPLE (more than two) TABLES:
While joining more than two tables, first initial two tables are joined and there after the result of first two table is joined with the third table and then final result is displayed.


For Example:
SELECT  a.id AS A_id, a.samplecolumn1, 
              b.id AS B_id, b.samplecol2,

              c.sometranscol
FROM     table_a a, table_b b, table_trans c
WHERE   a.id=b.id
AND        b.id=c.idd;



Sometime UNION, ALL etc could also be used in place of joins, like in below example you can fake it by union two outer joins:
select a.field1, b.field2
from table_a a, table_b b
where a.id = b.id(+)
union all 
select a.field1, b.field2
from table_a a, table b b
where a.id(+) = b.id
      and a.id is null

Saturday 5 September 2015

TRAINING (SQL-6) - Data Query Language (DQL) Keywords & Clauses

SQL Keywords & Clauses

1.) SELECT Statement
SELECT statement contains list of columns or all columns which needs to select/display after the query execution competes.

Syntax:

SELECT <Column1, Column1, ......., ColumnN)
SELECT <*>
Example:
SELECT *
SELECT Ename, Job

1.1) DISTINCT
Used with SELECT to club/group the result.
When NULL is used in DISTINCT clause, SQL will consider all NULL as same

Syntax:
SELECT DISTINCT <Column1>
Example:
SELECT DISTNCT Job

2.) FROM Clause
FROM clause is used to mention the table/tables going to be used for selection.

Syntax:
SELECT <Column1, Column2, ......., ColumnN)
FROM <Table 1, TABLE2,.....TableN>

Example:
SELECT EMPNO, ENAME
FROM EMP

3.) WHERE Clause
WHERE clause is used to narrow down/filter the data retrieved using SELECT statement. In-order to  narrow down/filter the data retrieved different comparison, logical and other operators are used.  mention the table/tables going to be used for selection.

3.1.1) RELATIONAL COMPARISON OPERATORS
Below are the list of relational operators used to compare any datatype (number, character, string or combination of these datatypes) and expression (formula).
  • EQUALS TO (=)
  • NOT EQUALS TO (<>)
  • GREATER THAN ( >)
  • LESSER THAN (<)
  • GREATER THAN or EQUALS TO (>=)
  • LESSER THAN or EQUALS TO (<=)
Syntax:
SELECT <Column1, Column2, ......., ColumnN)
FROM <Table 1, TABLE2,.....TableN>
WHERE <Column/Expression> = <FILTER CRITERIA>

Example:
SELECT EMPNO, ENAME
FROM EMP
WHERE EMPNO = 7900;


3.1.2) BETWEEN
BETWEEN is inclusive of both side of values around it.
Example:
WHERE Salary BETWEEN 4000 AND 5000;

3.1.3) IN
Example:
WHERE Cost IN (200, 400, 500);

3.1.4) LIKE
Example:
WHERE Last_Name LIKE 'S%';
WHERE Last_Name LIKE '_HAR%';

3.1.5) IS NULL
  • By definition a NULL value is an unknown value.
  • One NULL value never equals to another NULL value. There is an exception though ( When NULL is used in DISTINCT clause, SQL will consider all NULL as same).
Example:
WHERE Commision IS NULL;

3.1.6) NOT
For NEGATING/REVERTING the select result.
Example:
WHERE Salary NOT BETWEEN 4000 AND 5000;
WHERE Cost NOT IN (200, 400, 500);
WHERE Commision IS NOT NULL;

3.2) LOGICAL or BOOLEAN OPERATORS
Comparison operators can be combined with help of Logical or Boolean operators AND and OR.

3.2.1) AND
Conditions on both side of AND logical operator must be true (0) to fetch the results.
Example:
SELECT *
FROM emp 
WHERE empno = 7900 AND deptno = 30;

3.2.2) OR
Conditions on either side of OR logical operator must be true (0) to fetch the results.
Example:
SELECT *
FROM emp 
WHERE deptno 20 OR deptno 30;

PRECEDENCE OF LOGICAL OPERATORS
  • When AND and OR are used together in a WHERE clause, the AND operator always take precedence over the OR operator, meaning the AND condition are evaluated first.
  • If there are multiple operators of same precedence, the left operator is executed before right.
  • You can manipulate the precedence in WHERE clause using parentheses.
  • For example below queries aare going to give you different results
    • SELECT description, cost, prerequisite
      FROM course
      WHERE cost = 1195
      AND prerequisite = 20
      OR prerequisite =2;
    • SELECT description, cost, prerequisite
      FROM course
      WHERE cost = 1195
      AND (prerequisite = 20
      OR prerequisite =25);

4.) ORDER BY Clause

Result of SQLs are displayed in the order they are returned from database, however to display data in a specific order (ascending or descending) ORDER BY clause is used.
  • By Default when ORDER BY clause is used results are displayed in Ascending order.
  • If you want to display in specific order use the abbreviation DESC (descending) or ASC (ascending).
Syntax:
SELECT <Column1, Column2, ......., ColumnN)
FROM <Table 1, TABLE2,.....TableN>
WHERE <Column/Expression> = <FILTER CRITERIA>
ORDER BY <Column1, Column2, ......., ColumnN) 

Example:
SELECT empno, ename, deptno
FROM emp
WHERE ename LIKE 'J%'
ORDER BY deptno DESC;

5.) GROUP BY Clause

  • GROUP BY clause is similar to DISTINCT but only work on groups.
  • Used to club/group the results filtered on the basis of WHERE clause.

Syntax:
SELECT <Column1, Column2, ......., ColumnN)
FROM <Table 1, TABLE2,.....TableN>
WHERE <Column/Expression> = <FILTER CRITERIA>
GROUP BY <Column>
ORDER BY <Column1, Column2, ......., ColumnN) 

Example:
SELECT empno, ename, deptno
FROM emp
WHERE ename LIKE 'J%'
GROUP BY deptno
ORDER BY deptno DESC;

6.) HAVING Clause
HAVING clause is similar to WHERE clause to eliminate/filter the results, but it only works on groups/aggregate.

Syntax:
SELECT <Column1, Column2, ......., ColumnN)
FROM <Table 1, TABLE2,.....TableN>
WHERE <Column/Expression> = <FILTER CRITERIA>
GROUP BY <Column>
HAVING <Column/Expression> = <FILTER CRITERIA> 
ORDER BY <Column1, Column2, ......., ColumnN) 

Example:
SELECT location, count(location) "Total Locations", capacity, sum(capacity) "Total Capacity"
FROM section
WHERE section_no=3
GROUP BY location, capacity
HAVING sum(capacity) > 75
ORDER BY deptno DESC;