开发者

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

开发者 https://www.devze.com 2023-02-09 08:43 出处:网络
I have an integer colu开发者_如何学Gomn and I need to search for rows in which the said column starts with 19

I have an integer colu开发者_如何学Gomn 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%'

ERROR:  operator does not exist: integer ~~ unknown
LINE 1: select * from "table" where "id" like '19%'


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%'


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

精彩评论

暂无评论...
验证码 换一张
取 消