How smart is SELECT TOP 1?

  • SQL Server Express 2008 R2, called from an Access front end.

    I have a number of situations where I need to look at the results of a query and do something based on whether there are or are not any records in the resultset. I have tried SELECT TOP 1, but this seems to assemble the entire resultset first and then select only the first 1 (I think, anyway, I'm not that good at reading execution plans yet). Some of the queries return a large number of records and the resulting delay from calling them twice seems unnecessary to me.

    I only want to know if there are or are not any records at all in the result and would like SQL Server to stop processing as soon as it can say "YES" to that question. Is SELECT TOP 1 the right approach or is there some better way to accomplish this? Is it even possible?

  • Typically to see if there are any rows you would use EXISTS.

    IF EXISTS (SELECT 1 FROM <SomeTable>)

    BEGIN

    -- Some processing

    END

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • GilaMonster (12/31/2010)


    Typically to see if there are any rows you would use EXISTS.

    IF EXISTS (SELECT 1 FROM <SomeTable>)

    BEGIN

    -- Some processing

    END

    Yes, that was it - response time is instant.

    Thank you.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply