Fastest way to determine if record exists

前端 未结 11 1091
清歌不尽
清歌不尽 2020-11-29 16:16

As the title suggests... I\'m trying to figure out the fastest way with the least overhead to determine if a record exists in a table or not.

Sample query:

相关标签:
11条回答
  • 2020-11-29 16:55

    EXISTS (or NOT EXISTS) is specially designed for checking if something exists and therefore should be (and is) the best option. It will halt on the first row that matches so it does not require a TOP clause and it does not actually select any data so there is no overhead in size of columns. You can safely use SELECT * here - no different than SELECT 1, SELECT NULL or SELECT AnyColumn... (you can even use an invalid expression like SELECT 1/0 and it will not break).

    IF EXISTS (SELECT * FROM Products WHERE id = ?)
    BEGIN
    --do what you need if exists
    END
    ELSE
    BEGIN
    --do what needs to be done if not
    END
    
    0 讨论(0)
  • 2020-11-29 17:00
    SELECT COUNT(*) FROM products WHERE products.id = ?;
    

    This is the cross relational database solution that works in all databases.

    0 讨论(0)
  • 2020-11-29 17:02

    Don't think anyone has mentioned it yet, but if you are sure the data won't change underneath you, you may want to also apply the NoLock hint to ensure it is not blocked when reading.

    SELECT CASE WHEN EXISTS (SELECT 1 
                         FROM dbo.[YourTable] WITH (NOLOCK)
                         WHERE [YourColumn] = [YourValue]) 
            THEN CAST (1 AS BIT) 
            ELSE CAST (0 AS BIT) END
    
    0 讨论(0)
  • 2020-11-29 17:02

    Below is the simplest and fastest way to determine if a record exists in database or not Good thing is it works in all Relational DB's

    SELECT distinct 1 products.id FROM products WHERE products.id = ?;
    
    0 讨论(0)
  • 2020-11-29 17:02

    I've used this in the past and it doesn't require a full table scan to see if something exists. It's super fast...

    UPDATE TableName SET column=value WHERE column=value
    IF @@ROWCOUNT=0
    BEGIN
         --Do work
    END             
    
    0 讨论(0)
提交回复
热议问题