SQL: How to properly check if a record exists

前端 未结 9 1299
粉色の甜心
粉色の甜心 2020-11-28 01:23

While reading some SQL Tuning-related documentation, I found this:

SELECT COUNT(*) :

  • Counts the number of rows.
  • Often is improper
相关标签:
9条回答
  • 2020-11-28 01:58

    Other option:

    SELECT CASE
        WHEN EXISTS (
            SELECT 1
            FROM [MyTable] AS [MyRecord])
        THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
    END
    
    0 讨论(0)
  • 2020-11-28 01:59

    It's better to use either of the following:

    -- Method 1.
    SELECT 1
    FROM table_name
    WHERE unique_key = value;
    
    -- Method 2.
    SELECT COUNT(1)
    FROM table_name
    WHERE unique_key = value;
    

    The first alternative should give you no result or one result, the second count should be zero or one.

    How old is the documentation you're using? Although you've read good advice, most query optimizers in recent RDBMS's optimize SELECT COUNT(*) anyway, so while there is a difference in theory (and older databases), you shouldn't notice any difference in practice.

    0 讨论(0)
  • 2020-11-28 02:03

    The other answers are quite good, but it would also be useful to add LIMIT 1 (or the equivalent, to prevent the checking of unnecessary rows.

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

    You can use:

    SELECT 1 FROM MyTable WHERE <MyCondition>
    

    If there is no record matching the condition, the resulted recordset is empty.

    0 讨论(0)
  • 2020-11-28 02:18

    I would prefer not use Count function at all:

    IF [NOT] EXISTS ( SELECT 1 FROM MyTable WHERE ... )
         <do smth>
    

    For example if you want to check if user exists before inserting it into the database the query can look like this:

    IF NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' )
    BEGIN
        INSERT INTO Users (FirstName, LastName) VALUES ('John', 'Smith')
    END
    
    0 讨论(0)
  • 2020-11-28 02:18
    SELECT COUNT(1) FROM MyTable WHERE ...
    

    will loop thru all the records. This is the reason it is bad to use for record existence.

    I would use

    SELECT TOP 1 * FROM MyTable WHERE ...
    

    After finding 1 record, it will terminate the loop.

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