views:

45

answers:

2

I have next approximate tables structure:

accounts:
ID INT,
owner_id INT,
currency_id TINYINT

related to

clients:
ID INT

and

currency_types:
ID TINYINT,
name NVARCHAR(25)

I need to write a stored procedure to check existence of accounts with specific currency and all others, i.e. client can have accounts in specific currency, some other currencies and both.

I have already written this query:

SELECT
    ISNULL((
    SELECT 1
    WHERE EXISTS
    (
        SELECT 1
        FROM [accounts] AS A, [currency_types] AS CT
        WHERE
            A.[owner_id] = @client -- sp param
        AND A.[currency_id] = CT.[ID]
        AND CT.[name] = N'Ruble'
    )), 0) AS [ruble],
    ISNULL((
    SELECT 1
    WHERE EXISTS
    (    
        SELECT A.[ID]
        FROM [accounts] AS A, [currency_types] AS CT
        WHERE
            A.[owner_id] = @client 
        AND A.[currency_id] = CT.[ID]
        AND CT.[name] != N'Ruble'
    )), 0) AS [foreign]

Is it possible to optimize it? I'm new to (T)SQL, so thanks in advance!

+1  A: 

Seems pretty reasonable to me, EXISTS will give good performance for this kind of thing.

Do you have a reason for thinking it needs to be optimised? Is it performing badly?

The key thing to ensure is that you have suitable indexes (e.g. on accounts.[owner_id], CT.ID obviously is a PK)

AdaTheDev
@AdaTheDev: I'm new to SQL so just worry because query has 3 SELECTs.. and both WHERE conditions are very similar so maybe they could be split in something single but complex.
abatishchev
The outer select won't cost much at all (negligible). To achieve what you want, I actually think that approach is fine - can't see an easy way to achieve the same result. Complexity, usually makes things worse as it can make it harder for SQL Server to optimise the query as well
AdaTheDev
A: 

Such query requires one SELECT less:

RETURN ISNULL((SELECT 1
    WHERE
        EXISTS
        (
            SELECT 1
            FROM [accounts] AS A, [currency_types] AS CT
            WHERE
                A.[owner_id] = @client 
            AND A.[currency_id] = CT.[ID]
            AND CT.[name] != N'Ruble'

        )
    ), 0)
abatishchev