Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANY or IF EXISTS in T-SQL

Tags:

I have a table which is a mapping between foreign ids and local ids.

I had to write a query to find out whether or not this table is a bijection. I came up with this

IF 1 <> ANY(
    SELECT COUNT(foreignId)
    FROM mappingTable
    GROUP BY localId
    )
BEGIN
    SELECT 'Oh noes!'
END

ELSE BEGIN
    SELECT 'Everything is fine.'
END

My supervisor took one look at this and grimaced, and told me I should have written this instead:

IF EXISTS(
    SELECT NULL
    FROM mappingTable
    GROUP BY localId
    HAVING COUNT(foreignId) <> 1
    )
BEGIN
    SELECT 'Oh noes!'
END

ELSE BEGIN
    SELECT 'Everything is fine.'
END

My question is simply which of these queries is better style. I'm pretty sure that they are equivalent.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!