SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL GROUP BY SQL Having SQL In SQL INSERT INTO SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL ORDER BY SQL Select SQL Select Into SQL Top Limit Fetch SQL Stored Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL Backup Database SQL Check SQL Constraints SQL Create View SQL Create Database SQL Create Table SQL Data types SQL Dates SQL Default Constraint SQL Drop Database SQL Drop Table SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL Self Join

A self join joins a table to itself. It is useful when rows in the same table are related to other rows from that same table, such as employees and managers, categories and parent categories, or people and referrals.

Syntax

SELECT a.column_name, b.column_name
FROM table_name AS a
JOIN table_name AS b
    ON a.related_column = b.id;

The aliases are required in practice. Without aliases, the query has no clear way to know which copy of the table you mean.

Example

List employees with the name of their manager:

SELECT employee.name AS employee_name,
       manager.name AS manager_name
FROM employees AS employee
LEFT JOIN employees AS manager
    ON employee.manager_id = manager.employee_id;

Expected result

employee_namemanager_name
AnaMarcos
MarcosNULL
RaviAna

The LEFT JOIN keeps employees even when they do not have a manager. That is common for the top person in an organization chart.

Common mistakes

Related topics

Continue with SQL JOIN, SQL LEFT JOIN, SQL Aliases and the SQL Formatter.