SQL: How to properly check if a record exists

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

提交回复
热议问题