Flash cards
Review the key moves
1/4
Core idea
What is the main idea behind SQL Self Join?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
1Quick choice
Which statement best captures the main point of this lesson?
2Fill blank
Complete the missing token from the example code.
___(s)3Order
Put the learning moves in the order that makes the concept easiest to apply.
T1 and T2 are different table aliases for the same table.
A self join is a regular join, but the table is joined with itself.
SQL Self Join Example
A self join is a regular join, but the table is joined with itself.
Self Join Syntax
SELECT
column_name(s)
FROM
table1 T1, table1 T2 WHERE
condition
;T1 and T2 are different table aliases for the same table.
Demo Database
Below is a selection from the "Customers" table:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
| 2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
| 3 | Antonio Moreno TaquerÃa | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
SQL Self Join Example
The following SQL statement matches customers that are from the same city:
Example
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2,
A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;