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

前端 未结 5 1721
有刺的猬
有刺的猬 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)

提交回复
热议问题