Fastest way to determine if record exists

前端 未结 11 1090
清歌不尽
清歌不尽 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:38

    Nothing can beat -

    SELECT TOP 1 1 FROM products WHERE id = 'some value';
    

    You don't need to count to know if there is a data in table. And don't use alias when not necessary.

    0 讨论(0)
  • 2020-11-29 16:38

    You can also use

     If EXISTS (SELECT 1 FROM dbo.T1 WHERE T1.Name='Scot')
        BEGIN
             --<Do something>
        END 
    
    ELSE    
         BEGIN
           --<Do something>
         END
    
    0 讨论(0)
  • 2020-11-29 16:39

    SELECT TOP 1 products.id FROM products WHERE products.id = ?; will outperform all of your suggestions as it will terminate execution after it finds the first record.

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

    This approach returns a boolean for you.

    0 讨论(0)
  • 2020-11-29 16:47

    For those stumbling upon this from MySQL or Oracle background - MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses ROWNUM.

    0 讨论(0)
  • 2020-11-29 16:51
    create or replace procedure ex(j in number) as
    i number;
    begin
    select id into i from student where id=j;
    if i is not null then
    dbms_output.put_line('exists');
    end if;
    exception
       when no_data_found then
            dbms_output.put_line(i||' does not exists');
    
    end;
    
    0 讨论(0)
提交回复
热议问题