SQL: How to properly check if a record exists

前端 未结 9 1337
粉色の甜心
粉色の甜心 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

    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.

提交回复
热议问题