SQL: How to properly check if a record exists

前端 未结 9 1300
粉色の甜心
粉色の甜心 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 02:18

    I'm using this way:

    IIF(EXISTS (SELECT TOP 1 1 
                    FROM Users 
                    WHERE FirstName = 'John'), 1, 0) AS DoesJohnExist
    
    0 讨论(0)
  • 2020-11-28 02:21

    You can use:

    SELECT COUNT(1) FROM MyTable WHERE ... 
    

    or

    WHERE [NOT] EXISTS 
    ( SELECT 1 FROM MyTable WHERE ... )
    

    This will be more efficient than SELECT * since you're simply selecting the value 1 for each row, rather than all the fields.

    There's also a subtle difference between COUNT(*) and COUNT(column name):

    • COUNT(*) will count all rows, including nulls
    • COUNT(column name) will only count non null occurrences of column name
    0 讨论(0)
  • 2020-11-28 02:21

    You can use:

    SELECT 1 FROM MyTable WHERE... LIMIT 1
    

    Use select 1 to prevent the checking of unnecessary fields.

    Use LIMIT 1 to prevent the checking of unnecessary rows.

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