cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some...

14
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 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 (for example, = or <>,) to be used in comparing values from the columns. Joins can be categorized as: 1. Inner Joins 2. Cross Joins 3. Outer Joins (Full Outer Joins, Right Outer Joins, Left Outer Joins) 4. Self Joins 5. Natural Joins 6. Equi-Joins Inner joins can be specified in either the FROM or WHERE clauses. Outer joins can be specified in the FROM clause only. 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 ISO FROM clause join syntax is: FROM first_table join_type second_table [ON (join_condition)]

Transcript of cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some...

Page 1: cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some comparison operator like = or ). Inner joins use a comparison operator to match

JOINSBy using joins, you can retrieve data from two or more tables based on logical relationships between the tables. Joins indicate how Microsoft SQL Server 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 (for example, = or <>,) to be used in comparing values from

the columns.

Joins can be categorized as: 1. Inner Joins2. Cross Joins3. Outer Joins (Full Outer Joins, Right Outer Joins, Left Outer Joins)4. Self Joins5. Natural Joins6. Equi-Joins

Inner joins can be specified in either the FROM or WHERE clauses. Outer joins can be specified in the FROM clause only. 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 ISO FROM clause join syntax is:

FROM 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. The following is an example of a FROM clause join specification:

Page 2: cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some comparison operator like = or ). Inner joins use a comparison operator to match

TYPES OF JOINSJOIN TYPE DESCRIPTION

Inner joins

(the typical join operation, which uses some comparison operator like = or <>). 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 department number is the same in both the employee and department 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

RIGHT JOIN or RIGHT OUTER JOIN

FULL JOIN or FULL 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.

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.

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

Page 3: cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some comparison operator like = or ). Inner joins use a comparison operator to match

SQL JOIN QUERIESSample tablesAll subsequent explanations on join types in this article make use of the following two tables. The rows in these tables serve to illustrate the effect of different types of joins and join-predicates. In the following tables the DepartmentID column of the Department table (which can be designated as Department.DepartmentID) is the primary key, while Employee.DepartmentID is a foreign key.

Note: The "Marketing" Department currently has no listed employees. Also, employee "John" has not been assigned to any Department yet.

Script to create the tables

CREATE TABLE employee ( LastName varchar(25), DepartmentID int);

CREATE TABLE department ( DepartmentID int UNIQUE, DepartmentName varchar(25));

ALTER TABLE employee ADD CONSTRAINT fk_employee_deptFOREIGN KEY (DepartmentID)REFERENCES department(DepartmentID);

Page 4: cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some comparison operator like = or ). Inner joins use a comparison operator to match

Script to add data to the tables

INSERT INTO department VALUES (31, 'Sales');INSERT INTO department VALUES (33, 'Engineering');INSERT INTO department VALUES (34, 'Clerical');INSERT INTO department VALUES (35, 'Marketing');INSERT INTO employee VALUES ('Rafferty', 31);INSERT INTO employee VALUES ('Jones', 33);INSERT INTO employee VALUES ('Steinberg', 33);INSERT INTO employee VALUES ('Robinson', 34);INSERT INTO employee VALUES ('Smith', 34);INSERT INTO employee VALUES ('John', NULL);

1. Inner joinAn inner join is the most common join operation used in applications and can be regarded as the default join-type. Inner join creates a new result table by combining column values of two tables (A and B) based upon the join-predicate. The query compares each row of A with each row of B to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, column values for each matched pair of rows of A and B are combined into a result row. The result of the join can be defined as the outcome of first taking the Cartesian product (or cross-join) of all records in the tables (combining every record in table A with every record in table B)—then return all records which satisfy the join predicate. Actual SQL implementations normally use other approaches like a Hash join or a Sort-merge join where possible, since computing the Cartesian product is very inefficient.SQL specifies two different syntactical ways to express joins: "explicit join notation" and "implicit join notation".The "explicit join notation" uses the JOIN keyword to specify the table to join, and the ON keyword to specify the predicates for the join, as in the following example: SELECT * FROM employee INNER JOIN department ON employee.DepartmentID = department.DepartmentID;

The "implicit join notation" simply lists the tables for joining (in the FROM clause of the SELECT statement), using commas to separate them. Thus, it specifies a cross-join, and the WHERE clause may apply additional filter-predicates (which function comparably to the join-predicates in the explicit notation).

The query given above will join the Employee and Department tables using the DepartmentID column of both tables. Where the DepartmentID of these tables match (i.e. the join-predicate is satisfied), the query will combine the LastName, DepartmentID and DepartmentName columns from the two tables into a result row. Where the DepartmentID does not match, no result row is generated.Thus the result of the execution of query above will be:

Page 5: cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some comparison operator like = or ). Inner joins use a comparison operator to match

Note: Programmers should take special care when joining tables on columns that can contain NULL values, since NULL will never match any other value (or even NULL itself), unless the join condition explicitly uses the IS NULL or IS NOT NULL predicates.Notice that the employee "John" and the department "Marketing" do not appear in the query execution results. Neither of these has any matching records in the respective other table: "John" has no associated department, and no employee has the department ID 35. Thus, no information on John or on Marketing appears in the joined table. Depending on the desired results, this behavior may be a subtle bug. Outer joins may be used to avoid it.One can further classify inner joins as equi-joins, as natural joins, or as cross-joins.

2. Cross joinA cross join, cartesian join or product provides the foundation upon which all types of inner joins operate. A cross join returns the cartesian product of the sets of records from the two joined tables. Thus, it equates to an inner join where the join-condition always evaluates to True or where the join-condition is absent from the statement. In other words, a cross join combines every row in B with every row in A. The number of rows in the result set will be the number of rows in A times the number of rows in B.Thus, if A and B are two sets, then the cross join is written as A × B.The SQL code for a cross join lists the tables for joining (FROM), but does not include any filtering join-predicate.

Example of an explicit cross join:SELECT *FROM employee CROSS JOIN department;

Thus the result of the execution of query above will be:

Page 6: cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some comparison operator like = or ). Inner joins use a comparison operator to match

The cross join does not apply any predicate to filter records from the joined table. Programmers can further filter the results of a cross join by using a WHERE clause.

3. Outer joinsAn outer join does not require each record in the two joined tables to have a matching record. The joined table retains each record—even if no other matching record exists. Outer joins subdivide further into left outer joins, right outer joins, and full outer joins, depending on which table(s) one retains the rows from (left, right, or both). (In this case left and right refer to the two sides of the JOIN keyword.)No implicit join-notation for outer joins exists in standard SQL.

Left outer joinThe result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result—but with NULL in each column from B. This means that a left outer 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). If the right table returns one row and the

Page 7: cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some comparison operator like = or ). Inner joins use a comparison operator to match

left table returns more than one matching row for it, the values in the right table will be repeated for each distinct row on the left table.

For example, this allows us to find an employee's department, but still shows the employee(s) even when they have not been assigned to a department (contrary to the inner-join example above, where unassigned employees are excluded from the result).Example of a left outer join, with the additional result row italicized:

SELECT * FROM employee LEFT OUTER JOIN department ON employee.DepartmentID = department.DepartmentID;

Thus the result of the execution of query above will be:

Right outer joinsA right outer join (or right join) closely resembles a left outer join, except with the treatment of the tables reversed. Every row from the "right" table (B) will appear in the joined table at least once. If no matching row from the "left" table (A) exists, NULL will appear in columns from A for those records that have no match in B.A right outer join returns all the values from the right table and matched values from the left table (NULL in case of no matching join predicate).For example, this allows us to find each employee and his or her department, but still show departments that have no employees.

Page 8: cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some comparison operator like = or ). Inner joins use a comparison operator to match

Example right outer join, with the additional result row italicized:

SELECT * FROM employee RIGHT OUTER JOIN department ON employee.DepartmentID = department.DepartmentID;

Thus the result of the execution of query above will be:

In practice, explicit right outer joins are rarely used, since they can always be replaced with left outer joins (with the table order switched) and provide no additional functionality. The result above is produced also with a left outer join:

SELECT * FROM department LEFT OUTER JOIN employee ON employee.DepartmentID = department.DepartmentID;

Full outer joinConceptually, a full outer join combines the effect of applying both left and right outer joins. Where records in the FULL OUTER JOINed tables do not match, the result set will have NULL values for every column of the table that lacks a matching row. For those records that do match, a single row will be produced in the result set (containing fields populated from both tables).

Page 9: cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some comparison operator like = or ). Inner joins use a comparison operator to match

For example, this allows us to see each employee who is in a department and each department that has an employee, but also see each employee who is not part of a department and each department which doesn't have an employee.

Example full outer join:

SELECT * FROM employee FULL OUTER JOIN department ON employee.DepartmentID = department.DepartmentID;

Thus the result of the execution of query above will be:

Page 10: cs371database.files.wordpress.com …  · Web view(the typical join operation, which uses some comparison operator like = or ). Inner joins use a comparison operator to match

ASSIGNMENTGive brief description and Write down SQL queries for the following join types:

1) Equi-Join2) Natural Join3) Self Join

Project Related Task1) Write down queries for all the requirements in your project that require data from

multiple tables.