SQL: How to properly check if a record exists

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

提交回复
热议问题