-- Checking for errors using flags.
-- Another useful query is to see if the errors on moving (or
-- apparently moving) objects are correct. For example, it used to be that
-- some known QSOs were being flagged as moving objects. One way to look for
-- such objects is to compare the velocity to the error in velocity and see if
-- the "OBJECT1_MOVED" or "OBJECT2_BAD_MOVING_FIT" is set. 
-- This query introduces bitwise logic for flags, and uses the 'as' syntax to
-- make the query more readable. Note that if a flag is not set, the value
-- will be zero. If you want to ensure multiple flags are not set, you can
-- either check that each individually is zero, or their sum is zero.
--   (From Gordon Richards)

-- NOTE: This query times out (takes too long) without the "TOP 1000".

SELECT TOP 1000
  run,
  rerun,
  camcol,
  field,
  objID,
  ra, dec,
  rowv, colv,
  rowvErr, colvErr,
  i,
  (flags & dbo.fPhotoFlags('MOVED')) as MOVED,
  (flags & dbo.fPhotoFlags('BAD_MOVING_FIT')) as BAD_MOVING_FIT
FROM Galaxy
WHERE
  (flags & (dbo.fPhotoFlags('MOVED') + dbo.fPhotoFlags('BAD_MOVING_FIT'))) > 0
  and (rowv * rowv + colv * colv) >=
      (rowvErr * rowvErr + colvErr * colvErr)
