SQL LIKE condition to check for integer?

后端 未结 8 773
温柔的废话
温柔的废话 2020-12-01 01:11

I am using a set of SQL LIKE conditions to go through the alphabet and list all items beginning with the appropriate letter, e.g. to get all books where the title starts wit

相关标签:
8条回答
  • 2020-12-01 01:33

    Which one of those is indexable?

    This one is definitely btree-indexable:

    WHERE title >= '0' AND title < ':'
    

    Note that ':' comes after '9' in ASCII.

    0 讨论(0)
  • 2020-12-01 01:34

    That will select (by a regex) every book which has a title starting with a number, is that what you want?

    SELECT * FROM books WHERE title ~ '^[0-9]'
    

    if you want integers which start with specific digits, you could use:

    SELECT * FROM books WHERE CAST(price AS TEXT) LIKE '123%'
    

    or use (if all your numbers have the same number of digits (a constraint would be useful then))

    SELECT * FROM books WHERE price BETWEEN 123000 AND 123999;
    
    0 讨论(0)
  • 2020-12-01 01:39

    Assuming that you're looking for "numbers that start with 7" rather than "strings that start with 7," maybe something like

    select * from books where convert(char(32), book_id) like '7%'
    

    Or whatever the Postgres equivalent of convert is.

    0 讨论(0)
  • 2020-12-01 01:42

    I'm late to the party here, but if you're dealing with integers of a fixed length you can just do integer comparison:

    SELECT * FROM books WHERE price > 89999 AND price < 90100;
    
    0 讨论(0)
  • 2020-12-01 01:43

    If you want to search as string, you can cast to text like this:

    SELECT * FROM books WHERE price::TEXT LIKE '123%'
    
    0 讨论(0)
  • 2020-12-01 01:49

    Tested on PostgreSQL 9.5 :

    -- only digits

    select * from books where title ~ '^[0-9]*$';
    

    or,

    select * from books where title SIMILAR TO '[0-9]*';
    

    -- start with digit

    select * from books where title ~ '^[0-9]+';
    
    0 讨论(0)
提交回复
热议问题