G C Reddy

Software Testing Complete Reference

SQL JOINS

JOINS

By using joins, you can retrieve data from two or more tables based on logical relationships between the tables. Joins indicate how Microsoft® SQL Server™ 2000 should use data from one table to select the rows in another table.

A join condition defines the way two tables are related in a query by:

  • Specifying the column from each table to be used for the join. A typical join condition specifies a foreign key from one table and its associated key in the other table.
  • Specifying a logical operator (=, <>, and so on) to be used in comparing values from the columns.

Joins can be specified in either the FROM or WHERE clauses. The join conditions combine with the WHERE and HAVING search conditions to control the rows that are selected from the base tables referenced in the FROM clause.

Specifying the join conditions in the FROM clause helps separate them from any other search conditions that may be specified in a WHERE clause, and is the recommended method for specifying joins. A simplified SQL-92 FROM clause join syntax is:

SELECT columnListFROM first_table join_type second_table [ON (join_condition)]

Join_type specifies what kind of join is performed: an inner, outer, or cross join. join_condition defines the predicate to be evaluated for each pair of joined rows. This is an example of a FROM clause join specification:

Although join conditions usually have equality comparisons (=), other comparison or relational operators can be specified, as can other predicates

When SQL Server processes joins, the query engine chooses the most efficient method (out of several possibilities) of processing the join. Although the physical execution of various joins uses many different optimizations, the logical sequence is:

  • The join conditions in the FROM clause are applied.
  • The join conditions and search conditions from the WHERE clause are applied.
  • The search conditions from the HAVING clause are applied.

Types of Joins

Join conditions can be specified in either the FROM or WHERE clauses; specifying them in the FROM clause is recommended. WHERE and HAVING clauses can also contain search conditions to further filter the rows selected by the join conditions.

Joins can be categorized as:

  • Inner joins (the typical join operation, which uses some comparison operator like = or <>). These include equi-joins and natural joins.

Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. For example, retrieving all rows where the student identification number is the same in both the students and courses tables.

  • Outer joins. Outer joins can be a left, a right, or full outer join.

Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause:

    • LEFT JOIN or LEFT OUTER JOIN

The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.

    • RIGHT JOIN or RIGHT OUTER JOIN.

A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.

    • FULL JOIN or FULL OUTER JOIN.

A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.

  • Cross joins.

Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products.

Case Study:

When you look at the example tables below, notice that:

  • The “Employee_ID” column is the primary key of the “Employees” table
  • The “Prod_ID” column is the primary key of the “Orders” table
  • The “Employee_ID” column in the “Orders” table is used to refer to the persons in the “Employees” table without using their names

Employees:

Employee_ID Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari

Orders:

Prod_ID Product Employee_ID
234 Printer 01
657 Table 03
865 Chair 03


Using Joins

Example INNER JOIN

Syntax

SELECT field1, field2, field3
FROM first_table
INNER JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield

Who has ordered a product, and what did they order?

SELECT Employees.Name, Orders.Product
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID

The INNER JOIN returns all rows from both tables where there is a match. If there are rows in Employees that do not have matches in Orders, those rows will not be listed.

Result

Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair

Example LEFT JOIN

Syntax

SELECT field1, field2, field3
FROM first_table
LEFT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield

List all employees, and their orders – if any.

SELECT Employees.Name, Orders.Product
FROM Employees
LEFT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID

The LEFT JOIN returns all the rows from the first table (Employees), even if there are no matches in the second table (Orders). If there are rows in Employees that do not have matches in Orders, those rows also will be listed.

Result

Name Product
Hansen, Ola Printer
Svendson, Tove
Svendson, Stephen Table
Svendson, Stephen Chair
Pettersen, Kari

Example RIGHT JOIN

Syntax

SELECT field1, field2, field3
FROM first_table
RIGHT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield

List all orders, and who has ordered – if any.

SELECT Employees.Name, Orders.Product
FROM Employees
RIGHT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID

The RIGHT JOIN returns all the rows from the second table (Orders), even if there are no matches in the first table (Employees). If there had been any rows in Orders that did not have matches in Employees, those rows also would have been listed.

Result

Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair

Example

Who ordered a printer?

SELECT Employees.Name
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
WHERE Orders.Product = 'Printer'

Result

Name
Hansen, Ola

Self Join:

Joining a table to it self is called as self join. In a self-join, we have to use two copies of the same table twice. To distinguish between the two copies we have to use duplicate names to the tables called as table aliases.

Example:

Get the employees and corresponding manager names from the following emp table. In this table mgrid filed refers the id of the manager for the employee. These are nothing but empid’s. It means, any one of the employees will become the manager for other employee.

EMP
Empid Empname mgrid
100 Anil 104
101 Balu 103
102 Santosh 100
103 Vivek 104
104 Jagan 102
SELECT a.empid,a.empname,a.mgrid,b.empname ManagerName FROMEMP a INNER JOIN EMP b

ON a.mgrid=b.empid

BUILT IN FUNCTIONS

SQL Server 2000 provides a lot of functions, which can be used as calculated fields as part of column lists in a SELECT statement. Such functions are called as Built-in Functions.

Arithmetic operators

The arithmetic operators supported by SQL server are:

Ø       + for addition

Ø       – for subtraction

Ø       / for division

Ø       * for multiplication

Ø       % for modulo

The modulo arithmetic operator is used to obtain the remainder of two divisible numeric integer values. It cannot be used with money data type columns.

All the arithmetic operators can be used in the SELECT list with the column names and numeric constants in a combination.

Example:

SELECT title_id, price, price+5, ytd_sales*5 FROM titles.

When any arithmetic operation is performed on a NULL value, the result is always NULL because NULL values have no explicitly assigned values. Arithmetic operations can be performed on more than one column at a time. Consider the following query code:

SELECT Title_Id=title_id, sValue=ytd_sales*price FROM tiles

The above query computes the product of ytd_sales and price from the titles table and displays the output with the user-defined headings.

Some rules regarding the usage of arithmetic operators are:

Ø       Arithmetic operations can be performed on numeric columns or numeric constants.

Ø       The modulo (%) operator cannot be used with columns of money, smallmoney, float or real datatypes.

The syntax is:

SELECT function_name(parameters)

Tags: , ,

3 Responses to “SQL JOINS”


Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to G C Reddy QTP Group
Email:
Visit this group

gc