SQLite - getting number of rows in a database

后端 未结 6 1006
旧时难觅i
旧时难觅i 2020-12-24 00:57

I want to get a number of rows in my table using max(id). When it returns NULL - if there are no rows in the table - I want to return 0. And when t

6条回答
  •  情书的邮戳
    2020-12-24 01:16

    In SQL, NULL = NULL is false, you usually have to use IS NULL:

    SELECT CASE WHEN MAX(id) IS NULL THEN 0 ELSE (MAX(id) + 1) END FROM words
    

    But, if you want the number of rows, you should just use count(id) since your solution will give 10 if your rows are (0,1,3,5,9) where it should give 5.

    If you can guarantee you will always ids from 0 to N, max(id)+1 may be faster depending on the index implementation (it may be faster to traverse the right side of a balanced tree rather than traversing the whole tree, counting.

    But that's very implementation-specific and I would advise against relying on it, not least because it locks your performance to a specific DBMS.

提交回复
热议问题