-- Galaxies unsaturated near (given) coordinates.
--
-- Find galaxies without saturated pixels within 1' of a given point.
-- ra=185.0, dec=-0.5. This query uses a function fGetNearbyObjEq,
-- which takes 3 arguments (ra,dec, distance in arcmin); this function uses
-- the Neighbors table. The Neighbors table and the Galaxy table have in
-- common the objID, so we have to select objects from both where the objIDs
-- are the same. The output of the function is a table with the Galaxy Object
-- ID and distance in arcmin from the input.  This query introduces the use of
-- a JOIN to combine table contents.  Also, we use the 'ORDER BY' syntax,
-- which will sort the output.

SELECT TOP 100 G.objID, GN.distance
FROM	Galaxy AS G
   JOIN	dbo.fGetNearbyObjEq(185.,-0.5, 1) AS GN -- this function outputs a table, so we have to do a join
	ON G.objID = GN.objID  			-- get objects from temporary neighbors table GN with desired ObjID
WHERE 
   (G.flags & dbo.fPhotoFlags('saturated')) = 0 -- and the object is not saturated. f.PhotoFlags is a function that interprets the flag bits.
ORDER BY distance 				-- sort these by distance
