I show a grid with parent data and should show an icon if it has matching child rows. My DB is in SQL Server 2008. Let me simplify, I have the following two tables -
Order (PK: ID)
File (PK: FileID, FK: OrderID)
An Order may have zero or more files associated with it. The File table has an OrderID column that contains an FK link to Order . Now I am showing a grid in which all Orders are listed, and I want to display an icon image indicating whether this Order child lines (files) or not.
Here is the tricky way I experimented, but not sure how efficient / scalable it is -
SELECT DISTINCT o.ID, o.OrderNum, ... ,(CASE f.ID/f.ID WHEN 1 THEN 1 ELSE 0 END) as FilesExist ... FROM Order AS o LEFT OUTER JOIN dbo.FileHeader as f ON f.OrderID = o.ID
The CASE statement works just fine as required. It will return 1 if one or more files exist, otherwise 0. If there are several lines of the file, it will try to repeat the Order line for which I added DISTINCT, and I do not select f.ID but f.ID/f.ID , which will be 1 (it exists) and 0 for null (does not exist). I found out that JOINs are better than inline SELECT COUNT(*) .
I tested and works, but I need expert opinion and I need to make sure that this is the best way to do this. This is a very simple example, but my SELECT is complex, as there are many queries and getting it will be expensive, so I need to make sure it scales.
Thanks.
EDIT. # 1: In conclusion - either it will be an internal SELECT using COUNT (*)
SELECT c.ClaimNo,(SELECT COUNT(*) FROM dbo.FileHeader AS f WHERE f.ClaimID = c.ID ) AS FilesHExist FROM dbo.Claim AS c

or the LEFT OUTER JOIN approach that I mentioned.
SELECT DISTINCT c.ClaimNo, (CASE fh.ID / fh.ID WHEN 1 THEN 1 ELSE 0 END) AS FilesHExist FROM dbo.Claim AS c LEFT OUTER JOIN dbo.FileHeader AS fh ON fh.ClaimID = c.ID

Attached are two images of the query execution plan. Please suggest which one is better.