Sei sulla pagina 1di 26

Foreign key

From Wikipedia, the free encyclopedia

Jump to: navigation, search

In the context of relational databases, a foreign key is a referential constraint between two
tables.[1] The foreign key identifies a column or a set of columns in one (referencing) table that
refers to set of columns in another (referenced) table. The columns in the referencing table must
be the primary key or other candidate key in the referenced table. The values in one row of the
referencing columns must occur in a single row in the referenced table. Thus, a row in the
referencing table cannot contain values that don't exist in the referenced table (except potentially
NULL). This way references can be made to link information together and it is an essential part
of database normalization. Multiple rows in the referencing table may refer to the same row in
the referenced table. Most of the time, it reflects the one (master table, or referenced table) to
many (child table, or referencing table) relationship.

The referencing and referenced table may be the same table, i.e. the foreign key refers back to
the same table. Such a foreign key is known in SQL:2003 as a self-referencing or recursive
foreign key.

A table may have multiple foreign keys, and each foreign key can have a different referenced
table. Each foreign key is enforced independently by the database system. Therefore, cascading
relationships between tables can be established using foreign keys.

Improper foreign key/primary key relationships or not enforcing those relationships are often the
source of many database and data modeling problems.

Contents
[hide]

• 1 Defining Foreign Keys


• 2 Referential Actions
o 2.1 CASCADE
o 2.2 RESTRICT
o 2.3 NO ACTION
o 2.4 SET NULL
o 2.5 SET DEFAULT
o 2.6 Triggers
• 3 Example
• 4 See also
• 5 References
• 6 External links

[edit] Defining Foreign Keys


Foreign keys are defined in the ANSI SQL Standard, through a FOREIGN KEY constraint. The
syntax to add such a constraint to an existing table is defined in SQL:2003 as shown below.
Omitting the column list in the REFERENCES clause implies that the foreign key shall reference
the primary key of the referenced table.

ALTER TABLE <table identifier>


ADD [ CONSTRAINT <constraint identifier> ]
FOREIGN KEY ( <column expression> {, <column expression>}... )
REFERENCES <table identifier> [ ( <column expression> {, <column
expression>}... ) ]
[ ON UPDATE <referential action> ]
[ ON DELETE <referential action> ]

Likewise, foreign keys can be defined as part of the CREATE TABLE SQL statement.

CREATE TABLE table_name (


id INTEGER PRIMARY KEY,
col2 CHARACTER VARYING(20),
col3 INTEGER,
...
CONSTRAINT col3_fk FOREIGN KEY(col3)
REFERENCES other_table(key_col) ON DELETE CASCADE,
... )

If the foreign key is a single column only, the column can be marked as such using the following
syntax:

CREATE TABLE table_name (


id INTEGER PRIMARY KEY,
col2 CHARACTER VARYING(20),
col3 INTEGER REFERENCES other_table(column_name),
... )

[edit] Referential Actions


Because the Database Management System enforces referential constraints, it must ensure data
integrity if rows in a referenced table are to be deleted (or updated). If dependent rows in
referencing tables still exist, those references have to be considered. SQL:2003 specifies 5
different referential actions that shall take place in such occurrences:

• CASCADE
• RESTRICT
• NO ACTION
• SET NULL
• SET DEFAULT

[edit] CASCADE

Whenever rows in the master (referenced) table are deleted, the respective rows of the child
(referencing) table with a matching foreign key column will get deleted as well. This is called a
cascade delete.

Example Tables: Customer(customer_id, cname, caddress) and Order(customer_id, products,


payment)

Customer is the master table and Order is the child table, where 'customer_id' is the foreign key
in Order and represents the customer who placed the order. When a row of Customer is deleted,
any Order row matching the deleted Customer's customer_id will also be deleted.

[edit] RESTRICT

A value cannot be updated or deleted when a row exists in a foreign key table that references the
value in the referenced table.

Similarly,

[edit] NO ACTION

NO ACTION and RESTRICT are very much alike. The main difference between NO ACTION
and RESTRICT is that with NO ACTION the referential integrity check is done after trying to
alter the table. RESTRICT does the check before trying to execute the UPDATE or DELETE
statement. Both referential actions act the same if the referential integrity check fails: the
UPDATE or DELETE statement will result in an error.

In other words, when an UPDATE or DELETE statement is executed on the referenced table
using the referential action NO ACTION, the DBMS verifies at the end of the statement
execution that none of the referential relationships are violated. This is different from
RESTRICT, which assumes at the outset that the operation will violate the constraint. Using NO
ACTION, the triggers or the semantics of the statement itself may yield an end state in which no
foreign key relationships are violated by the time the constraint is finally checked, thus allowing
the statement to complete successfully.

[edit] SET NULL

The foreign key values in the referencing row are set to NULL when the referenced row is
updated or deleted. This is only possible if the respective columns in the referencing table are
nullable. Due to the semantics of NULL, a referencing row with NULLs in the foreign key
columns does not require a referenced row.

[edit] SET DEFAULT


Similarly to SET NULL, the foreign key values in the referencing row are set to the column
default when the referenced row is updated or deleted.

[edit] Triggers

Referential actions are generally implemented as implied triggers (i.e. triggers with system-
generated names, often hidden.) As such, they are subject to the same limitations as user-defined
triggers, and their order of execution relative to other triggers may need to be considered; in
some cases it may become necessary to replace the referential action with its equivalent user-
defined trigger to ensure proper execution order, or to work around mutating-table limitations.

Another important limitation appears with transaction isolation: your changes to a row may not
be able to fully cascade because the row is referenced by data your transaction cannot "see", and
therefore cannot cascade onto. An example: while your transaction is attempting to renumber a
customer account, a simultaneous transaction is attempting to create a new invoice for that same
customer; while a CASCADE rule may fix all the invoice rows your transaction can see to keep
them consistent with the renumbered customer row, it won't reach into another transaction to fix
the data there; because the database cannot guarantee consistent data when the two transactions
commit, one of them will be forced to rollback (often on a first-come-first-served basis.)

[edit] Example
As a first example to illustrate foreign keys, suppose an accounts database has a table with
invoices and each invoice is associated with a particular supplier. Supplier details (such as
address or phone number) are kept in a separate table; each supplier is given a 'supplier number'
to identify it. Each invoice record has an attribute containing the supplier number for that
invoice. Then, the 'supplier number' is the primary key in the Supplier table. The foreign key in
the Invoices table points to that primary key. The relational schema is the following. Primary
keys are marked in bold, and foreign keys are marked in italics.

Supplier ( SupplierNumber, Name, Address, Type )


Invoices ( InvoiceNumber, SupplierNumber, Text )

The corresponding Data Definition Language statement is as follows.

CREATE TABLE Supplier (


SupplierNumber INTEGER NOT NULL,
Name VARCHAR(20) NOT NULL,
Address VARCHAR(50) NOT NULL,
Type VARCHAR(10),
CONSTRAINT supplier_pk PRIMARY KEY(SupplierNumber),
CONSTRAINT number_value CHECK (SupplierNumber > 0) )

CREATE TABLE Invoices (


InvoiceNumber INTEGER NOT NULL,
SupplierNumber INTEGER NOT NULL,
Text VARCHAR(4096),
CONSTRAINT invoice_pk PRIMARY KEY(InvoiceNumber),
CONSTRAINT inumber_value CHECK (InvoiceNumber > 0),
CONSTRAINT supplier_fk FOREIGN KEY(SupplierNumber)
REFERENCES Supplier(SupplierNumber)
ON UPDATE CASCADE ON DELETE RESTRICT )

Trigger
A database trigger is procedural code that is automatically executed in response to certain
events on a particular table or view in a database. The trigger is mostly used for keeping the
integrity of the information on the database. For example, when a new record (representing a
new worker) is added to the employees table, new records should be created also in the tables of
the taxes, vacations, and salaries.

Contents
[hide]

• 1 The need and the usage


• 2 DML Triggers
• 3 Triggers in Oracle
o 3.1 Schema-level triggers
o 3.2 Mutating tables
• 4 Triggers in Microsoft SQL Server
• 5 Triggers in PostgreSQL
• 6 Triggers in Firebird
• 7 Triggers in MySQL
• 8 Triggers in IBM Midrange Systems
• 9 Triggers in IBM DB2 LUW
• 10 Triggers in SQLite

• 11 External links

[edit] The need and the usage


Triggers are commonly used to:

• prevent changes (e.g. prevent an invoice from being changed after it's been mailed out)
• log changes (e.g. keep a copy of the old data)
• audit changes (e.g. keep a log of the users and roles involved in changes)
• enhance changes (e.g. ensure that every change to a record is time-stamped by the
server's clock, not the client's)
• enforce business rules (e.g. require that every invoice have at least one line item)
• execute business rules (e.g. notify a manager every time an employee's bank account
number changes)
• replicate data (e.g. store a record of every change, to be shipped to another database later)
• enhance performance (e.g. update the account balance after every detail transaction, for
faster queries)

The examples above are called Data Manipulation Language (DML) triggers because the triggers
are defined as part of the Data Manipulation Language and are executed at the time the data are
manipulated. Some systems also support non-data triggers, which fire in response to Data
Definition Language (DDL) events such as creating tables, or runtime events such as logon,
commit, and rollback. Such DDL triggers can be used for auditing purposes.

The following are major features of database triggers and their effects:

• triggers do not accept parameters or arguments (but may store affected-data in temporary
tables)
• triggers cannot perform commit or rollback operations because they are part of the
triggering SQL statement (only through autonomous transactions)
• triggers can cancel a requested operation
• triggers can cause mutating table errors

[edit] DML Triggers


There are typically three triggering events that cause data triggers to 'fire':

• INSERT event (as a new record is being inserted into the database).
• UPDATE event (as a record is being changed).
• DELETE event (as a record is being deleted).

Structurally, triggers are either "row triggers" or "statement triggers". Row triggers define an
action for every row of a table, while statement triggers occur only once per INSERT, UPDATE,
or DELETE statement. DML triggers cannot be used to audit data retrieval via SELECT
statements, because SELECT is not a triggering event.

Furthermore, there are "BEFORE triggers" and "AFTER triggers" which run in addition to any
changes already being made to the database, and "INSTEAD OF trigger" which fully replace the
database's normal activity.

Triggers do not accept parameters, but they do receive information in the form of implicit
variables. For row-level triggers, these are generally OLD and NEW variables, each of which
have fields corresponding to the columns of the affected table or view; for statement-level
triggers, something like SQL Server's Inserted and Deleted tables may be provided so the trigger
can see all the changes being made.

For data triggers, the general order of operations will be as follows:

1. a statement requests changes on a row: OLD represents the row as it was before the
change (or is all-null for inserted rows), NEW represents the row after the changes (or is
all-null for deleted rows)
2. each statement-level BEFORE trigger is fired
3. each row-level BEFORE trigger fires, and can modify NEW (but not OLD); each trigger
can see NEW as modified by its predecessor, they are chained together
4. if an INSTEAD OF trigger is defined, it is run using OLD and NEW as available at this
point
5. if no INSTEAD OF trigger is defined, the database modifies the row according to its
normal logic; for updatable views, this may involve modifying one or more other tables
to achieve the desired effect; if a view is not updatable, and no INSTEAD OF trigger is
provided, an error is raised
6. each row-level AFTER trigger fires, and is given NEW and OLD, but its changes to
NEW are either disallowed or disregarded
7. each statement-level AFTER trigger is fired
8. implied triggers are fired, such as referential actions in support of foreign key constraints:
on-update or on-delete CASCADE, SET NULL, and SET DEFAULT rules

In ACID databases, an exception raised in a trigger will cause the entire stack of operations to be
rolled back, including the original statement.

[edit] Triggers in Oracle


In addition to triggers that fire when data is modified, Oracle 9i supports triggers that fire when
schema objects (that is, tables) are modified and when user logon or logoff events occur. These
trigger types are referred to as "Schema-level triggers".

[edit] Schema-level triggers

• After Creation
• Before Alter
• After Alter
• Before Drop
• After Drop
• Before Logoff
• After Logon

The two main types of triggers are:

1. Row Level Trigger


2. Statement Level Trigger

Based on the 2 types of classifications, we could have 12 types of triggers.

[edit] Mutating tables

When a single SQL statement modifies several rows of a table at once, the order of the
operations is not well-defined; there is no "order by" clause on "update" statements, for example.
Row-level triggers are executed as each row is modified, so the order in which trigger code is run
is also not well-defined. Oracle protects the programmer from this uncertainty by preventing
row-level triggers from modifying other rows in the same table – this is the "mutating table" in
the error message. Side-effects on other tables are allowed, however.

One solution is to have row-level triggers place information into a temporary table indicating
what further changes need to be made, and then have a statement-level trigger fire just once, at
the end, to perform the requested changes and clean up the temporary table.

Because a foreign key's referential actions are implemented via implied triggers, they are
similarly restricted. This may become a problem when defining a self-referential foreign key, or
a cyclical set of such constraints, or some other combination of triggers and CASCADE rules
(e.g. user deletes a record from table A, CASCADE rule on table A deletes a record from table
B, trigger on table B attempts to SELECT from table A, error occurs.)

[edit] Triggers in Microsoft SQL Server


Microsoft SQL Server supports triggers either after or instead of an insert, update, or delete
operation. They can be set on tables and views with the constraint that a view can be referenced
only by an INSTEAD OF trigger.

Microsoft SQL Server 2005 introduced support for Data Definition Language (DDL) triggers,
which can fire in reaction to a very wide range of events, including:

• Drop table
• Create table
• Alter table
• Login events

A full list is available on MSDN.

Performing conditional actions in triggers (or testing data following modification) is done
through accessing the temporary Inserted and Deleted tables.

[edit] Triggers in PostgreSQL


PostgreSQL introduced support for triggers in 1997. The following functionality in SQL:2003 is
not implemented in PostgreSQL:

• SQL allows triggers to fire on updates to specific columns; As of version 9.0 of


PostgreSQL this feature is also implemented in PostgreSQL.
• The standard allows the execution of a number of SQL statements other than SELECT,
INSERT, UPDATE, such as CREATE TABLE as the triggered action.

Synopsis:
SELECT * FROM MY_TABLE;
UPDATE MY_TABLE SET A = 5;
INSERT INTO MY_TABLE VALUES (3, 'aaa');

[edit] Triggers in Firebird


Firebird supports multiple row-level, BEFORE or AFTER, INSERT, UPDATE, DELETE (or
any combination thereof) triggers per table, where they are always "in addition to" the default
table changes, and the order of the triggers relative to each other can be specified where it would
otherwise be ambiguous (POSITION clause.) Triggers may also exist on views, where they are
always "instead of" triggers, replacing the default updatable view logic. (Before version 2.1,
triggers on views deemed updatable would run in addition to the default logic.)

Firebird does not raise mutating table exceptions (like Oracle), and triggers will by default both
nest and recurse as required (SQL Server allows nesting but not recursion, by default.) Firebird's
triggers use NEW and OLD context variables (not Inserted and Deleted tables,) and provide
UPDATING, INSERTING, and DELETING flags to indicate the current usage of the trigger.

{CREATE | RECREATE | CREATE OR ALTER} TRIGGER name FOR {TABLE name | VIEW
name}
[ACTIVE | INACTIVE]
{BEFORE | AFTER}
{INSERT [OR UPDATE] [OR DELETE] | UPDATE [OR INSERT] [OR DELETE] | DELETE
[OR UPDATE] [OR INSERT] }
[POSITION n] AS
BEGIN
...
END

As of version 2.1, Firebird additionally supports the following database-level triggers:

• CONNECT (exceptions raised here prevent the connection from completing)


• DISCONNECT
• TRANSACTION START
• TRANSACTION COMMIT (exceptions raised here prevent the transaction from
committing, or preparing if a two-phase commit is involved)
• TRANSACTION ROLLBACK

Database-level triggers can help enforce multi-table constraints, or emulate materialized views.
If an exception is raised in a TRANSACTION COMMIT trigger, the changes made by the
trigger so far are rolled back and the client application is notified, but the transaction remains
active as if COMMIT had never been requested; the client application can continue to make
changes and re-request COMMIT.

Syntax for database triggers:

{CREATE | RECREATE | CREATE OR ALTER} TRIGGER name


[ACTIVE | INACTIVE] ON
{CONNECT | DISCONNECT | TRANSACTION START | TRANSACTION COMMIT | TRANSACTION
ROLLBACK}
[POSITION n] AS
BEGIN
...
END

[edit] Triggers in MySQL


MySQL 5.0.2 introduced support for triggers. Some of the triggers MYSQL supports are

• Insert Trigger
• Update Trigger
• Delete Trigger

The SQL:2003 standard mandates that triggers give programmers access to record variables by
means of a syntax such as REFERENCING NEW AS n. For example, if a trigger is monitoring for
changes to a salary column one could write a trigger like the following:

CREATE TRIGGER salary_trigger


BEFORE UPDATE ON employee_table
REFERENCING NEW ROW AS n, OLD ROW AS o
FOR EACH ROW
IF n.salary <> o.salary THEN

END IF;
;

[edit] Triggers in IBM Midrange Systems


IBM Midrange Systems (AS/400, iSeries, etc.) support triggers on Insert, Update, and Delete
operations to DB2 physical files ("tables" in SQL parlance), both before and after the operation
occurs. Trigger programs may be created in any high-level language, or in MI. They are attached
to files with the ADDPFTRG command, and removed with the RMVPFTRG command. A
DSPFD on a physical file returns an entire section on attached triggers, and the PRTTRGPGM
command will generate a spooled report on all triggers in a library.

[edit] Triggers in IBM DB2 LUW


IBM DB2 for distributed systems known as DB2 for LUW (LUW means Linux Unix Windows)
supports 3 trigger types: Before trigger, After trigger and Instead of trigger. Both statement level
and row level triggers are supported. If there are more triggers for same operation on table then
firing order is determined by trigger creation data. Since version 9.7 IBM DB2 supports
autonomous transactions [1].

Before trigger is for checking data and deciding if operation should be permitted. If exception is
thrown from before trigger then operation is aborted and no data are changed. In DB2 before
triggers are read only — you cant modify data in before triggers. After triggers are designed for
post processing after requested change was performed. After triggers can write data into tables
and unlike some other databases you can write into any table including table on which trigger
operates. Instead of triggers are for making views writeable.

Triggers are usually programmed in SQL PL language.

[edit] Triggers in SQLite


CREATE [TEMP | TEMPORARY] TRIGGER [IF NOT EXISTS] [database_name .]
trigger_name
[BEFORE | AFTER | INSTEAD OF] {DELETE | INSERT | UPDATE [OF column_name [,
column_name]...]} ON {table_name | view_name}
[FOR EACH ROW] [WHEN condition]
BEGIN
...
END

SQLite only supports row-level triggers, not statement-level triggers.

Updateable views, which are not supported in SQLite, can be emulated with INSTEAD OF
triggers.

Understand the IO characteristics of SQL Server and the specific IO requirements /


characteristics of your application.
In order to be successful in designing and deploying storage for your SQL Server application, you
need to have an understanding of your application’s IO characteristics and a basic
understanding of SQL Server IO patterns. Performance monitor is the best place to capture this
information for an existing application. Some of the questions you should ask yourself here are:
•What is the read vs. write ratio of the application?
•What are the typical IO rates (IO per second, MB/s & size of the IOs)? Monitor the perfmon
counters:
1.Average read bytes/sec, average write bytes/sec
2.Reads/sec, writes/sec
3.Disk read bytes/sec, disk write bytes/sec
4.Average disk sec/read, average disk sec/write
5.Average disk queue length
•How much IO is sequential in nature, and how much IO is random in nature? Is this primarily an
OLTP application or a Relational Data Warehouse application?

An SQL JOIN clause combines records from two or more tables in a database.[1] It creates a set
that can be saved as a table or used as is. A JOIN is a means for combining fields from two tables
by using values common to each. ANSI standard SQL specifies four types of JOINs: INNER,
OUTER, LEFT, and RIGHT. In special cases, a table (base table, view, or joined table) can JOIN to
itself in a self-join.
A programmer writes a JOIN predicate to identify the records for joining. If the evaluated
predicate is true, the combined record is then produced in the expected format, a record set or a
temporary table, for example.

Contents
[hide]

• 1 Sample tables
• 2 Inner join
o 2.1 Equi-join
o 2.2 Natural join
o 2.3 Cross join
• 3 Outer joins
o 3.1 Left outer join
o 3.2 Right outer joins
o 3.3 Full outer join
• 4 Self-join
o 4.1 Example
• 5 Merge Rows
o 5.1 MySQL
o 5.2 PostgreSQL
• 6 Alternatives
• 7 Implementation
o 7.1 Join algorithms
 7.1.1 Nested loops
• 8 See also
• 9 Notes
• 10 References

• 11 External links

[edit] Sample tables


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

Employee Table

LastNa Departme
me ntID

Rafferty 31
Jones 33

Steinber
33
g

Robinso
34
n

Smith 34

John NULL

Department Table

Departme DepartmentN
ntID ame

31 Sales

33 Engineering

34 Clerical

35 Marketing

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 DATABASE join_example;


USE join_example;
CREATE TABLE `employee` (
`LastName` varchar(25),
`DepartmentID` int(4),
UNIQUE KEY `LastName` (`LastName`)
);
CREATE TABLE `department` (
`DepartmentID` int(4),
`DepartmentName` varchar(25),
UNIQUE KEY `DepartmentID` (`DepartmentID`)
);
ALTER TABLE employee ADD CONSTRAINT fk_employee_dept FOREIGN KEY
(DepartmentID) REFERENCES department(DepartmentID);

Script to add data to the tables


SET FOREIGN_KEY_CHECKS=0;
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);
INSERT INTO `department` VALUES (31, 'Sales');
INSERT INTO `department` VALUES (33, 'Engineering');
INSERT INTO `department` VALUES (34, 'Clerical');
INSERT INTO `department` VALUES (35, 'Marketing');
SET FOREIGN_KEY_CHECKS=1;

[edit] Inner join


An 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 following example shows a query which is equivalent to the one from the previous example,
but this time written using the implicit join notation:

SELECT *
FROM employee, department
WHERE employee.DepartmentID = department.DepartmentID
The queries given in the examples 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 either of the two queries above will be:

Employee.Last Employee.Depart Department.Departm Department.Depart


Name mentID entName mentID

Robinson 34 Clerical 34

Jones 33 Engineering 33

Smith 34 Clerical 34

Steinberg 33 Engineering 33

Rafferty 31 Sales 31

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.

[edit] Equi-join

An equi-join, also known as an equijoin, is a specific type of comparator-based join, or theta


join, that uses only equality comparisons in the join-predicate. Using other comparison operators
(such as <) disqualifies a join as an equi-join. The query shown above has already provided an
example of an equi-join:

SELECT *
FROM employee
INNER JOIN department
ON employee.DepartmentID = department.DepartmentID

SQL provides an optional shorthand notation for expressing equi-joins, by way of the USING
construct (Feature ID F402):
SELECT *
FROM employee
INNER JOIN department
USING (DepartmentID)

The USING construct is more than mere syntactic sugar, however, since the result set differs from
the result set of the version with the explicit predicate. Specifically, any columns mentioned in
the USING list will appear only once, with an unqualified name, rather than once for each table in
the join. In the above case, there will be a single DepartmentID column and no
employee.DepartmentID or department.DepartmentID.

The USING clause is not supported by SQL Server 2005.

[edit] Natural join

A natural join offers a further specialization of equi-joins. The join predicate arises implicitly by
comparing all columns in both tables that have the same column-name in the joined tables. The
resulting joined table contains only one column for each pair of equally-named columns.

The above sample query for inner joins can be expressed as a natural join in the following way:

SELECT *
FROM employee NATURAL JOIN department

As with the explicit USING clause, only one DepartmentID column occurs in the joined table,
with no qualifier:

Departme Employee.Last Department.Departme


ntID Name ntName

34 Smith Clerical

33 Jones Engineering

34 Robinson Clerical

33 Steinberg Engineering

31 Rafferty Sales

[edit] Cross join

A 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

Example of an implicit cross join:

SELECT *
FROM employee, department;
Employee.Last Employee.Depart Department.Departm Department.Depart
Name mentID entName mentID

Rafferty 31 Sales 31

Jones 33 Sales 31

Steinberg 33 Sales 31

Smith 34 Sales 31

Robinson 34 Sales 31

John NULL Sales 31

Rafferty 31 Engineering 33

Jones 33 Engineering 33

Steinberg 33 Engineering 33

Smith 34 Engineering 33

Robinson 34 Engineering 33

John NULL Engineering 33

Rafferty 31 Clerical 34

Jones 33 Clerical 34

Steinberg 33 Clerical 34

Smith 34 Clerical 34

Robinson 34 Clerical 34
John NULL Clerical 34

Rafferty 31 Marketing 35

Jones 33 Marketing 35

Steinberg 33 Marketing 35

Smith 34 Marketing 35

Robinson 34 Marketing 35

John NULL Marketing 35

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.

[edit] Outer joins


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

[edit] Left outer join

The 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 left table returns one row and the right table returns
more than one matching row for it, the values in the left table will be repeated for each distinct
row on the right 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
Employee.Last Employee.Depart Department.Departm Department.Depart
Name mentID entName mentID

Jones 33 Engineering 33

Rafferty 31 Sales 31

Robinson 34 Clerical 34

Smith 34 Clerical 34

John NULL NULL NULL

Steinberg 33 Engineering 33

[edit] Right outer joins

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

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

SELECT *
FROM employee RIGHT OUTER JOIN department
ON employee.DepartmentID = department.DepartmentID
Employee.Last Employee.Depart Department.Departm Department.Depart
Name mentID entName mentID

Smith 34 Clerical 34

Jones 33 Engineering 33

Robinson 34 Clerical 34

Steinberg 33 Engineering 33

Rafferty 31 Sales 31
NULL NULL Marketing 35
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

[edit] Full outer join

A full outer 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.

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
Employee.Last Employee.Depart Department.Departm Department.Depart
Name mentID entName mentID

Smith 34 Clerical 34

Jones 33 Engineering 33

Robinson 34 Clerical 34

John NULL NULL NULL

Steinberg 33 Engineering 33

Rafferty 31 Sales 31
NULL NULL Marketing 35

Some database systems (like MySQL) do not support this functionality directly, but they can
emulate it through the use of left and right outer joins and unions. The same example can appear
as follows:

SELECT *
FROM employee
LEFT JOIN department
ON employee.DepartmentID = department.DepartmentID
UNION
SELECT *
FROM employee
RIGHT JOIN department
ON employee.DepartmentID = department.DepartmentID

SQLite does not support right join, so outer join can be emulated as follows:

SELECT employee.*, department.*


FROM employee
LEFT JOIN department
ON employee.DepartmentID = department.DepartmentID
UNION ALL
SELECT employee.*, department.*
FROM department
LEFT JOIN employee
ON employee.DepartmentID = department.DepartmentID
WHERE employee.DepartmentID IS NULL

[edit] Self-join
A self-join is joining a table to itself.[2] This is best illustrated by the following example.

[edit] Example

A query to find all pairings of two employees in the same country is desired. If you had two
separate tables for employees and a query which requested employees in the first table having
the same country as employees in the second table, you could use a normal join operation to find
the answer table. However, all the employee information is contained within a single large table.
[3]

Considering a modified Employee table such as the following:

Employee Table

Employe LastNa Departme


Country
eID me ntID

123 Rafferty Australia 31

124 Jones Australia 33

Steinber
145 Australia 33
g

Robinso United
201 34
n States

305 Smith Germany 34

306 John Germany


NULL
An example solution query could be as follows:

SELECT F.EmployeeID, F.LastName, S.EmployeeID, S.LastName, F.Country


FROM Employee F, Employee S
WHERE F.Country = S.Country
AND F.EmployeeID < S.EmployeeID
ORDER BY F.EmployeeID, S.EmployeeID;

Which results in the following table being generated.

Employee Table after Self-join by Country

Employe LastNa Employe LastNa Countr


eID me eID me y

Australi
123 Rafferty 124 Jones
a

Steinber Australi
123 Rafferty 145
g a

Steinber Australi
124 Jones 145
g a

Germa
305 Smith 306 John
ny

For this example, note that:

• F and S are aliases for the first and second copies of the employee table.
• The condition F.Country = S.Country excludes pairings between employees
in different countries. The example question only wanted pairs of employees
in the same country.
• The condition F.EmployeeID < S.EmployeeID excludes pairings where the
EmployeeIDs are the same.
• F.EmployeeID < S.EmployeeID also excludes duplicate pairings. Without it, the
following less useful table would be generated (the table below displays only
the "Germany" portion of the result):

Employe LastNa Employe LastNa Countr


eID me eID me y
Germa
305 Smith 305 Smith
ny

Germa
305 Smith 306 John
ny

Germa
306 John 305 Smith
ny

Germa
306 John 306 John
ny

Only one of the two middle pairings is needed to satisfy the original question, and the topmost
and bottommost are of no interest at all in this example.

[edit] Merge Rows


To be able to do a select so as to merge multiple rows into 1 row : "group_concat notation".

MySQL uses the group_concat keyword to achieve that goal, and PostgreSQL group_concat
has to be manually added since it doesn't already exist. As in the following example:

Using the Employee


Table:

LastNa Departmen
me tID

Rafferty 31

Jones 33

Steinber
33
g

Robinso
34
n

Smith 34

John NULL

to achieve the following


results Table

DepartmentI LastNames
D
NULL John

31 Rafferty

Jones,
33
Steinberg

Robinson,
34
Smith

[edit] MySQL
SELECT DepartmentID, group_concat(LastName) AS LastNames
FROM employee
GROUP BY DepartmentID

[edit] PostgreSQL

First the function _group_concat and aggregate group_concat need to be created before that
query can be possible.

CREATE OR REPLACE FUNCTION _group_concat(text, text)


RETURNS text AS $$
SELECT CASE
WHEN $2 IS NULL THEN $1
WHEN $1 IS NULL THEN $2
ELSE $1 operator(pg_catalog.||) ', ' operator(pg_catalog.||) $2
END
$$ IMMUTABLE LANGUAGE SQL;

error// JOIN SQL


CREATE AGGREGATE group_concat (
BASETYPE = text,
SFUNC = _group_concat,
STYPE = text
);

SELECT DepartmentID, group_concat(LastName) AS LastNames


FROM employee
GROUP BY DepartmentID

[edit] Alternatives
The effect of outer joins can also be obtained using correlated subqueries. For example

SELECT employee.LastName, employee.DepartmentID, department.DepartmentName


FROM employee LEFT OUTER JOIN department
ON employee.DepartmentID = department.DepartmentID

can also be written as

SELECT employee.LastName, employee.DepartmentID,


(SELECT department.DepartmentName
FROM department
WHERE employee.DepartmentID = department.DepartmentID ) AS DepartmentName
FROM employee

[edit] Implementation
Much work in database-systems has aimed at efficient implementation of joins, because
relational systems commonly call for joins, yet face difficulties in optimising their efficient
execution. The problem arises because inner joins operate both commutatively and associatively.
In practice, this means that the user merely supplies the list of tables for joining and the join
conditions to use, and the database system has the task of determining the most efficient way to
perform the operation. A query optimizer determines how to execute a query containing joins. A
query optimizer has two basic freedoms:

1. Join order: Because joins function commutatively and associatively, the


order in which the system joins tables does not change the final result-set of
the query. However, join-order does have an enormous impact on the cost of
the join operation, so choosing the best join order becomes very important.
2. Join method: Given two tables and a join condition, multiple algorithms can
produce the result-set of the join. Which algorithm runs most efficiently
depends on the sizes of the input tables, the number of rows from each table
that match the join condition, and the operations required by the rest of the
query.

Many join-algorithms treat their inputs differently. One can refer to the inputs to a join as the
"outer" and "inner" join operands, or "left" and "right", respectively. In the case of nested loops,
for example, the database system will scan the entire inner relation for each row of the outer
relation.

One can classify query-plans involving joins as follows:[4]

left-deep

using a base table (rather than another join) as the inner operand of each join
in the plan

right-deep

using a base table as the outer operand of each join in the plan
bushy

neither left-deep nor right-deep; both inputs to a join may themselves result
from joins

These names derive from the appearance of the query plan if drawn as a tree, with the outer join
relation on the left and the inner relation on the right (as convention dictates).

[edit] Join algorithms

Three fundamental algorithms exist for performing a join operation.

Potrebbero piacerti anche