How do I search for a range of integers in PostgreSQL?

前端 未结 2 721
天命终不由人
天命终不由人 2021-01-25 01:32

I have an integer column and I need to search for rows in which the said column starts with 19

In MySQL I would use SELECT ... WHERE id LIKE \'19%\'

相关标签:
2条回答
  • 2021-01-25 02:21

    For all positive integers >= 10, you can do this with no TEXT/VARCHAR necessary:

    SELECT * FROM "table"
    WHERE $1 = id / (10 ^ (floor(log(id)-1)))::integer
    

    You can index this, as well:

    CREATE INDEX idx_table_2_digits 
        ON "table" ( 10 / (id ^ (floor(log(id)-1)))::integer);
    

    The calculation basically works like this:

    1. Find the largest power of 10 that is less than a given ID (let's call it X).
    2. Drop the magnitude of X by one (since we want two digits)
    3. Raise 10 to the power of X and cast to the result to INTEGER type (to force last step to be a SQL DIV instead of floating-point division).
    4. DIV the original ID by the 10^x to get the first two digits.

    This algorithm could even be generalized into a function, f(x,y), where x is the id and y is the number of leading digits to return:

    # python-esque pseudocode:
    
    def integer_leading_digits (id, digits):
        if id < (10 * (digits - 1)):
            return -1        # error condition
        return id DIV int(10 ^ (floor(log(id)-(digits-1))))
    
    0 讨论(0)
  • 2021-01-25 02:31

    In Postgres LIKE is string compare only - that explains the error.

    You can explicitly cast the column to string though:

    select * from "table" where id::text like '19%'
    
    0 讨论(0)
提交回复
热议问题