Solved

SQL Query to get orphaned nodes

Posted on 2014-11-11
4
213 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:jatkin
4 Comments
 
LVL 22

Accepted Solution

by:
Snarf0001 earned 250 total points
Comment Utility
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 250 total points
Comment Utility
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 32

Expert Comment

by:Stefan Hoffmann
Comment Utility
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:jatkin
Comment Utility
Perfect!!! Thanks :-)
Hope it is okay to split points equally as there was only 1 minute between posts!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article explains all about SQL Server Piecemeal Restore with examples in step by step manner.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Viewers will learn how the fundamental information of how to create a table.

772 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now