“SELECT TOP 1 1” VS “IF EXISTS(SELECT 1”

前端 未结 5 1704
有刺的猬
有刺的猬 2020-12-29 18:29

I have some .NET code that checks for the existence of a SQL record at a moderately-high interval. I am looking to make this check as \"cheap\" as possible.

I\'m wo

相关标签:
5条回答
  • 2020-12-29 19:01

    I'd recommend IF EXISTS(SELECT * ...), unless this is actually causing a performance issue. It expresses the intent of the query in a much better understood fashion than alternatives.

    I'd avoid COUNT(*) (as in the current answers) unless you actually need the count of rows from the table.

    If you want the "efficiency" of checking the rowcount from the result, I'd probably go for:

    select 1 where exists(select * from BigTable where SomeColumn=200)
    

    Which produces the same result set as your second query (either 0 or 1 row)

    0 讨论(0)
  • 2020-12-29 19:06

    This is what you want instead of the IF statement

      SELECT ISNULL(
         (SELECT TOP 1 1 FROM BigTable where SomeCol = 200), 0);
    
    0 讨论(0)
  • 2020-12-29 19:12

    Makes no difference at all, exists will not even evaluate the select portion of your statement. So, use the one you like.

    declare @test table (name varchar(20))
    
    -- comment out inserts for testing.
    insert into @test (name) values ('bob the builder')
    insert into @test (name) values ('bob the builder')
    
    -- for giggles, put 1/0 here. You'll find that divide by zero error.
    select 1 from @test
    
    -- notice that you don't receive a divide by zero error.
    -- the bit in the select portion is never executed, ever.
    if not exists (select 1/0 from @test) select 'Yay!'
    if     exists (select 1/0 from @test) select 'Boo!'
    

    In fact you can use these interchangeably:

    ... select * ... 
    ... select 1 ... 
    ... select top 1 * ... 
    ... select top 1 1 ... 
    ... select 'John Jacob Jingleheimer Schmidt' ... 
    
    0 讨论(0)
  • 2020-12-29 19:13

    Not sure about SQL Server but in other databases the standard method is:

    SELECT COUNT(*) FROM BigTable where SomeCol = 200;
    

    Actual efficiency depends on your indexes etc.

    0 讨论(0)
  • 2020-12-29 19:14

    I would definitely go for the 2nd option:

    SELECT TOP 1 1
    FROM   BigTable
    WHERE  SomeColumn = 200 
    

    The execution plan is simpler and efficient even when I/O and CPU numbers are mostly the same.

    0 讨论(0)
提交回复
热议问题