Sunteți pe pagina 1din 22

Advanced SQL Skills

Table of Contents
CHAPTER 1 SQL AGGREGATE FUNCTIONS ........................................................................................... 2 AVG() Function .................................................................................................................................... 2 COUNT () Function .............................................................................................................................. 3 FIRST() Function .................................................................................................................................. 4 LAST() Function ................................................................................................................................... 5 MAX() Function ................................................................................................................................... 5 MIN() Function .................................................................................................................................... 6 SUM() Function ................................................................................................................................... 6 COMBINE AGGREGATE FUNCTIONS.................................................................................................... 7 CHAPTER 2 GROUP BY WITH HAVING CLAUSE .................................................................................... 8 GROUP BY ........................................................................................................................................... 8 HAVING ............................................................................................................................................... 9 CHAPTER 3 SET OPERATIONS ............................................................................................................. 11 UNION ALL......................................................................................................................................... 12 UNION ............................................................................................................................................... 12 INTERSECT ......................................................................................................................................... 13 MINUS ............................................................................................................................................... 13 RULES AND RESTRICTIONS ON SET OPERATIONS ............................................................................. 14 CHAPTER 4 SET THEORY AND SQL JOINS ........................................................................................... 16 SET THEORY ....................................................................................................................................... 16 SQL INNER JOIN................................................................................................................................. 18 SQL LEFT JOIN.................................................................................................................................... 18 SQL RIGHT JOIN ................................................................................................................................. 19 SQL FULL JOIN ................................................................................................................................... 19 SELF JOIN ........................................................................................................................................... 20 CROSS JOIN (CARTESIAN JON)........................................................................................................... 21 SQL INDEXES...................................................................................................................................... 22

Advanced SQL Skills


CHAPTER 1 SQL AGGREGATE FUNCTIONS
SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions are mentioned in below table. Aggregate Function AVG() COUNT() FIRST() LAST() MAX() MIN() SUM() Function Objective Returns the average value Returns the number of rows Returns the first value Returns the last value Returns the largest value Returns the smallest value Returns the sum

AVG() Function
The AVG() function returns the average value of a numeric column. Syntax: SELECT AVG(column_name) FROM table_name Demo Database - "Products" table: ProductID 1001 1002 1003 1004 1005 1006 1007 1008 ProductName BirdEye Veg BirdEye Pie Tiger Beer A&W Root Beer F&N Ginger Beer F&N Orange Chef Anton's Gumbo Mix Chef Anton's Seasoning SupplierID 121200 121200 141401 131215 181628 181628 235811 235811 CategoryID 1 1 2 2 2 2 3 3 Unit 10 boxes x 10 bags 6 24 750m bottles 12 - 750m bottles 12 - 350m bottles 12 - 750m bottles 48 boxes 60 6 oz jar Price 25 3 48 24 13 12 96 34

Query: SELECT AVG(Price) AS PriceAverage FROM Products; Result: PriceAverage 31.88

Using the same Demo Database above the following SQL statement selects the "ProductName" and "Price" records that have an above average price: Query : SELECT ProductName, Price FROM Products WHERE Price>(SELECT AVG(Price) FROM Products); Result: ProductName Tiger Beer Chef Anton's Gumbo Mix Chef Anton's Seasoning Price 48 96 34 2

Advanced SQL Skills


COUNT () Function
The COUNT() function returns the number of rows that matches a specified criteria. Syntax: SELECT COUNT(*) FROM table_name; Syntax: SELECT COUNT(DISTINCT column_name) FROM table_name; The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column: Demo Database - "Orders" table: OrderID CustomerID EmployeeID OrderDate 10008 111001 5000 04/01/1996 10009 113552 3212 05/01/1996 10000 116321 2314 08/01/1996 10001 118425 5000 08/01/1996 10002 117776 3562 11/01/1996 10003 118343 3222 21/01/1996 10004 114252 9632 25/01/1996 10005 116828 3699 30/01/1996 ShipperID 121200 141401 181628 121200 141401 141401 141401 181628

Ex- 1 The following SQL statement counts the total number of orders in the "Orders" table: SELECT COUNT(*) AS NumberOfOrders FROM Orders; Result: NumberOfOrders 8

Ex 2 COUNT(column_name) ExampleUsing the same Demo Database above the following SQL statement counts the number of orders from "EmployeeID"=5000 from the "Orders" table: SELECT COUNT(CustomerID) AS OrdFromCust FROM Orders WHERE EmpoyeeID=5000; Result: OrdFromCust 2 Ex 3 COUNT(DISTINCT column_name)

Advanced SQL Skills


Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access Using the same Demo Database above the following SQL statement counts the number of unique employee in the "Orders" table: SELECT COUNT(DISTINCT EmployeeID) AS NumberFromEmployee FROM Orders; Result: NumberFromEmployee 7

FIRST() Function
The FIRST() function returns the first value of the selected column. Syntax: SELECT FIRST(column_name) FROM table_name; Note: The FIRST() function is only supported in MS Access Workaround in SQL Server, MySQL and Oracle SQL Server Syntax SELECT TOP 1 column_name FROM table_name ORDER BY column_name ASC; MySQL Syntax SELECT column_name FROM table_name ORDER BY column_name ASC LIMIT 1; Oracle Syntax SELECT column_name FROM table_name ORDER BY column_name ASC WHERE ROWNUM <=1; Ex 1 Using the same Demo Database above the following SQL statement selects the first value of the "CustomerID" column from the "Orders" table: SELECT FIRST(CustomerID) AS FirstCustomer FROM Orders; Result: FirstCustomer 111001

Advanced SQL Skills


LAST() Function
The LAST() function returns the last value of the selected column. Syntax: SELECT LAST(column_name) FROM table_name; Note: The LAST() function is only supported in MS Access. Ex 1 Using the same Demo Database above the following SQL statement selects the Last value of the "CustomerID" column from the "Orders" table: SELECT LAST (CustomerID) AS LastCustomer FROM Orders; Result: LastCustomer 116828

MAX() Function
The MAX() function returns the largest value of the selected column. Syntax: SELECT MAX(column_name) FROM table_name; Demo Database - "Products" table: ProductID 1001 1002 1003 1004 1005 1006 1007 1008 ProductName BirdEye Veg BirdEye Pie Tiger Beer A&W Root Beer F&N Ginger Beer F&N Orange Chef Anton's Gumbo Mix Chef Anton's Seasoning SupplierID 121200 121200 141401 131215 181628 181628 235811 235811 CategoryID 1 1 2 2 2 2 3 3 Unit 10 boxes x 10 bags 6 24 750m bottles 12 - 750m bottles 12 - 350m bottles 12 - 750m bottles 48 boxes 60 6 oz jar Price 25 3 48 24 13 12 96 34

Ex 1 The following SQL statement gets the largest value of the "Price" column from the "Products" table: SELECT MAX(Price) AS HighestPrice FROM Products; Result: HighestPrice 96

Advanced SQL Skills


MIN() Function
The MIN() function returns the smallest value of the selected column. Syntax: SELECT MIN(column_name) FROM table_name; Ex 1 Using the same Demo Database above the following SQL statement gets the smallest value of the "Price" column from the "Products" table SELECT MIN(Price) AS LowestOrderPrice FROM Products; Result: LowestPrice 3

SUM() Function
The SUM() function returns the total sum of a numeric column. Syntax: SELECT SUM(column_name) FROM table_name; Demo Database - "OrderDetails" table: OrderDetailID OrderID 1 10248 2 3 4 5 6 7 8 9 10 10248 10248 10249 10249 10250 10250 10250 10251 10251 ProductName BirdEye Veg BirdEye Pie Tiger Beer A&W Root Beer F&N Ginger Beer F&N Orange Chef Anton's Gumbo Mix Chef Anton's Seasoning BirdEye Chips BirdEye Peas Quantity 36 25 36 25 180 120 36 12 24 60

Ex 1 The following SQL statement finds the sum of all the "Quantity" fields for the "OrderDetails" table: SELECT SUM(Quantity) AS TotalQtyOrdered FROM OrderDetails; Result: TotalQtyOrdered 624

Advanced SQL Skills


COMBINE AGGREGATE FUNCTIONS
EX 1 Combine SUM() and MIN() functions The following SQL statement finds the sum of all the "Quantity" fields excluding the minimum quantity for the "OrderDetails" table: SELECT SUM(Quantity) AS EXMINTotalItemsOrdered FROM OrderDetails WHERE Quantity>(SELECT MIN(Quantity) FROM OrderDetails); Ex 2 Combine SUM() and AVG() functions The following SQL statement finds the sum of all the "Quantity" fields Greater than the average quantity for the "OrderDetails" table: SELECT SUM(Quantity) AS TotalItemsOrderedGTAVG FROM OrderDetails WHERE Quantity>(SELECT AVG(Quantity) FROM OrderDetails);

Advanced SQL Skills


CHAPTER 2 GROUP BY WITH HAVING CLAUSE
GROUP BY
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. Syntax SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name; Ex 1 below is a selection from the "Orders" table: OrderID CustomerID EmployeeID OrderDate 10248 10249 10250 90 81 34 5 6 4 1996-07-04 1996-07-05 1996-07-08 ShipperID 3 1 2

And a selection from the "Shippers" table: ShipperID ShipperName 1 2 3 Speedy Express United Package Phone (503) 555-9831 (503) 555-3199

Federal Shipping (503) 555-9931

And a selection from the "Employees" table: EmployeeID LastName FirstName 1 2 3 Davolio Fuller Leverling Nancy Andrew Janet BirthDate Photo Notes Education includes a BA

1968-12-08 EmpID1.pic

1952-02-19 EmpID2.pic Andrew received his BTS 1963-08-30 EmpID3.pic Janet has a BS degree

Now we want to find the number of orders sent by each shipper.

Advanced SQL Skills


SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders LEFT JOIN Shippers ON Orders.ShipperID=Shippers.ShipperID GROUP BY ShipperName; Ex- 2 Below retrieves a list of the highest paid salaries in each dept: SELECT max(salary), dept FROM employee GROUP BY dept; GROUP BY More Than One Column SELECT Shippers.ShipperName, Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM ((Orders INNER JOIN Shippers ON Orders.ShipperID=Shippers.ShipperID) INNER JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID) GROUP BY ShipperName,LastName;

HAVING
The HAVING clause has been added to SQL because the WHERE keyword could not be used with aggregate functions. Syntax SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value; Ex- 3 Below is a selection from the "Orders" table: OrderID CustomerID EmployeeID 10248 10249 10250 90 81 34 5 6 4 OrderDate 1996-07-04 1996-07-05 1996-07-08 ShipperID 3 1 2

Advanced SQL Skills


And a selection from the "Employees" table: EmployeeID LastName FirstName 1 2 3 Davolio Fuller Leverling Nancy Andrew Janet BirthDate Photo Notes Education includes a BA

1968-12-08 EmpID1.pic

1952-02-19 EmpID2.pic Andrew received his BTS 1963-08-30 EmpID3.pic Janet has a BS degree

Now we want to find all the employees with more than 25 orders. SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders INNER JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID) GROUP BY LastName HAVING COUNT(Orders.OrderID) > 25; Now we want to find if the employees "Davolio" or "Fuller" having more than 25 orders SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders INNER JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID WHERE LastName='Davolio' OR LastName='Fuller' GROUP BY LastName HAVING COUNT(Orders.OrderID) > 25;

10

Advanced SQL Skills


CHAPTER 3 SET OPERATIONS
There are situations when we need to combine the results from two or more SELECT statements. SQL enables us to handle these requirements by using set operations. The result of each SELECT statement can be treated as a set, and SQL set operations can be applied on those sets to arrive at a final result. Following are the four set operations: UNION ALL UNION MINUS INTERSECT

SQL statements containing these set operators are referred to as compound queries, and each SELECT statement in a compound query is referred to as a component query. Two SELECTs can be combined into a compound query by a set operation only if they satisfy the following two conditions: 1. The result sets of both the queries must have the same number of columns. 2. The datatype of each column in the second result set must match the datatype of its corresponding column in the first result set. 3. Minus and Intersect operators are not supported in all databases. E.g. MS Access

Set operations are often called vertical joins, because the result combines data from two or more SELECTS based on columns instead of rows. The generic syntax of a query involving a set operation is: <Component query> {UNION | UNION ALL | MINUS | INTERSECT} <Component query> Operator UNION ALL UNION Objective Combines the results of two SELECT statements into one result set. Combines the results of two SELECT statements into one result set, and then eliminates any duplicate rows from that result set. Takes the result set of one SELECT statement, and removes those rows that are also returned by a second SELECT statement. Returns only those rows that are returned by each of two SELECT statements.

MINUS

INTERSECT

Note: Minus and Intersect are supported only few databases like Oracle.

11

Advanced SQL Skills


Below queries will be used to explain set operators. Query 1
SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5;

Query 2
SELECT C.CUST_NBR, C.NAME FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN');

Output: CUST_NBR NAME ---------- -----------------------------1 Cooper Industries 2 Emblazon Corp. 3 Ditech Corp. 4 Flowtech Inc. 5 Gentech Industries

Output: CUST_NBR NAME ---------- -------------------4 Flowtech Inc. 8 Zantech Inc.

If we look at the results returned by these two queries, we will notice that there is one common row (for Flowtech Inc.). Below discuss the effects of the various set operations between these two result sets.

UNION ALL
The UNION ALL operator merges the result sets of two component queries. This operation returns rows retrieved by either of the component queries. The following example illustrates the UNION ALL operation: Query:
SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5 UNION ALL SELECT C.CUST_NBR, C.NAME FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN');

Output: CUST_NBR NAME ---------- -----------------------------1 Cooper Industries 2 Emblazon Corp. 3 Ditech Corp. 4 Flowtech Inc. 5 Gentech Industries 4 Flowtech Inc. 8 Zantech Inc.

As we can see from the result set, there is one customer, which is retrieved by both the SELECTs, and therefore appears twice in the result set. The UNION ALL operator simply merges the output of its component queries, without caring about any duplicates in the final result set.

UNION
The UNION operator returns all distinct rows retrieved by two component queries. The UNION operation eliminates duplicates while merging rows retrieved by either of the component queries. The following example illustrates the UNION operation:

12

Advanced SQL Skills


Query: SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5 UNION SELECT C.CUST_NBR, C.NAME FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN'); Output:

CUST_NBR NAME ---------- -----------------------------1 Cooper Industries 2 Emblazon Corp. 3 Ditech Corp. 4 Flowtech Inc. 5 Gentech Industries 8 Zantech Inc.

INTERSECT
INTERSECT returns only the rows retrieved by both component queries. Compare this with UNION, which returns the rows retrieved by any of the component queries. If UNION acts like 'OR', INTERSECT acts like 'AND'. For example: Query:
SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5 INTERSECT SELECT C.CUST_NBR, C.NAME FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN');

Output: CUST_NBR NAME ---------- ---------------------4 Flowtech Inc.

MINUS
MINUS returns all rows from the first SELECT that are not also returned by the second SELECT. For example: Query:
SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5 MINUS SELECT C.CUST_NBR, C.NAME FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN');

Output: CUST_NBR NAME ---------- -----------------------------1 Cooper Industries 2 Emblazon Corp. 3 Ditech Corp. 5 Gentech Industries

An important thing to note here is that the execution order of component queries in a set operation is from top to bottom. The results of UNION, UNION ALL, and INTERSECT will not change if we alter the ordering of component queries. However, the result of MINUS will be different if we 13

Advanced SQL Skills


alter the order of the component queries. If we rewrite the previous query by switching the positions of the two SELECTs, we get a completely different result: Query:
SELECT C.CUST_NBR, C.NAME FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN') MINUS SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5;

Output CUST_NBR NAME ---------- -----------------------------8 Zantech Inc.

The row for "Flowtech Inc." is returned by both queries, so in our first MINUS example the first component query adds "Flowtech Inc." to the result set while the second component query removes it. The second example turns the MINUS operation around. The first component query adds "Flowtech Inc." and "Zantech Inc." to the result set. The second component query specifies rows to subtract. One of the rows to subtract is "Flowtech Inc.", leaving "Zantech Inc." as the sole remaining row.

RULES AND RESTRICTIONS ON SET OPERATIONS


Rule 1 Column names for the result set are derived from the first SELECT: Query:
SELECT CUST_NBR "Customer ID", NAME "Customer Name" FROM CUSTOMER WHERE REGION_ID = 5 UNION SELECT C.CUST_NBR, C.NAME FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN');

Output: Customer ID Customer Name ----------- ---------------------1 Cooper Industries 2 Emblazon Corp. 3 Ditech Corp. 4 Flowtech Inc. 5 Gentech Industries 8 Zantech Inc.

Although both SELECTs use column aliases, the result set takes the column names from the first SELECT. The same thing happens when we create a view based on a set operation. The column names in the view are taken from the first SELECT:

Rule-2 If we want to use ORDER BY in a query involving set operations, we must place the ORDER BY at the end of the entire statement.

14

Advanced SQL Skills


The component queries can't have individual ORDER BY clauses. For example: Query:
SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5 UNION SELECT EMP_ID, LNAME FROM EMPLOYEE WHERE LNAME = 'MARTIN' ORDER BY CUST_NBR;

Output: CUST_NBR NAME ---------- --------------------1 Cooper Industries 2 Emblazon Corp. 3 Ditech Corp. 4 Flowtech Inc. 5 Gentech Industries 6 MARTIN

15

Advanced SQL Skills


CHAPTER 4 SET THEORY AND SQL JOINS
SET THEORY
Set: Set is a collection of different elements. Universal Set: It is a set that contains all elements of given problem definition. For this tutorial we are talking about Integers only. So our example Universal set contains all integers. It is denoted as U. Subset: If all the elements of set A are found in set B, then A is a subset of B. To denote this, we can mark it as A B. All the sets are subset of themselves. A A. To be more precise for subsets, we can say that A is a proper subset of B if and only if every element in A is also in B, and there exists at least one element in B that is not in A. Assume that A and B are empty sets. Then we define the elements for these two sets. A = {1,2,3} and B= {2,3,4} Consider set A and B individually and draw them in Universal set as below. U 1, 2, 3 A 2, 3, 4 B U

But when you draw both the sets together, there are some common elements in both sets. Union of A and B: A B is the set of all elements that are in A, B or both. : A B = {1,2,3,4} U 1 A 2 3 4 B

A B = {1,2,3,4} Intersection of A and B: AB is the set of all elements that are in both A AND B: AB = {2,3} U 1 A 2 3 4 B

A B = {2,3} Complement: Complement of A is the set of all elements that are not in A but do exist in Universal set U. It is denoted as A 16

Advanced SQL Skills


So for our example A = {4} and same way B = {1} E.g. A

Relative Complement: AB = set of elements that are not in A nor in A B. So AB = {4}

Symmetric difference: (A B) (AB) = A B is the set of elements that it is in either one of the sets but not both. (A B) (AB) = {1,4}

How this set theory is related to SQL joins? Lets find out now. Table1 EMPLOYEE_NAME EMP _ID EMP01 EMP02 EMP03 EMP04 EMP05 EMP06 EMP_NAME JAMES GERARD SARAH SANDY GARY JULIAN Table 2 EMPLOYEE_ROLE EMP _ID EMP01 EMP03 EMP05 EMP06 EMP01 EMP08 EMP_ROLE DEVELOPER ANALYST ADMIN TESTER CONFIG MGR COORDINATOR

Assumption: There is no referential integrity constrains between these two tables. Try to join these two tables in meaningful way with help of SQL joins.

17

Advanced SQL Skills


SQL INNER JOIN
(JOIN or EQUIJOIN) (Intersection of sets AB) An SQL INNER JOIN return all rows from multiple tables where the join condition is met. The INNER JOIN creates a new result table by combining column values of two tables (table1 and table2) based upon the join-condition. The query compares each row of table1 with each row of table2 to find all pairs of rows which satisfy the join-condition. When the join-condition is satisfied, column values for each matched pair of rows of A and B are combined into a result row.

Query:
SELECT EN.EMP_NAME, ER.EMP_ROLE FROM EMPLOYEE_NAME EN INNER JOIN EMPLOYEE_ROLE ER ON EN.EMP_ID = ER.EMP_ID

Output: EN.EMP_NAME JAMES JAMES SARAH GARY JULIAN ER.EMP_ROLE DEVELOPER CONFIG MGR ANALYST ADMIN TESTER

SQL LEFT JOIN


(LEFT OUTER JOIN) (Relative Complement BA) The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in right table, the join will still return a row in the result, but with NULL in each column from right table. This means that a left join returns all the values from the left table, plus matched values from the right table or NULL in case of no matching join predicate.

18

Advanced SQL Skills


Query:
SELECT EN.EMP_NAME, ER.EMP_ROLE FROM EMPLOYEE_NAME EN LEFT JOIN EMPLOYEE_ROLE ER ON EN.EMP_ID = ER.EMP_ID

Output: EN.EMP_NAME JAMES JAMES GERARD SARAH SANDY GARY JULIAN ER.EMP_ROLE DEVELOPER CONFIG MGR <NULL> ANALYST <NULL> ADMIN TESTER

SQL RIGHT JOIN


(RIGHT OUTER JOIN) (Relative Complement AB) The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the left table. This means that if the ON clause matches 0 (zero) records in left table, the join will still return a row in the result, but with NULL in each column from left table. This means that a right join returns all the values from the right table, plus matched values from the left table or NULL in case of no matching join predicate.

Query:
SELECT EN.EMP_NAME, ER.EMP_ROLE FROM EMPLOYEE_NAME EN RIGHT JOIN EMPLOYEE_ROLE ER ON EN.EMP_ID = ER.EMP_ID

Output EN.EMP_NAME JAMES JAMES SARAH GARY JULIAN <NULL> ER.EMP_ROLE DEVELOPER CONFIG MGR ANALYST ADMIN TESTER COORDINATOR

SQL FULL JOIN


(FULL OUTER JOIN) (UNION A B )

The SQL FULL JOIN combines the results of both left and right outer joins. The joined table will contain all records from both tables, and fill in NULLs for missing matches on either side. All rows in all joined tables and queries are included, whether they match or not. Note: Many databases like MySQL or MS Access do not support FULL OUTER JOIN. 19

Advanced SQL Skills

Query:
SELECT EN.EMP_NAME, ER.EMP_ROLE FROM EMPLOYEE_NAME EN FULL OUTER JOIN EMPLOYEE_ROLE ER ON EN.EMP_ID = ER.EMP_ID

Output: EN.EMP_NAME JAMES JAMES GERARD SARAH SANDY GARY JULIAN <NULL> ER.EMP_ROLE DEVELOPER CONFIG MGR <NULL> ANALYST <NULL> ADMIN TESTER COORDINATOR

SELF JOIN
A self-join is a query in which a table is joined (compared) to itself. Self-joins are used to compare values in a column with other values in the same column in the same table. One practical use for self-joins: obtaining running counts and running totals in an SQL query. To list a table two times in the same query, you must provide a table alias for at least one of instance of the table name. This table alias helps the query processor determine whether columns should present data from the right or left version of the table. To understand the self join consider below table - EMPLOYEE_NAME EMP_ID EMP06 EMP02 EMP03 EMP04 EMP05 EMP01 Query
SELECT EN1.EMP_NAME AS Emp_Name , EN1.EMP_ID, EN2.EMP_NAME AS Report_To_NAME, EN2.EMP_ID AS REPORT_TO_ID FROM EMPLOYEE_NAME EN1, EMPLOYEE_NAME EN2 WHERE EN1.REPORT_TO_ID = EN2.EMP_ID

EMP_NAME REPORT_TO_ID JULIAN EMP01 GERARD EMP02 SARAH EMP02 SANDY EMP02 GARY EMP02 JAMES EMP02

20

Advanced SQL Skills

Output EMP_NAME GERARD SARAH SANDY GARY JAMES JULIAN EMP_ID EMP02 EMP03 EMP04 EMP05 EMP01 EMP06 REPORT_TO_NAME GERARD GERARD GERARD GERARD GERARD JAMES REPORT_TO_ID EMP02 EMP02 EMP02 EMP02 EMP02 EMP01

CROSS JOIN (CARTESIAN JOIN)


A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. Now if we consider Table 1(Employee_Name) and Table 2(Employee_Role), following query will results in 36 rows. Because Table has 6 records and Table 2 also has 6 records. And as per cartesion join, size of the result set will be # of records in Table 1 X # of records in Table 2. So 6 X 6 = 36 records. Now imagine same situation for bigger tables where we are having few thousands records. This will result in large no. of result set and will put huge strain on system resources compared to any benefit we get from Cartesian join. Most of the time Cartesian joins are produced by accident and we need to avoid using it without where clause or we have real reason for doing so. Query
SELECT EN.EMP_NAME, ER.EMP_ROLE FROM EMPLOYEE_NAME EN, EMPLOYEE_ROLE ER

Output NAME GERARD SARAH SANDY GARY JULIAN JAMES GERARD SARAH SANDY ROLE ANALYST ANALYST ANALYST ANALYST ANALYST ANALYST ADMIN ADMIN ADMIN

(Note: There are 27 more ro

(Note: This table has 27 more rows which are not shown here)

So by any means if you have to use cross join or Cartesian join , limit your results by adding whee clause in query.

21

Advanced SQL Skills

Query SELECT * FROM EMPLOYEE_NAME, EMPLOYEE_ROLE WHERE EMPLOYEE_ROLE.EMP_ROLE = 'DEVELOPER' Output EMP_ID EMP02 EMP03 EMP04 EMP05 EMP06 EMP01 EMP_NAME GERARD SARAH SANDY GARY JULIAN JAMES REPORT_TO_ID EMP02 EMP02 EMP02 EMP02 EMP01 EMP02 EMP_ID_1 EMP01 EMP01 EMP01 EMP01 EMP01 EMP01 EMP_ROLE DEVELOPER DEVELOPER DEVELOPER DEVELOPER DEVELOPER DEVELOPER

SQL INDEXES
An index can be created in the table to find data more quickly and efficiently. The users cant see indexes. They are used to speed up your search and execute query efficiently. Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against. Index can be created by using single or group of columns in a table. When index is created, it is assigned a ROWID for each row before it sorts out the data. Proper indexes are good for performance in large databases, but you need to be careful while creating index. Selection of fields depends on what you are using in your SQL queries. Syntax to create index on column
CREATE INDEX index_name ON table_name ( column1, column2.....);

22

S-ar putea să vă placă și