W3. SQL Self Join Flashcards
1
Q
Q: What is a SQL self join?
A
A: A self join is when a table is joined with itself.
2
Q
Q: Why are table aliases needed in a self join?
A
A: To differentiate between the two instances of the same table.
3
Q
Q: What is the syntax for a self join?
A
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
4
Q
Q: Write a query to match customers from the same city using a self join.
A
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;
5
Q
Q: What does A.CustomerID <> B.CustomerID ensure in a self join?
A
A: It ensures that the query does not match a customer with themselves.