Read our blogs, tips and tutorials
Try our exercises or test your skills
Watch our tutorial videos or shorts
Take a self-paced course
Read our recent newsletters
License our courseware
Book expert consultancy
Buy our publications
Get help in using our site
547 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owl trainers only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Search our website
We also send out useful tips in a monthly email newsletter ...
Written by Andy Brown
In this tutorial
A self-join is when a table contains a link to itself.
Occasionally in SQL Server you find a table which references itself. Here's an example:
In this table, each film contains a pointer to its sequel number.
Another typical example is where you have a table of employees, each of whose records contains a field pointing to that table's immediate line manager (themselves also records in the table).
The secret to a self-join is to create good aliases. Here's an example query for the table above showing for each book its immediate prequel and sequel:
-- show books with their prequels and sequels
SELECT
book.BookName AS Book,
prequel.BookName AS Prequel,
sequel.BookName AS sequel
FROM
tblBook AS book
LEFT OUTER JOIN tblBook AS prequel
ON prequel.SequelBookId=book.BookId
LEFT OUTER JOIN tblBook AS sequel
ON book.SequelBookId=sequel.BookId
ORDER BY
book.BookName
Here are the rows that this query would show:
The books, prequels and sequels from the above query.
Notice that by using aliases, we can effectively treat each instance of the tblBook table as if it were a different table.
You can learn more about this topic on the following Wise Owl courses:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2024. All Rights Reserved.