SQL – Return TRUE/FALSE if query rows returned

Here’s a little trick you can use to return TRUE/FALSE if a query has returned results.

For example if a Person is in Category_ID 325 or 326 we want TRUE, otherwise FALSE.

This trick uses the COUNT function to check for any returned rows then a CASE statement and CAST to return either TRUE or FALSE

SELECT
CASE WHEN COUNT( Person_ID ) >= 1 THEN 
     CAST( 1 as BIT ) 
ELSE 
      CAST( 0 as BIT )  
END As IsPersonCat
FROM T_Persons
WHERE Category_ID IN ( 325, 326 )

Tagged in

One comment on “SQL – Return TRUE/FALSE if query rows returned

  1. Nice, but it can be simplified to below as values > 0 are
    cast to 1

    select cast(count(Person_ID)
    as bit) isPersonCat
    from T_Persons
    where Category_ID in (325, 326)

Leave a Comment

Your email address will not be published. Required fields are marked *