How to check if a value is a number in SQLite

后端 未结 9 2013
-上瘾入骨i
-上瘾入骨i 2020-12-10 14:29

I have a column that contains numbers and other string values (like \"?\", \"???\", etc.)

Is it possible to add an \"is number\" condition to the where clause in SQL

9条回答
  •  鱼传尺愫
    2020-12-10 15:11

    This answer is comprehensive and eliminates the shortcomings of all other answers. The only caveat is that it isn't sql standard... but neither is SQLite. If you manage to break this code please comment below, and I will patch it.

    Figured this out accidentally. You can check for equality with the CAST value.

    CASE   {TEXT_field}
        WHEN CAST({TEXT_field} AS INTEGER)                THEN 'Integer'     -- 'Number'
        WHEN CAST({TEXT_field} AS REAL)                   THEN 'Real'        -- 'Number'
        ELSE                                                   'Character'
    END
    

    OR

    CASE   
        WHEN {TEXT_field} = CAST({TEXT_field} AS INTEGER) THEN 'Integer'     --'Number'
        WHEN {TEXT_field} = CAST({TEXT_field} AS Real)    THEN 'Real'        --'Number'
        ELSE                                                   'Character'
    END
    

    (It's the same thing just different syntax.)

    • Note the order of execution. REAL must come after INTEGER.
    • Perhaps their is some implicit casting of values prior to checking for equality so that the right-side is re-CAST to TEXT before comparison to left-side.

    Updated for comment: @SimonWillison
    I have added a check for 'Real' values
    '1 frog' evaluated to 'Character' for me; which is correct
    '0' evaluated to 'Integer' for me; which is correct

    I am using SQLite version 3.31.1 with python sqlite3 version 2.6.0. The python element should not affect how a query executes.

提交回复
热议问题