Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

SQL Query to get orphaned nodes

Posted on 2014-11-11
4
Medium Priority
?
286 Views
Last Modified: 2014-11-11
Hi all,
I have an interesting query that I am trying to create...

I have a table that contains entities, each of these *may* have a parent (only single level)

What I would like to do is query the table to find entries that say they have a parent, but the parent entry does not exist.

tblData
ID, DESCRIPTION, PARENT
'A','Main Parent','-'
'B','First Child','A'
'C','Second Child','A'
'D','Another Parent','-'
'E','An Orphan','Z'

In this example, I would like to execute a query to get the record relating to 'E'

I've tried a few ways, but can't get it to work!!!

Any ideas would be very much appreciated..

Thanks a lot,

James
0
Comment
Question by:James Atkin
4 Comments
 
LVL 23

Accepted Solution

by:
Snarf0001 earned 1000 total points
ID: 40434781
select a.*
from tblData a
left join tblData b on a.Parent = b.ID
where a.Parent != '-' and b.ID is null

Open in new window

0
 
LVL 24

Assisted Solution

by:Phillip Burton
Phillip Burton earned 1000 total points
ID: 40434783
Try this:

Select T.ID
from tblData T
LEFT JOIN tblData U
on T.[Parent] = U.ID
where U.ID is null

Open in new window

0
 
LVL 36

Expert Comment

by:ste5an
ID: 40434792
You should use a foreign key constraint to avoid this situation.

SELECT  C.*
FROM    #tblData C
        LEFT JOIN #tblData P ON C.PARENT = P.ID
WHERE   P.ID IS NULL;

Open in new window

0
 
LVL 4

Author Closing Comment

by:James Atkin
ID: 40434793
Perfect!!! Thanks :-)
Hope it is okay to split points equally as there was only 1 minute between posts!
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Ready to get certified? Check out some courses that help you prepare for third-party exams.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

971 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question