0
0
SQLquery~5 mins

Self join for hierarchical data in SQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a self join in SQL?
A self join is when a table is joined with itself to compare rows within the same table. It helps to find relationships between rows.
Click to reveal answer
beginner
Why use a self join for hierarchical data?
Because hierarchical data has parent-child relationships stored in the same table, a self join lets us connect each child row to its parent row.
Click to reveal answer
intermediate
Example: What does this SQL do?<br>
SELECT e1.name AS Employee, e2.name AS Manager FROM employees e1 LEFT JOIN employees e2 ON e1.manager_id = e2.id;
This query lists each employee with their manager's name by joining the employees table to itself using the manager_id to find the manager's record.
Click to reveal answer
beginner
What is the key column used in a self join for hierarchical data?
Usually, a column like 'parent_id' or 'manager_id' links a row to its parent row's 'id'. This column is used to join the table to itself.
Click to reveal answer
intermediate
Can a self join return rows without parents?
Yes, using a LEFT JOIN in a self join will include rows that have no parent (null parent_id), showing them with no matching parent row.
Click to reveal answer
What does a self join do in SQL?
ADeletes duplicate rows
BJoins two different tables
CJoins a table with itself
DCreates a new table
Which column is typically used to join in hierarchical data self joins?
AForeign key referencing parent row
BDate column
CRandom column
DPrimary key only
What type of join is best to include rows without parents in a self join?
AINNER JOIN
BRIGHT JOIN
CFULL JOIN
DLEFT JOIN
In a self join for employees and managers, what does the ON clause usually compare?
AManager ID to Employee ID
BEmployee ID to Manager ID
CEmployee ID to Employee ID
DManager ID to Manager ID
What kind of data is best suited for self joins?
AFlat data with no relationships
BHierarchical data with parent-child links
CData with no keys
DRandom unstructured data
Explain how a self join works to show parent-child relationships in hierarchical data.
Think about how one row points to another row in the same table.
You got /4 concepts.
    Describe how to write a SQL query using a self join to list employees with their managers.
    Use table aliases like e1 and e2 to distinguish roles.
    You got /4 concepts.