SQL - Semijoins

> (Data|State) Management and Processing > (Data Type|Data Structure) > (Relation|Table) - Tabular data > Structured Query Language (SQL)

1 - About

A semijoin returns rows that match an EXISTS subquery without duplicating rows from the left side of the predicate when multiple rows on the right side satisfy the criteria of the subquery.

Semijoin and antijoin transformation cannot be done if the subquery is on an OR branch of the WHERE clause.

A semi-join is useful when a subquery is introduced using the EXISTS or IN operator. A semi-join allows to convert the EXISTS subquery into a join. This option is called a semi-join because, unlike a regular join, a single row only is returned from the driving table even if multiple matching rows exist in the join table.

Advertising

3 - Semijoins and Oracle

To encourage Oracle to perform a semi-join, add the HASH SEMI-JOIN or the MERGE SEMI-JOIN hint to the subquery.

4 - Example

table1
(inner set)
table2
(outer set)
Column ID Column ID Column ID_2
A A
B B A
D C C
[email protected]>SELECT table1.id "ID_table1"
  2    FROM table1
  3   WHERE EXISTS ( SELECT * FROM table2 WHERE table1.Id = table2.Id );
 
ID_table1
----------
A
B

A and B are present in the table1 and in the table2.